-
-
Notifications
You must be signed in to change notification settings - Fork 211
/
file_chan.go
90 lines (81 loc) · 1.85 KB
/
file_chan.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
package cloudbackup
import (
"context"
"os"
"time"
"github.com/admpub/log"
"github.com/admpub/nging/v4/application/library/flock"
"github.com/admpub/nging/v4/application/library/msgbox"
"github.com/admpub/nging/v4/application/library/s3manager"
"github.com/admpub/once"
"github.com/webx-top/com"
"github.com/webx-top/echo/param"
)
var (
BackupTasks = param.NewMap()
fileChan chan *PutFile
fileChanOnce once.Once
ctx context.Context
cancel context.CancelFunc
)
type PutFile struct {
Manager *s3manager.S3Manager
ObjectName string
FilePath string
WaitFillCompleted bool
}
func (mf *PutFile) Do() error {
fp, err := os.Open(mf.FilePath)
if err != nil {
log.Error(`Open ` + mf.FilePath + `: ` + err.Error())
return err
}
defer fp.Close()
if !mf.WaitFillCompleted || flock.IsCompleted(fp, time.Now()) {
fi, err := fp.Stat()
if err != nil {
log.Error(`Stat ` + mf.FilePath + `: ` + err.Error())
return err
}
err = mf.Manager.Put(context.Background(), fp, mf.ObjectName, fi.Size())
if err != nil {
log.Error(`s3manager.Put ` + mf.FilePath + `: ` + err.Error())
} else {
log.Info(`s3manager.Put ` + mf.FilePath + `: success`)
}
}
return err
}
func FileChan() chan *PutFile {
fileChanOnce.Do(initFileChan)
return fileChan
}
func initFileChan() {
fileChan = make(chan *PutFile, 1000)
ctx, cancel = context.WithCancel(context.Background())
go func() {
for {
select {
case <-ctx.Done():
return
case mf, ok := <-fileChan:
if !ok || mf == nil {
return
}
mf.Do()
}
}
}()
}
func ResetFileChan() {
cancel()
fileChanOnce.Reset()
}
func MonitorBackupStop(id uint) error {
if monitor, ok := BackupTasks.Get(id).(*com.MonitorEvent); ok {
monitor.Close()
BackupTasks.Delete(id)
msgbox.Success(`Cloud-Backup`, `Close: `+com.String(id))
}
return nil
}