-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
266 lines (244 loc) · 6.57 KB
/
main.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
package main
import (
"bufio"
"context"
"fmt"
"io"
"math"
"net/http"
"os"
"path"
"path/filepath"
"sync"
"time"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
// set up log formatting and log level, I want actual timestamps
func init() {
formatter := &logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
}
logrus.SetFormatter(formatter)
}
// Use mutex to help mitigate collisions, I followed along with https://gobyexample.com/mutexes
type FileProgress struct {
totalBytes int64
downloadedBytes int64
startTime time.Time
}
type DownloadProgress struct {
progress map[string]*FileProgress
mu sync.Mutex
}
func (dp *DownloadProgress) AddDownloadedBytes(url string, n int) {
dp.mu.Lock()
defer dp.mu.Unlock()
if _, ok := dp.progress[url]; !ok {
dp.progress[url] = &FileProgress{
totalBytes: 0,
downloadedBytes: 0,
startTime: time.Now(),
}
}
dp.progress[url].downloadedBytes += int64(n)
//logrus.Trace("Downloaded bytes now equal to: ", dp.progress[url].downloadedBytes)
}
func (dp *DownloadProgress) DownloadRate(url string) float64 {
dp.mu.Lock()
defer dp.mu.Unlock()
if _, ok := dp.progress[url]; !ok {
return 0
}
duration := time.Since(dp.progress[url].startTime).Seconds()
logrus.Trace("current duration: ", duration)
logrus.Trace("Current bytes: ", dp.progress[url].downloadedBytes)
return float64(dp.progress[url].downloadedBytes) / duration
}
// main function to download URL's
// TODO: break this up a little more would probably make sense...
func getURL(url string, outDir string, threadID int) {
dp := &DownloadProgress{
progress: make(map[string]*FileProgress),
}
totalDownloadTime := time.Duration(0)
startTime := time.Now()
// set up context and exit (cancel) for the monitorDownload goroutine
ctx, cancel := context.WithCancel(context.Background())
// start up our monitoring for this thread
monitorDownload(ctx, dp, url, threadID)
logrus.Info("Downloading file from URL: ", url)
resp, err := http.Get(url)
if err != nil {
logrus.Error("Error downloading file from URL:", url)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logrus.Error("Error: received non-200 status code from server for file:", url)
}
logrus.Tracef("Total upstream file size for %s is: %d", url, resp.ContentLength)
// Create the output file
filePath := filepath.Join(outDir, path.Base(url))
out, err := os.Create(filePath)
if err != nil {
logrus.Error("Error creating output file:", err)
}
defer out.Close()
/*
Read the response body in chunks
write each chunk to output file
update dp.downloadedBytes
*/
buf := make([]byte, 1024)
for {
n, err := resp.Body.Read(buf)
if err != nil && err != io.EOF {
logrus.Error("Error reading response body:", err)
break
}
if n == 0 {
break
}
if _, err := out.Write(buf[:n]); err != nil {
logrus.Error("Error writing to output file:", err)
break
}
dp.AddDownloadedBytes(url, n)
}
downloadTime := time.Since(startTime)
totalDownloadTime += downloadTime
// now exit the context when we're done so we stop logging download rate
cancel()
logrus.Infof("Total download time for url %s: %s\n", url, totalDownloadTime.Truncate(time.Second).String())
logrus.Infof("Total file size for url %s: %s\n", url, bytesToReadable(int64(dp.progress[url].totalBytes)))
}
func monitorDownload(ctx context.Context, dp *DownloadProgress, url string, threadID int) {
go func() {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
// If the context is cancelled, stop the goroutine
return
case <-ticker.C:
duration := time.Since(dp.progress[url].startTime).Seconds()
rate := math.Round(float64(dp.progress[url].downloadedBytes))
logrus.WithFields(logrus.Fields{
"threadID": threadID,
}).Infof("Current download rate for: %s is %s/s", url, bytesToReadable(int64(rate/duration)))
}
}
}()
}
// https://gist.github.com/chadleeshaw/5420caa98498c46a84ce94cd9655287a convert bytes to human readable number
func bytesToReadable(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}
func readFile(filePath string) ([]string, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
// Start up main func
func main() {
var logLevel string
app := &cli.App{
Name: "downloader",
Usage: "Download things and save them in a dir",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "file, f",
Aliases: []string{"f"},
Value: "",
Usage: "The path to the input `FILE` containing urls.",
Required: true,
},
&cli.StringFlag{
Name: "outdir, d",
Aliases: []string{"o"},
Value: "./output",
Usage: "The `DIRECTORY` where the files will be saved to.",
Required: false,
},
&cli.StringFlag{
Name: "loglevel",
Value: "info",
Usage: "Set log level (debug, info, warn, error, fatal, panic)",
Destination: &logLevel,
},
&cli.IntFlag{
Name: "threads",
Value: 4,
Usage: "Number of download threads",
},
},
Action: func(c *cli.Context) error {
urlChan := make(chan string)
var wg sync.WaitGroup
// create the output directory, if it does not exist already
outDir := c.String("outdir")
err := os.MkdirAll(outDir, 0755)
if err != nil {
return cli.Exit("Error creating output dir.", 1)
}
rawFile, err := readFile(c.String("file"))
if err != nil {
logrus.Error("Error reading input file:", err)
os.Exit(1)
}
level, err := logrus.ParseLevel(c.String("loglevel"))
if err != nil {
return err
}
logrus.SetLevel(level)
for i := 0; i < c.Int("threads"); i++ {
wg.Add(1)
go func(threadID int) {
defer wg.Done()
for url := range urlChan {
getURL(url, outDir, threadID)
if err != nil {
logrus.WithFields(logrus.Fields{
"threadID": threadID,
}).Error(err)
}
}
}(i)
}
for _, url := range rawFile {
urlChan <- url
}
close(urlChan)
wg.Wait()
logrus.Info("Downloaded all files listed in:", c.String("file"))
return nil
},
}
err := app.Run(os.Args)
if err != nil {
cli.Exit(err.Error(), 1)
os.Exit(1)
}
}