|
| 1 | +package speedtest |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "math" |
| 7 | + |
| 8 | + "github.com/rs/zerolog/log" |
| 9 | + "github.com/showwin/speedtest-go/speedtest" |
| 10 | + "github.com/threefoldtech/zosbase/pkg/perf" |
| 11 | +) |
| 12 | + |
| 13 | +type SpeedTestTask struct { |
| 14 | +} |
| 15 | + |
| 16 | +// CPUBenchmarkResult holds CPU benchmark results with the workloads number during the benchmark. |
| 17 | +type SpeedTestResults struct { |
| 18 | + Download float64 `json:"download_speed"` |
| 19 | + Upload float64 `json:"upload_speed"` |
| 20 | +} |
| 21 | + |
| 22 | +var _ perf.Task = (*SpeedTestTask)(nil) |
| 23 | + |
| 24 | +// ID returns task ID. |
| 25 | +func (c *SpeedTestTask) ID() string { |
| 26 | + return "speedtest" |
| 27 | +} |
| 28 | + |
| 29 | +// Cron returns task cron schedule. |
| 30 | +func (c *SpeedTestTask) Cron() string { |
| 31 | + return "*/30 * * * * *" |
| 32 | +} |
| 33 | + |
| 34 | +// Description returns task description. |
| 35 | +func (c *SpeedTestTask) Description() string { |
| 36 | + return "Measures the download/upload speed of the node." |
| 37 | +} |
| 38 | + |
| 39 | +// Jitter returns the max number of seconds the job can sleep before actual execution. |
| 40 | +func (c *SpeedTestTask) Jitter() uint32 { |
| 41 | + return 0 |
| 42 | +} |
| 43 | + |
| 44 | +func NewTask() perf.Task { |
| 45 | + return &SpeedTestTask{} |
| 46 | +} |
| 47 | + |
| 48 | +// Run executes the SpeedTest task. |
| 49 | +func (c *SpeedTestTask) Run(ctx context.Context) (interface{}, error) { |
| 50 | + serverList, err := speedtest.FetchServers() |
| 51 | + if err != nil { |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + servers, err := serverList.FindServer([]int{}) |
| 55 | + if err != nil { |
| 56 | + return nil, err |
| 57 | + } |
| 58 | + if len(servers) < 1 { |
| 59 | + return nil, fmt.Errorf("no speedtest server found") |
| 60 | + } |
| 61 | + |
| 62 | + speedtestServer := servers[0] |
| 63 | + |
| 64 | + err = speedtestServer.DownloadTest() |
| 65 | + if err != nil { |
| 66 | + log.Error().Err(err).Msg("speedtest download test failed") |
| 67 | + return nil, err |
| 68 | + } |
| 69 | + |
| 70 | + err = speedtestServer.UploadTest() |
| 71 | + if err != nil { |
| 72 | + log.Error().Err(err).Msg("speedtest upload test failed") |
| 73 | + return nil, err |
| 74 | + } |
| 75 | + |
| 76 | + download := speedtestServer.DLSpeed.Mbps() |
| 77 | + upload := speedtestServer.ULSpeed.Mbps() |
| 78 | + |
| 79 | + if math.IsNaN(download) || math.IsNaN(upload) { |
| 80 | + return nil, fmt.Errorf("speedtest returned NaN value") |
| 81 | + } |
| 82 | + |
| 83 | + log.Info().Msgf("speedtest result: download %.2f Mbps, upload %.2f Mbps", download, upload) |
| 84 | + return SpeedTestResults{ |
| 85 | + Download: download, |
| 86 | + Upload: upload, |
| 87 | + }, nil |
| 88 | + |
| 89 | +} |
0 commit comments