-
Notifications
You must be signed in to change notification settings - Fork 2
/
realtime.go
203 lines (164 loc) · 5.5 KB
/
realtime.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/imup-io/client/speedtesting"
log "golang.org/x/exp/slog"
)
type realtimeApiPayload struct {
ID string `json:"hostId,omitempty"`
Email string `json:"email,omitempty"`
GroupID string `json:"group_id,omitempty"`
Key string `json:"apiKey,omitempty"`
Version string `json:"version,omitempty"`
Data interface{} `json:"data,omitempty"`
}
func (i *imup) sendClientHealthy(ctx context.Context) error {
data := &realtimeApiPayload{
ID: i.cfg.HostID(), Key: i.cfg.APIKey(), Email: i.cfg.EmailAddress(), GroupID: i.cfg.GroupID(),
}
b, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("json.Marshal: %v", err)
}
return sendRealtimeData(ctx, bytes.NewBuffer(b), i.cfg.LivenessCheckInURL())
}
func sendRealtimeData(ctx context.Context, b *bytes.Buffer, addr string) error {
req, err := retryablehttp.NewRequest("POST", addr, b)
req = req.WithContext(ctx)
if err != nil {
return fmt.Errorf("NewRequest: %v", err)
}
req.Header.Set("Content-Type", "application/json")
client := retryablehttp.NewClient()
client.Backoff = exactJitterBackoff
client.RetryMax = 3
client.RetryWaitMin = time.Duration(200) * time.Millisecond
client.RetryWaitMax = time.Duration(3) * time.Second
client.Logger = log.New(log.Default().Handler())
if _, err := client.Do(req); err != nil {
return fmt.Errorf("addr: %s, client.Do: %s", addr, err)
}
return nil
}
func (i *imup) shouldRunSpeedtest(ctx context.Context) (bool, error) {
data := &realtimeApiPayload{
ID: i.cfg.HostID(), Key: i.cfg.APIKey(), Email: i.cfg.EmailAddress(), GroupID: i.cfg.GroupID(),
}
b, err := json.Marshal(data)
if err != nil {
return false, fmt.Errorf("json.Marshal: %v", err)
}
req, err := retryablehttp.NewRequest("POST", i.cfg.ShouldRunSpeedTestURL(), bytes.NewBuffer(b))
req = req.WithContext(ctx)
if err != nil {
return false, fmt.Errorf("NewRequest: %v", err)
}
req.Header.Set("Content-Type", "application/json")
client := retryablehttp.NewClient()
client.Backoff = exactJitterBackoff
client.RetryMax = 2
client.RetryWaitMin = time.Duration(30) * time.Second
client.RetryWaitMax = time.Duration(60) * time.Second
client.Logger = log.New(log.Default().Handler())
resp, err := client.Do(req)
if err != nil {
return false, fmt.Errorf("addr: %s, client.Do: %v", i.cfg.ShouldRunSpeedTestURL(), err)
}
defer resp.Body.Close()
sr := struct {
Success bool `json:"success,omitempty"`
Data bool `json:"data,omitempty"`
}{}
if err = json.NewDecoder(resp.Body).Decode(&sr); err != nil {
return false, fmt.Errorf("error parsing server response: %v", err)
}
return sr.Data, nil
}
func (i *imup) postSpeedTestRealtimeStatus(ctx context.Context, status string) error {
data := &realtimeApiPayload{
ID: i.cfg.HostID(), Key: i.cfg.APIKey(), Email: i.cfg.EmailAddress(), Data: status,
}
b, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("json.Marshal: %v", err)
}
return sendRealtimeData(ctx, bytes.NewBuffer(b), i.cfg.SpeedTestStatusUpdateURL())
}
func (i *imup) postSpeedTestRealtimeResults(ctx context.Context, status string, result *speedtesting.SpeedTestResult) error {
res := struct {
Data string `json:"data,omitempty"`
Download float64 `json:"download,omitempty"`
Upload float64 `json:"upload,omitempty"`
}{
Data: status,
Download: result.DownloadMbps,
Upload: result.UploadMbps,
}
data := &realtimeApiPayload{
ID: i.cfg.HostID(), Key: i.cfg.APIKey(), Email: i.cfg.EmailAddress(), Data: res,
}
b, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("marshal: %v", err)
}
return sendRealtimeData(ctx, bytes.NewBuffer(b), i.cfg.SpeedTestResultsURL())
}
// remoteConfigReload shares its config version with imup and determines if
// a new remote configuration is available
// this feature is WIP and not yet released
func (i *imup) remoteConfigReload(ctx context.Context) error {
// NOTE: this feature is only intended for (org) clients running with an API key
if i.cfg.APIKey() == "" {
return nil
}
data := &realtimeApiPayload{
ID: i.cfg.HostID(),
Email: i.cfg.EmailAddress(),
GroupID: i.cfg.GroupID(),
Key: i.cfg.APIKey(),
Version: i.cfg.Version(),
}
b, err := json.Marshal(data)
if err != nil {
return err
}
req, err := retryablehttp.NewRequest("POST", i.cfg.RealtimeConfigURL(), bytes.NewBuffer(b))
req = req.WithContext(ctx)
if err != nil {
return fmt.Errorf("creating request to check for a remote config %v", err)
}
req.Header.Set("Content-Type", "application/json")
client := retryablehttp.NewClient()
client.Backoff = exactJitterBackoff
client.RetryMax = 50_000
client.RetryWaitMin = time.Duration(30) * time.Second
client.RetryWaitMax = time.Duration(60) * time.Second
client.Logger = log.New(log.Default().Handler())
resp, err := client.Do(req)
if err != nil {
if err == context.Canceled {
return nil
}
return fmt.Errorf("error posting to %s :%s", i.cfg.RealtimeConfigURL(), err)
}
defer resp.Body.Close()
if retcode := resp.StatusCode; retcode == http.StatusOK {
if data, err := io.ReadAll(resp.Body); err != nil {
return fmt.Errorf("cannot read raw remote config from api %s", err)
} else {
i.reloadConfig(data)
}
} else if retcode == http.StatusNoContent {
log.Debug("config has not changed")
} else if i.cfg.Verbosity() == log.LevelDebug {
log.Debug("unexpected response returned from api", "retcode", retcode)
}
return nil
}