-
Notifications
You must be signed in to change notification settings - Fork 262
/
root.go
304 lines (243 loc) · 10.9 KB
/
root.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
/*
* Copyright 2020 The Dragonfly 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 cmd
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"syscall"
"time"
"github.com/gofrs/flock"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
"d7y.io/dragonfly/v2/client/config"
"d7y.io/dragonfly/v2/client/dfget"
"d7y.io/dragonfly/v2/cmd/dependency"
logger "d7y.io/dragonfly/v2/internal/dflog"
"d7y.io/dragonfly/v2/pkg/basic"
"d7y.io/dragonfly/v2/pkg/dfnet"
"d7y.io/dragonfly/v2/pkg/dfpath"
"d7y.io/dragonfly/v2/pkg/net/ip"
"d7y.io/dragonfly/v2/pkg/rpc/dfdaemon/client"
"d7y.io/dragonfly/v2/pkg/source"
"d7y.io/dragonfly/v2/pkg/types"
"d7y.io/dragonfly/v2/pkg/unit"
"d7y.io/dragonfly/v2/version"
)
var (
dfgetConfig *config.DfgetConfig
)
var dfgetDescription = `dfget is the client of dragonfly which takes a role of peer in a P2P network.
When user triggers a file downloading task, dfget will download the pieces of
file from other peers. Meanwhile, it will act as an uploader to support other
peers to download pieces from it if it owns them. In addition, dfget has the
abilities to provide more advanced functionality, such as network bandwidth
limit, transmission encryption and so on.`
// rootCmd represents the commonv1 command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "dfget url -O path",
Short: "the P2P client of dragonfly",
Long: dfgetDescription,
Args: cobra.MaximumNArgs(1),
DisableAutoGenTag: true,
SilenceUsage: true,
FParseErrWhitelist: cobra.FParseErrWhitelist{UnknownFlags: true},
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
// Convert config
if err := dfgetConfig.Convert(args); err != nil {
return err
}
// Validate config
if err := dfgetConfig.Validate(); err != nil {
return err
}
// Initialize daemon dfpath
d, err := initDfgetDfpath(dfgetConfig)
if err != nil {
return err
}
// Initialize logger
if err := logger.InitDfget(dfgetConfig.Verbose, dfgetConfig.Console, d.LogDir()); err != nil {
return fmt.Errorf("init client dfget logger: %w", err)
}
// update plugin directory
source.UpdatePluginDir(d.PluginDir())
fmt.Printf("--%s-- %s\n", start.Format("2006-01-02 15:04:05"), dfgetConfig.URL)
fmt.Printf("dfget version: %s\n", version.GitVersion)
fmt.Printf("current user: %s, default peer ip: %s\n", basic.Username, ip.IPv4)
fmt.Printf("output path: %s\n", dfgetConfig.Output)
// do get file
err = runDfget(d.DfgetLockPath(), d.DaemonSockPath())
if err != nil {
msg := fmt.Sprintf("download success: %t cost: %d ms error: %s", false, time.Since(start).Milliseconds(), err.Error())
logger.With("url", dfgetConfig.URL).Info(msg)
fmt.Println(msg)
return fmt.Errorf("download url %s: %w", dfgetConfig.URL, err)
}
msg := fmt.Sprintf("download success: %t cost: %d ms", true, time.Since(start).Milliseconds())
logger.With("url", dfgetConfig.URL).Info(msg)
fmt.Println(msg)
return nil
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
logger.Error(err)
os.Exit(1)
}
}
func init() {
// Initialize default dfget config
dfgetConfig = config.NewDfgetConfig()
// Initialize command and config
dependency.InitCommandAndConfig(rootCmd, true, dfgetConfig)
// Add flags
flagSet := rootCmd.Flags()
flagSet.StringVarP(&dfgetConfig.URL, "url", "u", dfgetConfig.URL,
"Download one file from the url, equivalent to the command's first position argument")
flagSet.StringVarP(&dfgetConfig.Output, "output", "O", dfgetConfig.Output,
"Destination path which is used to store the downloaded file, it must be a full path")
flagSet.DurationVar(&dfgetConfig.Timeout, "timeout", dfgetConfig.Timeout, "Timeout for the downloading task, 0 is infinite")
flagSet.String("ratelimit", unit.Bytes(dfgetConfig.RateLimit.Limit).String(),
"The downloading network bandwidth limit per second in format of G(B)/g/M(B)/m/K(B)/k/B, pure number will be parsed as Byte, 0 is infinite")
flagSet.StringVar(&dfgetConfig.Digest, "digest", dfgetConfig.Digest,
"Check the integrity of the downloaded file with digest, in format of md5:xxx or sha256:yyy")
flagSet.StringVar(&dfgetConfig.Tag, "tag", dfgetConfig.Tag,
"Different tags for the same url will be divided into different P2P overlay, it conflicts with --digest")
flagSet.StringVar(&dfgetConfig.Filter, "filter", dfgetConfig.Filter,
"Filter the query parameters of the url, P2P overlay is the same one if the filtered url is same, "+
"in format of key&sign, which will filter 'key' and 'sign' query parameters")
flagSet.StringSliceVarP(&dfgetConfig.Header, "header", "H", dfgetConfig.Header, "url header, eg: --header='Accept: *' --header='Host: abc'")
flagSet.BoolVar(&dfgetConfig.DisableBackSource, "disable-back-source", dfgetConfig.DisableBackSource,
"Disable downloading directly from source when the daemon fails to download file")
flagSet.StringVarP(&dfgetConfig.Pattern, "pattern", "p", dfgetConfig.Pattern, "The downloading pattern: p2p/seed-peer/source")
flagSet.BoolVarP(&dfgetConfig.ShowProgress, "show-progress", "b", dfgetConfig.ShowProgress, "Show progress bar, it conflicts with --console")
flagSet.StringVar(&dfgetConfig.Application, "application", dfgetConfig.Application, "The caller name which is mainly used for statistics and access control")
flagSet.StringVar(&dfgetConfig.DaemonSock, "daemon-sock", dfgetConfig.DaemonSock, "Download socket path of daemon. In linux, default value is /var/run/dfdaemon.sock, in macos(just for testing), default value is /tmp/dfdaemon.sock")
flagSet.StringVar(&dfgetConfig.WorkHome, "workhome", dfgetConfig.WorkHome, "Dfget working directory")
flagSet.StringVar(&dfgetConfig.LogDir, "logdir", dfgetConfig.LogDir, "Dfget log directory")
flagSet.BoolVarP(&dfgetConfig.Recursive, "recursive", "r", dfgetConfig.Recursive,
"Recursively download all resources in target url, the target source client must support list action")
flagSet.UintVar(&dfgetConfig.RecursiveLevel, "level", dfgetConfig.RecursiveLevel,
"Recursively download only. Set the maximum number of subdirectories that dfget will recurse into. Set to 0 for no limit")
flagSet.BoolVarP(&dfgetConfig.RecursiveList, "list", "l", dfgetConfig.RecursiveList,
"Recursively download only. List all urls instead of downloading them.")
flagSet.StringVar(&dfgetConfig.RecursiveAcceptRegex, "accept-regex", dfgetConfig.RecursiveAcceptRegex,
"Recursively download only. Specify a regular expression to accept the complete URL. In this case, you have to enclose the pattern into quotes to prevent your shell from expanding it")
flagSet.StringVar(&dfgetConfig.RecursiveRejectRegex, "reject-regex", dfgetConfig.RecursiveRejectRegex,
`Recursively download only. Specify a regular expression to reject the complete URL. In this case, you have to enclose the pattern into quotes to prevent your shell from expanding it`)
flagSet.BoolVar(&dfgetConfig.KeepOriginalOffset, "original-offset", dfgetConfig.KeepOriginalOffset,
`Range request only. Download ranged data into target file with original offset. Daemon will make a hardlink to target file. Client can download many ranged data into one file for same url. When enabled, back source in client will be disabled`)
flagSet.StringVar(&dfgetConfig.Range, "range", dfgetConfig.Range,
`Download range. Like: 0-9, stands download 10 bytes from 0 -9, [0:9] in real url`)
// Bind cmd flags
if err := viper.BindPFlags(flagSet); err != nil {
panic(fmt.Errorf("bind dfget flags to viper: %w", err))
}
}
func initDfgetDfpath(cfg *config.ClientOption) (dfpath.Dfpath, error) {
options := []dfpath.Option{}
if cfg.WorkHome != "" {
options = append(options, dfpath.WithWorkHome(cfg.WorkHome))
}
if cfg.LogDir != "" {
options = append(options, dfpath.WithLogDir(cfg.LogDir))
}
if cfg.DaemonSock != "" {
options = append(options, dfpath.WithDownloadUnixSocketPath(cfg.DaemonSock))
}
return dfpath.New(options...)
}
// runDfget does some init operations and starts to download.
func runDfget(dfgetLockPath, daemonSockPath string) error {
logger.Infof("Version:\n%s", version.Version())
// Dfget config values
s, _ := yaml.Marshal(dfgetConfig)
logger.Infof("client dfget configuration:\n%s", string(s))
ff := dependency.InitMonitor(dfgetConfig.PProfPort, dfgetConfig.Telemetry)
defer ff()
var (
dfdaemonClient client.Client
err error
)
if dfgetConfig.Pattern != types.SourcePattern {
logger.Info("start to check and spawn daemon")
if dfdaemonClient, err = checkAndSpawnDaemon(dfgetLockPath, daemonSockPath); err != nil {
logger.Errorf("check and spawn daemon error: %v", err)
} else {
logger.Info("check and spawn daemon success")
}
}
return dfget.Download(dfgetConfig, dfdaemonClient)
}
// checkAndSpawnDaemon do checking at three checkpoints
func checkAndSpawnDaemon(dfgetLockPath, daemonSockPath string) (client.Client, error) {
netAddr := &dfnet.NetAddr{Type: dfnet.UNIX, Addr: daemonSockPath}
dfdaemonClient, err := client.GetInsecureClient(context.Background(), netAddr.String())
if err != nil {
return nil, err
}
// 1.Check without lock
if dfdaemonClient.CheckHealth(context.Background()) == nil {
return dfdaemonClient, nil
}
lock := flock.New(dfgetLockPath)
if err := lock.Lock(); err != nil {
logger.Errorf("flock lock failed %s", err)
return nil, err
}
defer func() {
if err := lock.Unlock(); err != nil {
logger.Errorf("flock unlock failed %s", err)
}
}()
// 2.Check with lock
if dfdaemonClient.CheckHealth(context.Background()) == nil {
return dfdaemonClient, nil
}
cmd := exec.Command(os.Args[0], "daemon", "--launcher", strconv.Itoa(os.Getpid()), "--config", viper.GetString("config"))
cmd.Stdin = nil
cmd.Stdout = nil
cmd.Stderr = nil
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
logger.Info("do start daemon")
err = cmd.Start()
if err != nil {
return nil, err
}
// 3. check health with at least 5s timeout
tick := time.NewTicker(50 * time.Millisecond)
defer tick.Stop()
timeout := time.After(5 * time.Second)
for {
select {
case <-timeout:
return nil, errors.New("the daemon is unhealthy")
case <-tick.C:
if err = dfdaemonClient.CheckHealth(context.Background()); err != nil {
continue
}
return dfdaemonClient, nil
}
}
}