generated from gopherdojo/template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdl.go
216 lines (173 loc) · 4.02 KB
/
pdl.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
package pdl
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
type PDL struct {
url string
proc uint
fileSize uint
split uint
dir string
filename string
}
type Range struct {
start uint
end uint
}
func New(proc int, url, dir string) (*PDL, error) {
if url == "" {
return nil, errors.New("no url specified")
}
pdl := &PDL{
proc: uint(proc),
url: url,
dir: dir,
}
pdl.setSize()
pdl.setFilename()
return pdl, nil
}
func (p *PDL) Run() error {
if err := p.download(); err != nil {
return err
}
if err := p.merge(); err != nil {
return err
}
fmt.Println("finished")
return nil
}
func (p *PDL) download() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
eg, egctx := errgroup.WithContext(ctx)
for i := 0; i < int(p.proc); i++ {
i := i
eg.Go(func() error {
return p.partialDownload(egctx, i)
})
}
if err := eg.Wait(); err != nil {
return err
}
return nil
}
func (p *PDL) merge() (rerr error) {
out, err := os.Create(p.filePath())
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to Create %s in Merge", p.filePath()))
}
defer func() {
if err := out.Close(); err != nil {
rerr = err
}
}()
for i := 0; i < int(p.proc); i++ {
worker := i + 1
tmpfile, err := os.Open(p.tmpFilePath(worker))
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to Open %s in Merge", p.tmpFilePath(worker)))
}
_, err = io.Copy(out, tmpfile)
// Not use defer
tmpfile.Close()
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to Copy %s in Merge", p.tmpFilePath(worker)))
}
// delete
if err := os.Remove(p.tmpFilePath(worker)); err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to Remove %s in Merge", p.tmpFilePath(worker)))
}
}
return nil
}
func (p *PDL) makeRange(i, proc uint) Range {
start := p.split * i
end := start + p.split - 1
if i == proc-1 {
end = p.fileSize
}
return Range{
start: start,
end: end,
}
}
func (p *PDL) setSize() error {
resp, err := http.Head(p.url)
if err != nil {
return errors.Wrap(err, "failed to get Head")
}
p.fileSize = uint(resp.ContentLength)
p.split = p.fileSize / p.proc
return nil
}
func (p *PDL) setFilename() {
token := strings.Split(p.url, "/")
var original string
for i := 1; original == ""; i++ {
original = token[len(token)-i]
}
p.filename = original
}
func (p *PDL) tmpFilename(worker int) string {
return fmt.Sprintf("%s.%d", p.filename, worker)
}
func (p *PDL) partialDownload(ctx context.Context, index int) error {
worker := index + 1
fmt.Printf("start download worker: %d\n", worker)
// request
req, err := http.NewRequest("GET", p.url, nil)
if err != nil {
return errors.Wrap(err, "failed to create NewRequest for GET")
}
r := p.makeRange(uint(index), p.proc)
// set header
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", r.start, r.end))
// do
resp, err := http.DefaultClient.Do(req)
if err != nil {
return errors.Wrap(err, "failed to access")
}
defer resp.Body.Close()
// write
if err := p.writeTmpfile(resp.Body, int(worker)); err != nil {
return err
}
select {
case <-ctx.Done():
fmt.Printf("cancelled worker: %d\n", worker)
return ctx.Err()
default:
fmt.Printf("finish download worker: %d\n", worker)
return nil
}
}
func (p *PDL) filePath() string {
return filepath.Join(p.dir, p.filename)
}
func (p *PDL) tmpFilePath(worker int) string {
return filepath.Join(p.dir, p.tmpFilename(worker))
}
func (p *PDL) writeTmpfile(body io.Reader, worker int) (rerr error) {
out, err := os.Create(p.tmpFilePath(worker))
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to create file, worker: %d", worker))
}
defer func() {
if err := out.Close(); err != nil {
rerr = errors.Wrap(err, fmt.Sprintf("failed to close file, worker: %d", worker))
}
}()
if _, err := io.Copy(out, body); err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to write file, worker: %d", worker))
}
return nil
}