forked from ego-component/eoss
/
client.go
191 lines (177 loc) · 6.05 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package eos
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptrace"
"strings"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gotomicro/ego/core/elog"
"go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
const PackageName = "component.eoss"
// Client object storage client interface
type Client interface {
GetBucketName(ctx context.Context, key string) (string, error)
Get(ctx context.Context, key string, options ...GetOptions) (string, error)
GetBytes(ctx context.Context, key string, options ...GetOptions) ([]byte, error)
GetAsReader(ctx context.Context, key string, options ...GetOptions) (io.ReadCloser, error)
GetWithMeta(ctx context.Context, key string, attributes []string, options ...GetOptions) (io.ReadCloser, map[string]string, error)
GetAndDecompress(ctx context.Context, key string) (string, error)
GetAndDecompressAsReader(ctx context.Context, key string) (io.ReadCloser, error)
Put(ctx context.Context, key string, reader io.ReadSeeker, meta map[string]string, options ...PutOptions) error
PutAndCompress(ctx context.Context, key string, reader io.ReadSeeker, meta map[string]string, options ...PutOptions) error
Del(ctx context.Context, key string) error
DelMulti(ctx context.Context, keys []string) error
Head(ctx context.Context, key string, meta []string) (map[string]string, error)
ListObject(ctx context.Context, key string, prefix string, marker string, maxKeys int, delimiter string) ([]string, error)
SignURL(ctx context.Context, key string, expired int64, options ...SignOptions) (string, error)
Range(ctx context.Context, key string, offset int64, length int64) (io.ReadCloser, error)
Exists(ctx context.Context, key string) (bool, error)
Copy(ctx context.Context, srcKey, dstKey string, options ...CopyOption) error
}
func newStorage(name string, cfg *BucketConfig, logger *elog.Component) (Client, error) {
storageType := strings.ToLower(cfg.StorageType)
if storageType == StorageTypeOSS {
client, err := oss.New(cfg.Endpoint, cfg.AccessKeyID, cfg.AccessKeySecret)
if err != nil {
return nil, err
}
var ossClient *OSS
if cfg.Shards != nil && len(cfg.Shards) > 0 {
buckets := make(map[string]*oss.Bucket)
for _, v := range cfg.Shards {
bucket, err := client.Bucket(cfg.Bucket + "-" + v)
if err != nil {
return nil, err
}
for i := 0; i < len(v); i++ {
buckets[strings.ToLower(v[i:i+1])] = bucket
}
}
ossClient = &OSS{
Shards: buckets,
}
} else {
bucket, err := client.Bucket(cfg.Bucket)
if err != nil {
return nil, err
}
ossClient = &OSS{
Bucket: bucket,
}
}
ossClient.cfg = cfg
if cfg.EnableCompressor {
// 目前仅支持 gzip
if comp, ok := compressors[cfg.CompressType]; ok {
ossClient.compressor = comp
} else {
logger.Warn("unknown type", elog.String("name", cfg.CompressType))
}
}
return ossClient, nil
} else if storageType == StorageTypeS3 {
var config *aws.Config
// use minio
if cfg.S3ForcePathStyle {
config = &aws.Config{
Region: aws.String(cfg.Region),
DisableSSL: aws.Bool(!cfg.SSL),
Credentials: credentials.NewStaticCredentials(cfg.AccessKeyID, cfg.AccessKeySecret, ""),
Endpoint: aws.String(cfg.Endpoint),
S3ForcePathStyle: aws.Bool(true),
}
} else {
config = &aws.Config{
Region: aws.String(cfg.Region),
DisableSSL: aws.Bool(!cfg.SSL),
Credentials: credentials.NewStaticCredentials(cfg.AccessKeyID, cfg.AccessKeySecret, ""),
}
if cfg.Endpoint != "" {
config.Endpoint = aws.String(cfg.Endpoint)
}
}
if cfg.Debug {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody | aws.LogDebugWithSigning)
slog.Default().Enabled(context.Background(), slog.LevelDebug)
}
config.HTTPClient = &http.Client{
Timeout: time.Second * time.Duration(cfg.S3HttpTimeoutSecs),
}
var tp http.RoundTripper = createTransport(cfg)
if cfg.EnableMetricInterceptor {
tp = metricInterceptor(name, cfg, logger, tp)
}
if cfg.EnableTraceInterceptor {
tp = traceLogReqIdInterceptor(name, cfg, logger, tp)
if cfg.EnableClientTrace {
tp = otelhttp.NewTransport(tp,
otelhttp.WithClientTrace(func(ctx context.Context) *httptrace.ClientTrace {
return otelhttptrace.NewClientTrace(ctx)
}))
} else {
tp = otelhttp.NewTransport(tp)
}
}
tp = fixedInterceptor(name, cfg, logger, tp)
config.HTTPClient.Transport = tp
service := s3.New(session.Must(session.NewSession(config)))
var s3Client *S3
if cfg.Shards != nil && len(cfg.Shards) > 0 {
buckets := make(map[string]string)
for _, v := range cfg.Shards {
for i := 0; i < len(v); i++ {
buckets[strings.ToLower(v[i:i+1])] = cfg.Bucket + "-" + v
}
}
s3Client = &S3{
ShardsBucket: buckets,
client: service,
}
} else {
s3Client = &S3{
BucketName: cfg.Bucket,
client: service,
}
}
s3Client.cfg = cfg
if cfg.EnableCompressor {
// 目前仅支持 gzip
if comp, ok := compressors[cfg.CompressType]; ok {
s3Client.compressor = comp
} else {
logger.Warn("unknown type", elog.String("name", cfg.CompressType))
}
}
return s3Client, nil
} else {
return nil, fmt.Errorf("unknown StorageType:\"%s\", only supports oss,s3", cfg.StorageType)
}
}
func createTransport(config *BucketConfig) *http.Transport {
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: config.MaxIdleConns,
IdleConnTimeout: config.IdleConnTimeout,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DisableKeepAlives: !config.EnableKeepAlives,
MaxIdleConnsPerHost: config.MaxIdleConnsPerHost,
}
}