/
repo.go
276 lines (232 loc) · 7.04 KB
/
repo.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
package syntheticsstub
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"strconv"
"sync"
"time"
)
const itemNotFound = -1
// SyntheticsRepo is local storage for Synthetics data
type SyntheticsRepo struct {
fileName string
lock sync.RWMutex
tests []V202101beta1Test
agents []V202101beta1Agent
health []V202101beta1TestHealth
ipInfo []V202101beta1IpInfo
traceRoutes []V202101beta1TracerouteResult
}
// syntheticsStorage is internally used for marshall/unmarshall the data as JSON
type syntheticsStorage struct {
Tests []V202101beta1Test
Agents []V202101beta1Agent
Health []V202101beta1TestHealth
IpInfo []V202101beta1IpInfo
TraceRoutes []V202101beta1TracerouteResult
}
func NewSyntheticsRepo(fileName string) *SyntheticsRepo {
r := &SyntheticsRepo{
fileName: fileName,
tests: make([]V202101beta1Test, 0),
agents: make([]V202101beta1Agent, 0),
}
r.load()
return r
}
func (r *SyntheticsRepo) GetTest(id string) *V202101beta1Test {
r.lock.RLock()
defer r.lock.RUnlock()
index := r.findTestByID(id)
if index == itemNotFound {
return nil
}
copyItem := r.tests[index]
return ©Item
}
func (r *SyntheticsRepo) ListTests() []V202101beta1Test {
r.lock.RLock()
defer r.lock.RUnlock()
copyItems := make([]V202101beta1Test, len(r.tests), len(r.tests))
copy(copyItems, r.tests)
return copyItems
}
// NOTE: multiple tests with same name are allowed
func (r *SyntheticsRepo) CreateTest(t V202101beta1Test) (*V202101beta1Test, error) {
// NOTE: add input "t" validation here if it turns out to be useful
r.lock.Lock()
defer r.lock.Unlock()
newTest := t
newTest.Id = r.allocateNewTestID()
newTest.Cdate = time.Now()
r.tests = append(r.tests, newTest)
r.save()
return &newTest, nil
}
// NOTE: in live server PATCH comes with update mask; here we just update the entire test object for simplicity
func (r *SyntheticsRepo) PatchTest(t V202101beta1Test) (*V202101beta1Test, error) {
r.lock.Lock()
defer r.lock.Unlock()
index := r.findTestByID(t.Id)
if index == itemNotFound {
return nil, fmt.Errorf("test of id %q doesn't exists", t.Id)
}
r.tests[index] = t
r.save()
return &t, nil
}
func (r *SyntheticsRepo) DeleteTest(id string) error {
r.lock.Lock()
defer r.lock.Unlock()
index := r.findTestByID(id)
if index == itemNotFound {
return fmt.Errorf("test of id %q doesn't exists", id)
}
r.tests = append(r.tests[:index], r.tests[index+1:]...)
r.save()
return nil
}
func (r *SyntheticsRepo) UpdateTestStatus(id string, status V202101beta1TestStatus) error {
r.lock.Lock()
defer r.lock.Unlock()
index := r.findTestByID(id)
if index == itemNotFound {
return fmt.Errorf("test of id %q doesn't exists", id)
}
r.tests[index].Status = status
return nil
}
func (r *SyntheticsRepo) DeleteAgent(id string) error {
r.lock.Lock()
defer r.lock.Unlock()
itemIndex := r.findAgentByID(id)
if itemIndex == itemNotFound {
return fmt.Errorf("agent of id %q doesn't exists", id)
}
r.agents = append(r.agents[:itemIndex], r.agents[itemIndex+1:]...)
r.save()
return nil
}
func (r *SyntheticsRepo) GetAgent(id string) *V202101beta1Agent {
r.lock.RLock()
defer r.lock.RUnlock()
index := r.findAgentByID(id)
if index == itemNotFound {
return nil
}
copyItem := r.agents[index]
return ©Item
}
// NOTE: in live server PATCH comes with update mask; here we just update the entire agent object for simplicity
func (r *SyntheticsRepo) PatchAgent(a V202101beta1Agent) (*V202101beta1Agent, error) {
r.lock.Lock()
defer r.lock.Unlock()
index := r.findAgentByID(a.Id)
if index == itemNotFound {
return nil, fmt.Errorf("agent of id %q doesn't exists", a.Id)
}
r.agents[index] = a
r.save()
return &r.agents[index], nil
}
func (r *SyntheticsRepo) ListAgents() []V202101beta1Agent {
r.lock.RLock()
defer r.lock.RUnlock()
copyItems := make([]V202101beta1Agent, len(r.agents), len(r.agents))
copy(copyItems, r.agents)
return copyItems
}
// NOTE: in live server GetHealthForTests comes with set of filters; here we just return same result everytime for simplicity
func (r *SyntheticsRepo) GetHealthForTests() []V202101beta1TestHealth {
// no lock needed as this collection is read-only
copyItems := make([]V202101beta1TestHealth, len(r.health), len(r.health))
copy(copyItems, r.health)
return copyItems
}
// NOTE: in live server GetIpInfo comes with set of filters; here we just return same result everytime for simplicity
func (r *SyntheticsRepo) GetIpInfo() []V202101beta1IpInfo {
// no lock needed as this collection is read-only
copyItems := make([]V202101beta1IpInfo, len(r.ipInfo), len(r.ipInfo))
copy(copyItems, r.ipInfo)
return copyItems
}
// NOTE: in live server GetTraceRoutes comes with set of filters; here we just return same result everytime for simplicity
func (r *SyntheticsRepo) GetTraceRoutes() []V202101beta1TracerouteResult {
// no lock needed as this collection is read-only
copyItems := make([]V202101beta1TracerouteResult, len(r.traceRoutes), len(r.traceRoutes))
copy(copyItems, r.traceRoutes)
return copyItems
}
func (r *SyntheticsRepo) findTestByID(id string) int {
// r.lock should be already in locked state at this point
for i, item := range r.tests {
if item.Id == id {
return i
}
}
return itemNotFound
}
func (r *SyntheticsRepo) findAgentByID(id string) int {
// r.lock should be already in locked state at this point
for i, item := range r.agents {
if item.Id == id {
return i
}
}
return itemNotFound
}
func (r *SyntheticsRepo) allocateNewTestID() string {
// r.lock should be already in locked state at this point
var id int
for _, item := range r.tests {
itemID, err := strconv.Atoi(item.Id)
if err != nil {
itemID = 1000000 // str conversion error, assume some high integer for the id
}
if itemID > id {
id = itemID
}
}
return strconv.FormatInt(int64(id)+1, 10)
}
func (r *SyntheticsRepo) load() {
// r.lock should be already in locked state at this point
bytes, err := ioutil.ReadFile(r.fileName)
if err != nil {
log.Printf("SyntheticsRepo storage %q not found. Starting with fresh one", r.fileName)
return // nothing to load is ok
}
var storage syntheticsStorage
err = json.Unmarshal(bytes, &storage)
if err != nil {
log.Printf("SyntheticsRepo unmarshal from %q failed: %v", r.fileName, err)
panic(err) // loading invalid data is not ok
}
r.tests = storage.Tests
r.agents = storage.Agents
r.health = storage.Health
r.ipInfo = storage.IpInfo
r.traceRoutes = storage.TraceRoutes
log.Printf("SyntheticsRepo successfuly loaded from %q, num tests: %d, num agents: %d, num health: %d, num ipInfo: %d, num traceRoutes: %d",
r.fileName, len(r.tests), len(r.agents), len(r.health), len(r.ipInfo), len(r.traceRoutes))
}
func (r *SyntheticsRepo) save() {
// r.lock should be already in locked state at this point
storage := syntheticsStorage{
Tests: r.tests,
Agents: r.agents,
Health: r.health,
IpInfo: r.ipInfo,
TraceRoutes: r.traceRoutes,
}
bytes, err := json.MarshalIndent(&storage, "", " ")
if err != nil {
panic(err)
}
err = ioutil.WriteFile(r.fileName, bytes, 0644)
if err != nil {
panic(err)
}
}