/
distribute_kodo.go
350 lines (286 loc) · 8.71 KB
/
distribute_kodo.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
Copyright 2021 The KodeRover Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package taskplugin
import (
"context"
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"go.uber.org/zap"
"github.com/koderover/zadig/v2/pkg/microservice/warpdrive/config"
"github.com/koderover/zadig/v2/pkg/microservice/warpdrive/core/service/taskplugin/s3"
"github.com/koderover/zadig/v2/pkg/microservice/warpdrive/core/service/types/task"
"github.com/koderover/zadig/v2/pkg/setting"
s3tool "github.com/koderover/zadig/v2/pkg/tool/s3"
)
// InitializeDistribute2S3TaskPlugin ...
func InitializeDistribute2S3TaskPlugin(taskType config.TaskType) TaskPlugin {
return &Distribute2S3TaskPlugin{
Name: taskType,
}
}
// Distribute2S3TaskPlugin Plugin name should be compatible with task type
type Distribute2S3TaskPlugin struct {
Name config.TaskType
Task *task.DistributeToS3
Log *zap.SugaredLogger
}
func (p *Distribute2S3TaskPlugin) SetAckFunc(func()) {
}
const (
// Distribute2S3TaskTimeout ...
Distribute2S3TaskTimeout = 60 * 10 // 10 minutes
)
// Init ...
func (p *Distribute2S3TaskPlugin) Init(jobname, filename string, xl *zap.SugaredLogger) {
// SetLogger ...
p.Log = xl
}
// Type ...
func (p *Distribute2S3TaskPlugin) Type() config.TaskType {
return p.Name
}
// Status ...
func (p *Distribute2S3TaskPlugin) Status() config.Status {
return p.Task.TaskStatus
}
// SetStatus ...
func (p *Distribute2S3TaskPlugin) SetStatus(status config.Status) {
p.Task.TaskStatus = status
}
// TaskTimeout ...
func (p *Distribute2S3TaskPlugin) TaskTimeout() int {
if p.Task.Timeout == 0 {
p.Task.Timeout = Distribute2S3TaskTimeout
}
return p.Task.Timeout
}
// 是否是kodo
func isKODO(storage *s3.S3) bool {
return strings.Contains(storage.Endpoint, "qiniucs.com")
}
func upload(ctx context.Context, log *zap.SugaredLogger, storage *s3.S3, localfile, destfile string) error {
if isKODO(storage) {
err := uploadFileToS3(storage.Ak, storage.Sk, storage.Bucket, destfile, localfile)
if err != nil {
log.Warnf("failed to upload file to s3 %s=>%s %v", localfile, destfile, err)
} else {
log.Infof("succeed to upload file to s3 %s=>%s", localfile, destfile)
}
return err
}
forcedPathStyle := true
if storage.Provider == setting.ProviderSourceAli {
forcedPathStyle = false
}
client, err := s3tool.NewClient(storage.Endpoint, storage.Ak, storage.Sk, storage.Region, storage.Insecure, forcedPathStyle)
if err != nil {
return err
}
objectKey := storage.GetObjectPath(destfile)
return client.Upload(storage.Bucket, localfile, objectKey)
}
// Run ...
func (p *Distribute2S3TaskPlugin) Run(ctx context.Context, pipelineTask *task.Task, pipelineCtx *task.PipelineCtx, serviceName string) {
var err error
defer func() {
if err != nil {
p.Task.TaskStatus = config.StatusFailed
p.Task.Error = err.Error()
}
}()
localFile := filepath.Join(pipelineCtx.DistDir, p.Task.PackageFile)
if _, err = os.Stat(localFile); os.IsNotExist(err) {
if pipelineTask.StorageURI == "" {
err = fmt.Errorf("no source storage found")
return
}
var srcStorage *s3.S3
srcStorage, err = s3.UnmarshalNewS3StorageFromEncrypted(pipelineTask.StorageURI)
if err != nil {
p.Log.Errorf("failed to init source s3 client")
return
}
if srcStorage.Subfolder != "" {
srcStorage.Subfolder = fmt.Sprintf("%s/%s/%d/%s", srcStorage.Subfolder, pipelineTask.PipelineName, pipelineTask.TaskID, "file")
} else {
srcStorage.Subfolder = fmt.Sprintf("%s/%d/%s", pipelineTask.PipelineName, pipelineTask.TaskID, "file")
}
var tmpFile *os.File
tmpFile, err = ioutil.TempFile("", "")
if err != nil {
p.Log.Errorf("failed to create tempfile %v", err)
return
}
_ = tmpFile.Close()
defer func() {
_ = os.Remove(tmpFile.Name())
}()
forcedPathStyle := true
if srcStorage.Provider == setting.ProviderSourceAli {
forcedPathStyle = false
}
var s3client *s3tool.Client
s3client, err = s3tool.NewClient(srcStorage.Endpoint, srcStorage.Ak, srcStorage.Sk, srcStorage.Region, srcStorage.Insecure, forcedPathStyle)
if err != nil {
p.Log.Errorf("failed to create s3 client source storage %s: %v", srcStorage.GetURI(), err)
return
}
objectKey := srcStorage.GetObjectPath(p.Task.PackageFile)
err = s3client.Download(srcStorage.Bucket, objectKey, tmpFile.Name())
if err != nil {
p.Log.Errorf("failed to download file from source storage %s: %v", srcStorage.GetURI(), err)
return
}
localFile = tmpFile.Name()
}
var destStorage *s3.S3
destStorage, err = s3.UnmarshalNewS3StorageFromEncrypted(p.Task.DestStorageURL)
if err != nil {
p.Log.Errorf("failed to init destination s3 client %v", err)
return
}
p.Log.Infof("upload package file %s to s3\n", p.Task.PackageFile)
p.Log.Infof("upload file %s to bucket %s/%s", p.Task.PackageFile, destStorage.Bucket, destStorage.Subfolder)
remoteFileKey := filepath.Join(
"/", pipelineTask.ProductName,
p.Task.ServiceName,
fmt.Sprintf("%d", pipelineTask.TaskID))
if isKODO(destStorage) {
remoteFileKey = filepath.Join(remoteFileKey, p.Task.PackageFile)
}
if destStorage.Subfolder != "" {
destStorage.Subfolder = fmt.Sprintf("%s/%s", destStorage.Subfolder, remoteFileKey)
} else {
destStorage.Subfolder = remoteFileKey
}
remoteFileName := p.Task.PackageFile
p.Task.RemoteFileKey = filepath.Join(destStorage.Subfolder, p.Task.PackageFile)
if isKODO(destStorage) {
remoteFileName = remoteFileKey
p.Task.RemoteFileKey = destStorage.Subfolder
}
err = upload(ctx, p.Log, destStorage, localFile, remoteFileName)
if err != nil {
p.Log.Errorf("failed to upload file to dest storage %s %v", destStorage.GetURI(), err)
return
}
p.Log.Infof(
"md5sum enabled, will do md5sum and upload file %s.md5 to bucket %s",
p.Task.PackageFile,
destStorage.Bucket,
)
localMd5File := fmt.Sprintf("%s.md5", localFile)
var f *os.File
f, err = os.Open(localFile)
if err != nil {
p.Log.Errorf("open local file error: %v", err)
return
}
defer func() {
_ = f.Close()
}()
h := md5.New()
if _, err = io.Copy(h, f); err != nil {
p.Log.Errorf("copy md5 error: %v", err)
return
}
err = ioutil.WriteFile(localMd5File, []byte(fmt.Sprintf("%x", h.Sum(nil))), 0644)
if err != nil {
p.Log.Errorf("write md5 file error: %v", err)
return
}
defer func() {
_ = os.Remove(localMd5File)
}()
remoteMd5File := fmt.Sprintf("%s.md5", p.Task.PackageFile)
if isKODO(destStorage) {
remoteMd5File = fmt.Sprintf("%s.md5", remoteFileKey)
}
err = upload(ctx, p.Log, destStorage, localMd5File, remoteMd5File)
if err != nil {
p.Log.Errorf("failed to upload md5 file to %s %v", destStorage.GetURI(), err)
return
}
p.Task.TaskStatus = config.StatusPassed
}
// Wait ...
func (p *Distribute2S3TaskPlugin) Wait(ctx context.Context) {
timeout := time.After(time.Duration(p.TaskTimeout()) * time.Second)
for {
select {
case <-ctx.Done():
p.Task.TaskStatus = config.StatusCancelled
return
case <-timeout:
p.Task.TaskStatus = config.StatusTimeout
return
default:
time.Sleep(time.Second * 1)
if p.IsTaskDone() {
return
}
}
}
}
// Complete ...
func (p *Distribute2S3TaskPlugin) Complete(ctx context.Context, pipelineTask *task.Task, serviceName string) {
}
// SetTask ...
func (p *Distribute2S3TaskPlugin) SetTask(t map[string]interface{}) error {
task, err := ToDistributeToS3Task(t)
if err != nil {
return err
}
p.Task = task
return nil
}
// GetTask ...
func (p *Distribute2S3TaskPlugin) GetTask() interface{} {
return p.Task
}
// IsTaskDone ...
func (p *Distribute2S3TaskPlugin) IsTaskDone() bool {
if p.Task.TaskStatus != config.StatusCreated && p.Task.TaskStatus != config.StatusRunning {
return true
}
return false
}
// IsTaskFailed ...
func (p *Distribute2S3TaskPlugin) IsTaskFailed() bool {
if p.Task.TaskStatus == config.StatusFailed || p.Task.TaskStatus == config.StatusTimeout || p.Task.TaskStatus == config.StatusCancelled {
return true
}
return false
}
// SetStartTime ...
func (p *Distribute2S3TaskPlugin) SetStartTime() {
p.Task.StartTime = time.Now().Unix()
}
// SetEndTime ...
func (p *Distribute2S3TaskPlugin) SetEndTime() {
p.Task.EndTime = time.Now().Unix()
}
// IsTaskEnabled ...
func (p *Distribute2S3TaskPlugin) IsTaskEnabled() bool {
return p.Task.Enabled
}
// ResetError ...
func (p *Distribute2S3TaskPlugin) ResetError() {
p.Task.Error = ""
}