provider.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import os
  2. import shutil
  3. from abc import ABC, abstractmethod
  4. from typing import BinaryIO, Tuple
  5. import boto3
  6. from botocore.exceptions import ClientError
  7. from open_webui.config import (
  8. S3_ACCESS_KEY_ID,
  9. S3_BUCKET_NAME,
  10. S3_ENDPOINT_URL,
  11. S3_REGION_NAME,
  12. S3_SECRET_ACCESS_KEY,
  13. STORAGE_PROVIDER,
  14. UPLOAD_DIR,
  15. )
  16. from open_webui.constants import ERROR_MESSAGES
  17. class StorageProvider(ABC):
  18. @abstractmethod
  19. def get_file(self, file_path: str) -> str:
  20. pass
  21. @abstractmethod
  22. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  23. pass
  24. @abstractmethod
  25. def delete_all_files(self) -> None:
  26. pass
  27. @abstractmethod
  28. def delete_file(self, file_path: str) -> None:
  29. pass
  30. class LocalStorageProvider(StorageProvider):
  31. @staticmethod
  32. def upload_file(file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  33. contents = file.read()
  34. if not contents:
  35. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  36. file_path = f"{UPLOAD_DIR}/{filename}"
  37. with open(file_path, "wb") as f:
  38. f.write(contents)
  39. return contents, file_path
  40. @staticmethod
  41. def get_file(file_path: str) -> str:
  42. """Handles downloading of the file from local storage."""
  43. return file_path
  44. @staticmethod
  45. def delete_file(file_path: str) -> None:
  46. """Handles deletion of the file from local storage."""
  47. filename = file_path.split("/")[-1]
  48. file_path = f"{UPLOAD_DIR}/{filename}"
  49. if os.path.isfile(file_path):
  50. os.remove(file_path)
  51. else:
  52. print(f"File {file_path} not found in local storage.")
  53. @staticmethod
  54. def delete_all_files() -> None:
  55. """Handles deletion of all files from local storage."""
  56. if os.path.exists(UPLOAD_DIR):
  57. for filename in os.listdir(UPLOAD_DIR):
  58. file_path = os.path.join(UPLOAD_DIR, filename)
  59. try:
  60. if os.path.isfile(file_path) or os.path.islink(file_path):
  61. os.unlink(file_path) # Remove the file or link
  62. elif os.path.isdir(file_path):
  63. shutil.rmtree(file_path) # Remove the directory
  64. except Exception as e:
  65. print(f"Failed to delete {file_path}. Reason: {e}")
  66. else:
  67. print(f"Directory {UPLOAD_DIR} not found in local storage.")
  68. class S3StorageProvider(StorageProvider):
  69. def __init__(self):
  70. self.s3_client = boto3.client(
  71. "s3",
  72. region_name=S3_REGION_NAME,
  73. endpoint_url=S3_ENDPOINT_URL,
  74. aws_access_key_id=S3_ACCESS_KEY_ID,
  75. aws_secret_access_key=S3_SECRET_ACCESS_KEY,
  76. )
  77. self.bucket_name = S3_BUCKET_NAME
  78. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  79. """Handles uploading of the file to S3 storage."""
  80. _, file_path = LocalStorageProvider.upload_file(file, filename)
  81. try:
  82. self.s3_client.upload_file(file_path, self.bucket_name, filename)
  83. return (
  84. open(file_path, "rb").read(),
  85. "s3://" + self.bucket_name + "/" + filename,
  86. )
  87. except ClientError as e:
  88. raise RuntimeError(f"Error uploading file to S3: {e}")
  89. def get_file(self, file_path: str) -> str:
  90. """Handles downloading of the file from S3 storage."""
  91. try:
  92. bucket_name, key = file_path.split("//")[1].split("/")
  93. local_file_path = f"{UPLOAD_DIR}/{key}"
  94. self.s3_client.download_file(bucket_name, key, local_file_path)
  95. return local_file_path
  96. except ClientError as e:
  97. raise RuntimeError(f"Error downloading file from S3: {e}")
  98. def delete_file(self, file_path: str) -> None:
  99. """Handles deletion of the file from S3 storage."""
  100. filename = file_path.split("/")[-1]
  101. try:
  102. self.s3_client.delete_object(Bucket=self.bucket_name, Key=filename)
  103. except ClientError as e:
  104. raise RuntimeError(f"Error deleting file from S3: {e}")
  105. # Always delete from local storage
  106. LocalStorageProvider.delete_file(file_path)
  107. def delete_all_files(self) -> None:
  108. """Handles deletion of all files from S3 storage."""
  109. try:
  110. response = self.s3_client.list_objects_v2(Bucket=self.bucket_name)
  111. if "Contents" in response:
  112. for content in response["Contents"]:
  113. self.s3_client.delete_object(
  114. Bucket=self.bucket_name, Key=content["Key"]
  115. )
  116. except ClientError as e:
  117. raise RuntimeError(f"Error deleting all files from S3: {e}")
  118. # Always delete from local storage
  119. LocalStorageProvider.delete_all_files()
  120. def get_storage_provider(storage_provider: str):
  121. if storage_provider == "local":
  122. Storage = LocalStorageProvider()
  123. elif storage_provider == "s3":
  124. Storage = S3StorageProvider()
  125. else:
  126. raise RuntimeError(f"Unsupported storage provider: {storage_provider}")
  127. return Storage
  128. Storage = get_storage_provider(STORAGE_PROVIDER)