feat(ks3): add KS3 object storage support
Add Kingsoft Cloud KS3 as a supported storage provider, including backend service implementation, storage config UI, and provider scheme recognition throughout the codebase.
This commit is contained in:
@@ -126,6 +126,17 @@ func NewFileServiceFromStorageConfig(
|
||||
}
|
||||
return svc, p, err
|
||||
|
||||
case "ks3":
|
||||
if sec == nil || sec.KS3 == nil || sec.KS3.Endpoint == "" || sec.KS3.Region == "" || sec.KS3.AccessKey == "" || sec.KS3.SecretKey == "" || sec.KS3.BucketName == "" {
|
||||
return nil, p, fmt.Errorf("incomplete ks3 config")
|
||||
}
|
||||
pathPrefix := strings.TrimSpace(sec.KS3.PathPrefix)
|
||||
if pathPrefix == "" {
|
||||
pathPrefix = "weknora/"
|
||||
}
|
||||
svc, err := NewKS3FileService(sec.KS3.Endpoint, sec.KS3.Region, sec.KS3.AccessKey, sec.KS3.SecretKey, sec.KS3.BucketName, pathPrefix)
|
||||
return svc, p, err
|
||||
|
||||
default:
|
||||
return nil, p, fmt.Errorf("unsupported provider %q", p)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/google/uuid"
|
||||
ks3aws "github.com/ks3sdklib/aws-sdk-go/aws"
|
||||
"github.com/ks3sdklib/aws-sdk-go/aws/credentials"
|
||||
ks3s3 "github.com/ks3sdklib/aws-sdk-go/service/s3"
|
||||
)
|
||||
|
||||
const ks3Scheme = "ks3://"
|
||||
|
||||
// ks3FileService implements FileService for Kingsoft Cloud KS3.
|
||||
// KS3 uses V2 signing by default and virtual-hosted style addressing,
|
||||
// so it cannot be handled by the generic S3 provider without workarounds.
|
||||
type ks3FileService struct {
|
||||
client *ks3s3.S3
|
||||
bucketName string
|
||||
pathPrefix string
|
||||
}
|
||||
|
||||
// NewKS3FileService creates a KS3 file service and ensures the bucket exists.
|
||||
func NewKS3FileService(endpoint, region, accessKey, secretKey, bucketName, pathPrefix string) (interfaces.FileService, error) {
|
||||
client, err := newKS3Client(endpoint, region, accessKey, secretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pathPrefix = strings.Trim(pathPrefix, "/")
|
||||
|
||||
svc := &ks3FileService{
|
||||
client: client,
|
||||
bucketName: bucketName,
|
||||
pathPrefix: pathPrefix,
|
||||
}
|
||||
|
||||
if err := ensureKS3Bucket(client, bucketName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
func newKS3Client(endpoint, region, accessKey, secretKey string) (*ks3s3.S3, error) {
|
||||
creds := credentials.NewStaticCredentials(accessKey, secretKey, "")
|
||||
client := ks3s3.New(&ks3aws.Config{
|
||||
Credentials: creds,
|
||||
Region: region,
|
||||
Endpoint: endpoint,
|
||||
DisableSSL: false,
|
||||
S3ForcePathStyle: false, // KS3 uses virtual-hosted style
|
||||
SignerVersion: "V2", // KS3 recommends V2 signing
|
||||
MaxRetries: 3,
|
||||
})
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func ensureKS3Bucket(client *ks3s3.S3, bucketName string) error {
|
||||
_, err := client.HeadBucket(&ks3s3.HeadBucketInput{
|
||||
Bucket: ks3aws.String(bucketName),
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
// Bucket doesn't exist, try to create it
|
||||
_, createErr := client.CreateBucket(&ks3s3.CreateBucketInput{
|
||||
Bucket: ks3aws.String(bucketName),
|
||||
})
|
||||
if createErr != nil {
|
||||
return fmt.Errorf("failed to create KS3 bucket %q: %w", bucketName, createErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckKS3Connectivity tests KS3 connectivity using the provided credentials.
|
||||
func CheckKS3Connectivity(ctx context.Context, endpoint, region, accessKey, secretKey, bucketName string) error {
|
||||
client, err := newKS3Client(endpoint, region, accessKey, secretKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := client.HeadBucket(&ks3s3.HeadBucketInput{
|
||||
Bucket: ks3aws.String(bucketName),
|
||||
})
|
||||
done <- err
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case err := <-done:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func joinKS3Key(parts ...string) string {
|
||||
filtered := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
p = strings.Trim(p, "/")
|
||||
if p != "" {
|
||||
filtered = append(filtered, p)
|
||||
}
|
||||
}
|
||||
return strings.Join(filtered, "/")
|
||||
}
|
||||
|
||||
func parseKS3FilePath(filePath string) (bucket, objectKey string, err error) {
|
||||
if !strings.HasPrefix(filePath, ks3Scheme) {
|
||||
return "", "", fmt.Errorf("invalid KS3 file path: %s", filePath)
|
||||
}
|
||||
rest := strings.TrimPrefix(filePath, ks3Scheme)
|
||||
parts := strings.SplitN(rest, "/", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return "", "", fmt.Errorf("invalid KS3 file path: %s", filePath)
|
||||
}
|
||||
return parts[0], parts[1], nil
|
||||
}
|
||||
|
||||
func (s *ks3FileService) SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error) {
|
||||
ext := filepath.Ext(file.Filename)
|
||||
objectKey := joinKS3Key(s.pathPrefix, fmt.Sprintf("%d", tenantID), knowledgeID, uuid.New().String()+ext)
|
||||
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
contentType := file.Header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
contentType = utils.GetContentTypeByExt(ext)
|
||||
}
|
||||
|
||||
_, err = s.client.PutObject(&ks3s3.PutObjectInput{
|
||||
Bucket: ks3aws.String(s.bucketName),
|
||||
Key: ks3aws.String(objectKey),
|
||||
Body: src,
|
||||
ContentType: ks3aws.String(contentType),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to upload file to KS3: %w", err)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s%s/%s", ks3Scheme, s.bucketName, objectKey), nil
|
||||
}
|
||||
|
||||
func (s *ks3FileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
|
||||
safeName, err := utils.SafeFileName(fileName)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid file name: %w", err)
|
||||
}
|
||||
ext := filepath.Ext(safeName)
|
||||
objectKey := joinKS3Key(s.pathPrefix, fmt.Sprintf("%d", tenantID), "exports", uuid.New().String()+ext)
|
||||
|
||||
_, err = s.client.PutObject(&ks3s3.PutObjectInput{
|
||||
Bucket: ks3aws.String(s.bucketName),
|
||||
Key: ks3aws.String(objectKey),
|
||||
Body: bytes.NewReader(data),
|
||||
ContentType: ks3aws.String(utils.GetContentTypeByExt(ext)),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to upload bytes to KS3: %w", err)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s%s/%s", ks3Scheme, s.bucketName, objectKey), nil
|
||||
}
|
||||
|
||||
func (s *ks3FileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
|
||||
_, objectKey, err := parseKS3FilePath(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := utils.SafeObjectKey(objectKey); err != nil {
|
||||
return nil, fmt.Errorf("invalid file path: %w", err)
|
||||
}
|
||||
|
||||
resp, err := s.client.GetObject(&ks3s3.GetObjectInput{
|
||||
Bucket: ks3aws.String(s.bucketName),
|
||||
Key: ks3aws.String(objectKey),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get file from KS3: %w", err)
|
||||
}
|
||||
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
func (s *ks3FileService) DeleteFile(ctx context.Context, filePath string) error {
|
||||
_, objectKey, err := parseKS3FilePath(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := utils.SafeObjectKey(objectKey); err != nil {
|
||||
return fmt.Errorf("invalid file path: %w", err)
|
||||
}
|
||||
|
||||
_, err = s.client.DeleteObject(&ks3s3.DeleteObjectInput{
|
||||
Bucket: ks3aws.String(s.bucketName),
|
||||
Key: ks3aws.String(objectKey),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete file from KS3: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ks3FileService) CheckConnectivity(ctx context.Context) error {
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := s.client.HeadBucket(&ks3s3.HeadBucketInput{
|
||||
Bucket: ks3aws.String(s.bucketName),
|
||||
})
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case err := <-done:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ks3FileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
|
||||
_, objectKey, err := parseKS3FilePath(filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := utils.SafeObjectKey(objectKey); err != nil {
|
||||
return "", fmt.Errorf("invalid file path: %w", err)
|
||||
}
|
||||
|
||||
url, err := s.client.GeneratePresignedUrl(&ks3s3.GeneratePresignedUrlInput{
|
||||
Bucket: ks3aws.String(s.bucketName),
|
||||
Key: ks3aws.String(objectKey),
|
||||
HTTPMethod: ks3s3.HTTPMethod("GET"),
|
||||
Expires: int64((24 * time.Hour).Seconds()),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to generate KS3 presigned URL: %w", err)
|
||||
}
|
||||
|
||||
return url, nil
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
|
||||
const storageAllowListEnv = "STORAGE_ALLOW_LIST"
|
||||
|
||||
var supportedStorageProviders = []string{"local", "minio", "cos", "tos", "s3", "oss"}
|
||||
var supportedStorageProviders = []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3"}
|
||||
|
||||
func getSupportedStorageProviders() []string {
|
||||
providers := make([]string, len(supportedStorageProviders))
|
||||
|
||||
@@ -432,6 +432,17 @@ func (h *SystemHandler) isOSSConfigured(c *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// isKS3Configured checks whether KS3 connection info is available from tenant config.
|
||||
func (h *SystemHandler) isKS3Configured(c *gin.Context) bool {
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.KS3 != nil {
|
||||
ks3Conf := tenant.StorageEngineConfig.KS3
|
||||
return ks3Conf.Endpoint != "" && ks3Conf.Region != "" && ks3Conf.AccessKey != "" && ks3Conf.SecretKey != "" && ks3Conf.BucketName != ""
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isTOSEnvAvailable checks whether TOS env vars are set.
|
||||
func (h *SystemHandler) isTOSEnvAvailable() bool {
|
||||
return os.Getenv("TOS_ENDPOINT") != "" &&
|
||||
@@ -443,7 +454,7 @@ func (h *SystemHandler) isTOSEnvAvailable() bool {
|
||||
|
||||
// StorageEngineStatusItem describes one storage engine's availability and description.
|
||||
type StorageEngineStatusItem struct {
|
||||
Name string `json:"name"` // "local", "minio", "cos", "tos"
|
||||
Name string `json:"name"` // "local", "minio", "cos", "tos"
|
||||
Allowed bool `json:"allowed"`
|
||||
Available bool `json:"available"` // whether the engine can be used
|
||||
Description string `json:"description"` // short description for UI
|
||||
@@ -470,6 +481,7 @@ func (h *SystemHandler) GetStorageEngineStatus(c *gin.Context) {
|
||||
tosConfigured := h.isTOSConfigured(c)
|
||||
s3Configured := h.isS3Configured(c)
|
||||
ossConfigured := h.isOSSConfigured(c)
|
||||
ks3Configured := h.isKS3Configured(c)
|
||||
allowed := getAllowedStorageProviders()
|
||||
allowedProviders := make([]string, 0, len(supportedStorageProviders))
|
||||
for _, provider := range getSupportedStorageProviders() {
|
||||
@@ -484,6 +496,7 @@ func (h *SystemHandler) GetStorageEngineStatus(c *gin.Context) {
|
||||
{Name: "tos", Allowed: allowed["tos"], Available: tosConfigured, Description: "火山引擎对象存储服务,适合公有云部署"},
|
||||
{Name: "s3", Allowed: allowed["s3"], Available: s3Configured, Description: "AWS S3 与兼容对象存储服务,适合公有云与混合云部署"},
|
||||
{Name: "oss", Allowed: allowed["oss"], Available: ossConfigured, Description: "阿里云对象存储服务,适合公有云部署,支持 S3 兼容协议"},
|
||||
{Name: "ks3", Allowed: allowed["ks3"], Available: ks3Configured, Description: "金山云对象存储服务,适合公有云部署"},
|
||||
}
|
||||
c.JSON(200, gin.H{
|
||||
"code": 0,
|
||||
@@ -586,12 +599,13 @@ func isBlockedStorageEndpoint(endpoint string) (bool, string) {
|
||||
|
||||
// StorageCheckRequest is the body for POST /system/storage-engine-check.
|
||||
type StorageCheckRequest struct {
|
||||
Provider string `json:"provider"` // "minio", "cos", "tos", "s3", "oss"
|
||||
Provider string `json:"provider"` // "minio", "cos", "tos", "s3", "oss", "ks3"
|
||||
MinIO *types.MinIOEngineConfig `json:"minio,omitempty"`
|
||||
COS *types.COSEngineConfig `json:"cos,omitempty"`
|
||||
TOS *types.TOSEngineConfig `json:"tos,omitempty"`
|
||||
S3 *types.S3EngineConfig `json:"s3,omitempty"`
|
||||
OSS *types.OSSEngineConfig `json:"oss,omitempty"`
|
||||
KS3 *types.KS3EngineConfig `json:"ks3,omitempty"`
|
||||
}
|
||||
|
||||
// StorageCheckResponse is the response for a single-engine connectivity check.
|
||||
@@ -634,6 +648,8 @@ func (h *SystemHandler) CheckStorageEngine(c *gin.Context) {
|
||||
h.checkS3(c, ctx, req.S3)
|
||||
case "oss":
|
||||
h.checkOSS(c, ctx, req.OSS)
|
||||
case "ks3":
|
||||
h.checkKS3(c, ctx, req.KS3)
|
||||
default:
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: "本地存储无需检测"}})
|
||||
}
|
||||
@@ -867,6 +883,42 @@ func (h *SystemHandler) checkOSS(c *gin.Context, ctx context.Context, cfg *types
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: fmt.Sprintf("连接成功,Bucket「%s」已确认存在", cfg.BucketName)}})
|
||||
}
|
||||
|
||||
func (h *SystemHandler) checkKS3(c *gin.Context, ctx context.Context, cfg *types.KS3EngineConfig) {
|
||||
if cfg == nil {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "未提供 KS3 配置"}})
|
||||
return
|
||||
}
|
||||
|
||||
endpoint, region, accessKey, secretKey := cfg.Endpoint, cfg.Region, cfg.AccessKey, cfg.SecretKey
|
||||
if endpoint == "" || region == "" || accessKey == "" || secretKey == "" || cfg.BucketName == "" {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Endpoint、Region、Access Key、Secret Key、Bucket 名称不能为空"}})
|
||||
return
|
||||
}
|
||||
|
||||
if blocked, reason := isBlockedStorageEndpoint(endpoint); blocked {
|
||||
logger.Warnf(ctx, "Storage check: KS3 endpoint blocked by SSRF protection, endpoint: %s", endpoint)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}})
|
||||
return
|
||||
}
|
||||
|
||||
err := file.CheckKS3Connectivity(ctx, endpoint, region, accessKey, secretKey, cfg.BucketName)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Storage check: KS3 connectivity failed, bucket: %s, error: %v", cfg.BucketName, err)
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "403") || strings.Contains(errMsg, "AccessDenied") {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "认证失败,请检查 Access Key / Secret Key 是否正确"}})
|
||||
return
|
||||
}
|
||||
if strings.Contains(errMsg, "404") || strings.Contains(errMsg, "NoSuchBucket") {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Bucket「%s」不存在,请检查名称和 Region", cfg.BucketName)}})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: sanitizeStorageCheckError(err)}})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: fmt.Sprintf("连接成功,Bucket「%s」已确认存在", cfg.BucketName)}})
|
||||
}
|
||||
|
||||
func (h *SystemHandler) ResolveDocumentReader(ctx context.Context, addr string) interfaces.DocumentReader {
|
||||
if addr == "" {
|
||||
return h.documentReader
|
||||
|
||||
@@ -170,7 +170,7 @@ func (c ChunkingConfig) ResolveParserEngine(fileType string) string {
|
||||
// StorageProviderConfig stores the KB-level storage provider selection.
|
||||
// Credentials are managed at the tenant level (StorageEngineConfig).
|
||||
type StorageProviderConfig struct {
|
||||
Provider string `yaml:"provider" json:"provider"` // "local", "minio", "cos", "tos", "s3", "oss"
|
||||
Provider string `yaml:"provider" json:"provider"` // "local", "minio", "cos", "tos", "s3", "oss", "ks3"
|
||||
}
|
||||
|
||||
func (c StorageProviderConfig) Value() (driver.Value, error) {
|
||||
@@ -284,7 +284,7 @@ func InferStorageFromFilePath(filePath string) string {
|
||||
// e.g. "minio://bucket/key" → "minio", "local://tenant/file.pdf" → "local"
|
||||
// Returns "" if the path does not use a known provider scheme.
|
||||
func ParseProviderScheme(filePath string) string {
|
||||
for _, provider := range []string{"local", "minio", "cos", "tos", "s3", "oss"} {
|
||||
for _, provider := range []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3"} {
|
||||
if strings.HasPrefix(filePath, provider+"://") {
|
||||
return provider
|
||||
}
|
||||
|
||||
@@ -402,16 +402,17 @@ func (c *ParserEngineConfig) Scan(value interface{}) error {
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, COS, TOS, S3, and OSS.
|
||||
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, COS, TOS, S3, OSS, and KS3.
|
||||
// Knowledge bases select which provider to use; parameters are read from here.
|
||||
type StorageEngineConfig struct {
|
||||
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos", "tos", "s3", "oss"
|
||||
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos", "tos", "s3", "oss", "ks3"
|
||||
Local *LocalEngineConfig `json:"local,omitempty"`
|
||||
MinIO *MinIOEngineConfig `json:"minio,omitempty"`
|
||||
COS *COSEngineConfig `json:"cos,omitempty"`
|
||||
TOS *TOSEngineConfig `json:"tos,omitempty"`
|
||||
S3 *S3EngineConfig `json:"s3,omitempty"`
|
||||
OSS *OSSEngineConfig `json:"oss,omitempty"`
|
||||
KS3 *KS3EngineConfig `json:"ks3,omitempty"`
|
||||
}
|
||||
|
||||
// LocalEngineConfig is for local file system storage (single-machine deployment only).
|
||||
@@ -474,6 +475,16 @@ type OSSEngineConfig struct {
|
||||
TempRegion string `json:"temp_region"`
|
||||
}
|
||||
|
||||
// KS3EngineConfig is for Kingsoft Cloud KS3 object storage.
|
||||
type KS3EngineConfig struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Region string `json:"region"`
|
||||
AccessKey string `json:"access_key"`
|
||||
SecretKey string `json:"secret_key"`
|
||||
BucketName string `json:"bucket_name"`
|
||||
PathPrefix string `json:"path_prefix"`
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface for StorageEngineConfig
|
||||
func (c *StorageEngineConfig) Value() (driver.Value, error) {
|
||||
if c == nil {
|
||||
|
||||
Reference in New Issue
Block a user