-
Notifications
You must be signed in to change notification settings - Fork 0
/
acp.go
142 lines (117 loc) · 2.37 KB
/
acp.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
package acp
import (
"context"
"sync"
"github.com/sirupsen/logrus"
)
type Copyer struct {
*option
running sync.WaitGroup
eventCh chan Event
getDevice func(in string) string
getDiskUsageCache func(mountPoint string) *diskUsageCache
}
func New(ctx context.Context, opts ...Option) (*Copyer, error) {
opt := newOption()
for _, o := range opts {
if o == nil {
continue
}
opt = o(opt)
}
if err := opt.check(); err != nil {
return nil, err
}
getDevice, err := getMountpointCache()
if err != nil {
return nil, err
}
c := &Copyer{
option: opt,
eventCh: make(chan Event, 128),
getDevice: getDevice,
getDiskUsageCache: Cache(func(mountPoint string) *diskUsageCache {
return newDiskUsageCache(mountPoint, defaultDiskUsageFreshInterval)
}),
}
c.running.Add(1)
go wrap(ctx, func() { c.run(ctx) })
return c, nil
}
func (c *Copyer) Wait() {
c.running.Wait()
}
func (c *Copyer) run(ctx context.Context) error {
defer c.running.Done()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go wrap(ctx, func() { c.eventLoop(ctx) })
indexed, err := c.index(ctx)
if err != nil {
return err
}
prepared := c.prepare(ctx, indexed)
copyed := c.copy(ctx, prepared)
c.cleanupJob(ctx, copyed)
// empty pipes
for range indexed {
}
for range prepared {
}
for range copyed {
}
return nil
}
func (c *Copyer) eventLoop(ctx context.Context) {
c.running.Add(1)
defer c.running.Done()
chans := make([]chan Event, len(c.eventHanders))
for idx := range chans {
chans[idx] = make(chan Event, 128)
}
for idx, ch := range chans {
handler := c.eventHanders[idx]
events := ch
c.running.Add(1)
go wrap(ctx, func() {
defer c.running.Done()
for {
e, ok := <-events
if !ok {
handler(&EventFinished{})
return
}
handler(e)
}
})
}
defer func() {
for _, ch := range chans {
close(ch)
}
}()
for {
select {
case e, ok := <-c.eventCh:
if !ok {
return
}
for _, ch := range chans {
ch <- e
}
case <-ctx.Done():
return
}
}
}
func (c *Copyer) logf(l logrus.Level, format string, args ...any) {
c.logger.Logf(l, format, args...)
}
func (c *Copyer) submit(e Event) {
c.eventCh <- e
}
func (c *Copyer) reportError(src, dst string, err error) {
e := &Error{Src: src, Dst: dst, Err: err}
c.logf(logrus.ErrorLevel, e.Error())
c.submit(&EventReportError{Error: e})
}