forked from zpeters/speedtest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspeedtest.go
379 lines (343 loc) · 11 KB
/
speedtest.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
speedtest is an unofficial commandline interface to speedtest.net
Version 1.0 was designed as an "app only". Version 2.0 will make a cleaner split between libraries and interface
*/
package main
import (
"context"
"fmt"
"log"
"math/rand"
"net/url"
"os"
"strings"
"time"
"github.com/dchest/uniuri"
"github.com/zpeters/speedtest/print"
"github.com/zpeters/speedtest/sthttp"
"github.com/zpeters/speedtest/tests"
"github.com/google/go-github/github"
"github.com/spf13/viper"
"github.com/urfave/cli"
)
// Version placeholder, injected in Makefile
var Version string
func runTest(c *cli.Context, stClient *sthttp.Client, tester *tests.Tester) {
// create our server object and load initial config
var testServer sthttp.Server
config, err := stClient.GetConfig()
if err != nil {
log.Printf("Cannot get speedtest config\n")
log.Fatal(err)
}
stClient.Config = &config
// if we are *not* running a report then say hello to everyone
if !tester.Report {
fmt.Printf("github.com/zpeters/speedtest -- unofficial cli for speedtest.net\n")
}
// if we are in debug mode print outa an environment report
if stClient.Debug {
print.EnvironmentReport(stClient)
}
// get all possible servers (excluding blacklisted)
if stClient.Debug {
log.Printf("Getting all servers for our test list")
}
var allServers []sthttp.Server
if c.String("mini") == "" {
allServers, err = stClient.GetServers()
if err != nil {
log.Fatal(err)
}
}
// if a mini speedtest installation was specified, use that...
if c.String("mini") != "" {
//construct testserver object manually
u, err := url.Parse(c.String("mini"))
if err != nil {
log.Fatalf("Speedtest mini server URL is not a valid URL: %s", err)
}
if stClient.Debug {
log.Printf("Using Mini Server '%s'", c.String("mini"))
}
testServer.URL = c.String("mini")
if !strings.HasSuffix(c.String("mini"), "/") {
testServer.URL += "/"
}
testServer.URL += "speedtest/upload.php"
testServer.Name = u.Host
testServer.Sponsor = "speedtest-mini"
testServer.ID = "0"
testServer.Latency, err = stClient.GetLatency(testServer, stClient.GetLatencyURL(testServer))
if err != nil {
log.Fatal(err)
}
// if they specified a specific speedtest.net server, test against that...
} else if c.String("server") != "" {
if stClient.Debug {
log.Printf("Server '%s' specified, getting info...", c.String("server"))
}
// find server and load latency report
testServer = tester.FindServer(c.String("server"), allServers)
// load latency
testServer.Latency, err = stClient.GetLatency(testServer, stClient.GetLatencyURL(testServer))
if err != nil {
log.Fatal(err)
}
if !tester.Report {
fmt.Printf("Server: %s - %s (%s)\n", testServer.ID, testServer.Name, testServer.Sponsor)
}
// ...otherwise get a list of all servers sorted by distance...
} else {
if stClient.Debug {
log.Printf("Getting closest servers...")
}
closestServers := stClient.GetClosestServers(allServers)
if stClient.Debug {
log.Printf("Getting the fastests of our closest servers...")
}
// ... and get the fastests NUMCLOSEST ones
testServer = stClient.GetFastestServer(closestServers)
if !viper.GetBool("report") {
fmt.Printf("Server: %s - %s (%s)\n", testServer.ID, testServer.Name, testServer.Sponsor)
}
}
// if ping only then just output latency results and exit nicely...
if c.Bool("ping") {
if c.Bool("report") {
if viper.GetString("algotype") == "max" {
fmt.Printf("%3.2f (Lowest)\n", testServer.Latency)
} else {
fmt.Printf("%3.2f (Avg)\n", testServer.Latency)
}
} else {
if viper.GetString("algotype") == "max" {
fmt.Printf("Ping (Lowest): %3.2f ms\n", testServer.Latency)
} else {
fmt.Printf("Ping (Avg): %3.2f ms\n", testServer.Latency)
}
}
os.Exit(0)
// ...otherwise run our full test
} else {
var dmbps float64
var umbps float64
if !viper.GetBool("report") {
if c.Bool("downloadonly") {
dmbps = tester.Download(testServer)
} else if c.Bool("uploadonly") {
umbps = tester.Upload(testServer)
} else {
dmbps = tester.Download(testServer)
umbps = tester.Upload(testServer)
}
if viper.GetString("algotype") == "max" {
fmt.Printf("Ping (Lowest): %3.2f ms | Download (Max): %3.2f Mbps | Upload (Max): %3.2f Mbps\n", testServer.Latency, dmbps, umbps)
} else {
fmt.Printf("Ping (Avg): %3.2f ms | Download (Avg): %3.2f Mbps | Upload (Avg): %3.2f Mbps\n", testServer.Latency, dmbps, umbps)
}
} else {
fmt.Printf("%s%s%s%s\"%s (%s, %s)\"%s", time.Now().Format("2006-01-02 15:04:05 -0700"), viper.GetString("reportchar"), testServer.ID, viper.GetString("reportchar"), testServer.Sponsor, testServer.Name, testServer.Country, viper.GetString("reportchar"))
fmt.Printf("%3.2f%s", testServer.Latency, viper.GetString("reportchar"))
if c.Bool("downloadonly") {
dmbps = tester.Download(testServer)
dkbps := dmbps * 1000
fmt.Printf("%d\n", int(dkbps))
} else if c.Bool("uploadonly") {
umbps = tester.Upload(testServer)
ukbps := umbps * 1000
fmt.Printf("%d\n", int(ukbps))
} else {
dmbps = tester.Download(testServer)
dkbps := dmbps * 1000
fmt.Printf("%d%s", int(dkbps), viper.GetString("reportchar"))
umbps = tester.Upload(testServer)
ukbps := umbps * 1000
fmt.Printf("%d\n", int(ukbps))
}
}
}
}
func init() {
viper.SetDefault("debug", false)
viper.SetDefault("quiet", false)
viper.SetDefault("report", false)
viper.SetDefault("numclosest", 3)
viper.SetDefault("numlatencytests", 5)
viper.SetDefault("reportchar", "|")
viper.SetDefault("algotype", "max")
viper.SetDefault("httptimeout", 15)
viper.SetDefault("dlsizes", []int{350, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000})
viper.SetDefault("ulsizes", []int{int(0.25 * 1024 * 1024), int(0.5 * 1024 * 1024), int(1.0 * 1024 * 1024), int(1.5 * 1024 * 1024), int(2.0 * 1024 * 1024)})
viper.SetDefault("speedtestconfigurl", "http://c.speedtest.net/speedtest-config.php?x="+uniuri.New())
viper.SetDefault("speedtestserversurl", "http://c.speedtest.net/speedtest-servers-static.php?x="+uniuri.New())
viper.SetDefault("useragent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.21 Safari/537.36")
}
func main() {
// seeding randomness
rand.Seed(time.Now().UTC().UnixNano())
// set logging to stdout for global logger
log.SetOutput(os.Stdout)
// setting up cli settings
app := cli.NewApp()
app.Name = "speedtest"
app.Usage = "Unofficial command line interface to speedtest.net (https://github.com/zpeters/speedtest)"
app.Author = "Zach Peters - zpeters@gmail.com - github.com/zpeters"
app.Version = Version
// setup cli flags
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "algo, a",
Usage: "Specify the measurement method to use ('max', 'avg')",
},
cli.BoolFlag{
Name: "debug, d",
Usage: "Turn on debugging",
},
cli.BoolFlag{
Name: "list, l",
Usage: "List available servers",
},
cli.BoolFlag{
Name: "update, u",
Usage: "Check for a new version of speedtest",
},
cli.BoolFlag{
Name: "ping, p",
Usage: "Ping only mode",
},
cli.BoolFlag{
Name: "quiet, q",
Usage: "Quiet mode",
},
cli.BoolFlag{
Name: "report, r",
Usage: "Reporting mode output, minimal output with '|' for separators, use '--rc'\n\t\tto change separator characters. Reports the following: Server ID, \n\t\tServer Name (Location), Ping time in ms, Download speed in kbps, Upload speed in kbps",
},
cli.BoolFlag{
Name: "downloadonly, do",
Usage: "Only perform download test",
},
cli.BoolFlag{
Name: "uploadonly, uo",
Usage: "Only perform upload test",
},
cli.StringFlag{
Name: "reportchar, rc",
Usage: "Set the report separator. Example: --rc=','",
},
cli.StringFlag{
Name: "server, s",
Usage: "Use a specific server",
},
cli.StringSliceFlag{
Name: "blacklist, b",
Usage: "Blacklist a server. Use this multiple times for more than one server",
},
cli.StringFlag{
Name: "mini, m",
Usage: "URL of speedtest mini server",
},
cli.StringFlag{
Name: "useragent, ua",
Usage: "Specify a useragent string",
},
cli.IntFlag{
Name: "numclosest, nc",
Value: viper.GetInt("numclosest"),
Usage: "Number of 'closest' servers to find",
},
cli.IntFlag{
Name: "numlatency, nl",
Value: viper.GetInt("numlatencytests"),
Usage: "Number of latency tests to perform",
},
cli.StringFlag{
Name: "interface, I",
Usage: "Source IP address or name of an interface",
},
}
// toggle our switches and setup variables
app.Action = func(c *cli.Context) {
// just check the version if that is what they want
if c.Bool("update") {
// Check if there is an update
client := github.NewClient(nil)
latestRelease, _, err := client.Repositories.GetLatestRelease(context.Background(), "zpeters", "speedtest")
if err != nil {
log.Fatalf("github call: %s", err)
}
githubTag := *latestRelease.TagName
if Version != githubTag {
fmt.Printf("New version %s available at https://github.com/zpeters/speedtest/releases\n", githubTag)
} else {
fmt.Printf("You are up to date\n")
}
os.Exit(0)
}
// set our flags
if c.Bool("debug") {
viper.Set("debug", true)
}
if c.Bool("quiet") {
viper.Set("quiet", true)
}
if c.Bool("report") {
viper.Set("report", true)
}
if c.String("algo") != "" {
if c.String("algo") == "max" {
viper.Set("algotype", "max")
} else if c.String("algo") == "avg" {
viper.Set("algotype", "avg")
} else {
fmt.Printf("** Invalid algorithm '%s'\n", c.String("algo"))
os.Exit(1)
}
}
viper.Set("numclosest", c.Int("numclosest"))
viper.Set("numlatencytests", c.Int("numlatency"))
if c.String("reportchar") != "" {
viper.Set("reportchar", c.String("reportchar"))
}
if c.String("interface") != "" {
viper.Set("interface", c.String("interface"))
}
if len(c.StringSlice("blacklist")) > 0 {
viper.Set("blacklist", c.StringSlice("blacklist"))
}
stClient := sthttp.NewClient(
&sthttp.SpeedtestConfig{
ConfigURL: viper.GetString("speedtestconfigurl"),
ServersURL: viper.GetString("speedtestserversurl"),
AlgoType: viper.GetString("algotype"),
NumClosest: viper.GetInt("numclosest"),
NumLatencyTests: viper.GetInt("numlatencytests"),
Interface: viper.GetString("interface"),
Blacklist: viper.GetStringSlice("blacklist"),
UserAgent: viper.GetString("useragent"),
},
&sthttp.HTTPConfig{
HTTPTimeout: viper.GetDuration("httptimeout") * time.Second,
},
viper.GetBool("debug"),
viper.GetString("reportchar"))
tester := tests.NewTester(
stClient,
viper.Get("dlsizes").([]int),
viper.Get("ulsizes").([]int),
viper.GetBool("quiet"),
viper.GetBool("report"))
// run a oneshot list
if c.Bool("list") {
tester.ListServers(stClient.SpeedtestConfig.ConfigURL, stClient.SpeedtestConfig.ServersURL, stClient.SpeedtestConfig.Blacklist)
os.Exit(0)
}
// run our test
runTest(c, stClient, tester)
// exit nicely
os.Exit(0)
}
// run the app
app.Run(os.Args)
}