Skip to content

Commit 66993a2

Browse files
authored
[refactor] Clean-up tests from #2188 (#2200)
Signed-off-by: Yuri Shkuro <ys@uber.com>
1 parent b687b1b commit 66993a2

File tree

2 files changed

+78
-45
lines changed

2 files changed

+78
-45
lines changed

plugin/sampling/strategystore/static/strategy_store.go

+22-17
Original file line numberDiff line numberDiff line change
@@ -84,35 +84,40 @@ func (h *strategyStore) Close() {
8484
}
8585

8686
func (h *strategyStore) autoUpdateStrategies(interval time.Duration, filePath string) {
87-
lastString := ""
87+
lastValue := ""
8888
ticker := time.NewTicker(interval)
8989
defer ticker.Stop()
9090
for {
9191
select {
9292
case <-ticker.C:
93-
currBytes, err := ioutil.ReadFile(filepath.Clean(filePath))
94-
if err != nil {
95-
h.logger.Error("ReadFile failed", zap.Error(err))
96-
}
97-
currStr := string(currBytes)
98-
if lastString == currStr {
99-
continue
100-
}
101-
if err = h.updateSamplingStrategy(currBytes); err != nil {
102-
h.logger.Error("UpdateSamplingStrategy failed", zap.Error(err))
103-
}
104-
lastString = currStr
105-
93+
lastValue = h.reloadSamplingStrategyFile(filePath, lastValue)
10694
case <-h.ctx.Done():
10795
return
10896
}
10997
}
11098
}
11199

100+
func (h *strategyStore) reloadSamplingStrategyFile(filePath string, lastValue string) string {
101+
currBytes, err := ioutil.ReadFile(filepath.Clean(filePath))
102+
if err != nil {
103+
h.logger.Error("failed to load sampling strategies", zap.String("file", filePath), zap.Error(err))
104+
return lastValue
105+
}
106+
newValue := string(currBytes)
107+
if lastValue == newValue {
108+
return lastValue
109+
}
110+
if err = h.updateSamplingStrategy(currBytes); err != nil {
111+
h.logger.Error("failed to update sampling strategies from file", zap.Error(err))
112+
return lastValue
113+
}
114+
return newValue
115+
}
116+
112117
func (h *strategyStore) updateSamplingStrategy(bytes []byte) error {
113118
var strategies strategies
114119
if err := json.Unmarshal(bytes, &strategies); err != nil {
115-
return fmt.Errorf("failed to unmarshal strategies: %w", err)
120+
return fmt.Errorf("failed to unmarshal sampling strategies: %w", err)
116121
}
117122
h.parseStrategies(&strategies)
118123
h.logger.Info("Updated sampling strategies:" + string(bytes))
@@ -124,12 +129,12 @@ func loadStrategies(strategiesFile string) (*strategies, error) {
124129
if strategiesFile == "" {
125130
return nil, nil
126131
}
127-
bytes, err := ioutil.ReadFile(strategiesFile) /* nolint #nosec , this comes from an admin, not user */
132+
data, err := ioutil.ReadFile(strategiesFile) /* nolint #nosec , this comes from an admin, not user */
128133
if err != nil {
129134
return nil, fmt.Errorf("failed to open strategies file: %w", err)
130135
}
131136
var strategies strategies
132-
if err := json.Unmarshal(bytes, &strategies); err != nil {
137+
if err := json.Unmarshal(data, &strategies); err != nil {
133138
return nil, fmt.Errorf("failed to unmarshal strategies: %w", err)
134139
}
135140
return &strategies, nil

plugin/sampling/strategystore/static/strategy_store_test.go

+56-28
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"github.com/stretchr/testify/assert"
2525
"github.com/stretchr/testify/require"
2626
"go.uber.org/zap"
27+
"go.uber.org/zap/zaptest/observer"
2728

2829
"github.com/jaegertracing/jaeger/pkg/testutils"
2930
"github.com/jaegertracing/jaeger/thrift-gen/sampling"
@@ -242,54 +243,81 @@ func TestDeepCopy(t *testing.T) {
242243
SamplingRate: 0.5,
243244
},
244245
}
245-
copy := deepCopy(s)
246-
assert.False(t, copy == s)
247-
assert.EqualValues(t, copy, s)
246+
cp := deepCopy(s)
247+
assert.False(t, cp == s)
248+
assert.EqualValues(t, cp, s)
248249
}
249250

250251
func TestAutoUpdateStrategy(t *testing.T) {
251-
// copy from fixtures/strategies.json
252252
tempFile, _ := ioutil.TempFile("", "for_go_test_*.json")
253-
tempFile.Close()
253+
require.NoError(t, tempFile.Close())
254+
defer func() {
255+
require.NoError(t, os.Remove(tempFile.Name()))
256+
}()
254257

258+
// copy known fixture content into temp file which we can later overwrite
255259
srcFile, dstFile := "fixtures/strategies.json", tempFile.Name()
256260
srcBytes, err := ioutil.ReadFile(srcFile)
257261
require.NoError(t, err)
258-
err = ioutil.WriteFile(dstFile, srcBytes, 0644)
259-
require.NoError(t, err)
262+
require.NoError(t, ioutil.WriteFile(dstFile, srcBytes, 0644))
260263

261-
interval := time.Millisecond * 10
262-
store, err := NewStrategyStore(Options{
264+
ss, err := NewStrategyStore(Options{
263265
StrategiesFile: dstFile,
264-
ReloadInterval: interval,
266+
ReloadInterval: time.Millisecond * 10,
265267
}, zap.NewNop())
266268
require.NoError(t, err)
267-
defer store.(*strategyStore).Close()
269+
store := ss.(*strategyStore)
270+
defer store.Close()
268271

272+
// confirm baseline value
269273
s, err := store.GetSamplingStrategy("foo")
270274
require.NoError(t, err)
271275
assert.EqualValues(t, makeResponse(sampling.SamplingStrategyType_PROBABILISTIC, 0.8), *s)
272276

273-
// update file
274-
newStr := strings.Replace(string(srcBytes), "0.8", "0.9", 1)
275-
err = ioutil.WriteFile(dstFile, []byte(newStr), 0644)
276-
require.NoError(t, err)
277-
278-
// wait for reloading
279-
time.Sleep(interval * 4)
277+
// verify that reloading in no-op
278+
value := store.reloadSamplingStrategyFile(dstFile, string(srcBytes))
279+
assert.Equal(t, string(srcBytes), value)
280280

281-
// verity reloading
282-
s, err = store.GetSamplingStrategy("foo")
283-
require.NoError(t, err)
281+
// update file with new probability of 0.9
282+
newStr := strings.Replace(string(srcBytes), "0.8", "0.9", 1)
283+
require.NoError(t, ioutil.WriteFile(dstFile, []byte(newStr), 0644))
284+
285+
// wait for reload timer
286+
for i := 0; i < 1000; i++ { // wait up to 1sec
287+
s, err = store.GetSamplingStrategy("foo")
288+
require.NoError(t, err)
289+
if s.ProbabilisticSampling != nil && s.ProbabilisticSampling.SamplingRate == 0.9 {
290+
break
291+
}
292+
time.Sleep(1 * time.Millisecond)
293+
}
284294
assert.EqualValues(t, makeResponse(sampling.SamplingStrategyType_PROBABILISTIC, 0.9), *s)
295+
}
285296

286-
// check bad file content
287-
_ = ioutil.WriteFile(dstFile, []byte("bad value"), 0644)
288-
time.Sleep(interval * 2)
297+
func TestAutoUpdateStrategyErrors(t *testing.T) {
298+
tempFile, _ := ioutil.TempFile("", "for_go_test_*.json")
299+
require.NoError(t, tempFile.Close())
300+
defer func() {
301+
_ = os.Remove(tempFile.Name())
302+
}()
303+
304+
zapCore, logs := observer.New(zap.InfoLevel)
305+
logger := zap.New(zapCore)
306+
307+
s, err := NewStrategyStore(Options{
308+
StrategiesFile: "fixtures/strategies.json",
309+
ReloadInterval: time.Hour,
310+
}, logger)
311+
require.NoError(t, err)
312+
store := s.(*strategyStore)
313+
defer store.Close()
289314

290-
// remove file(test read file failure)
291-
_ = os.Remove(dstFile)
292-
// wait for delete and update failure
293-
time.Sleep(interval * 2)
315+
// check invalid file path or read failure
316+
assert.Equal(t, "blah", store.reloadSamplingStrategyFile(tempFile.Name()+"bad-path", "blah"))
317+
assert.Len(t, logs.FilterMessage("failed to load sampling strategies").All(), 1)
294318

319+
// check bad file content
320+
require.NoError(t, ioutil.WriteFile(tempFile.Name(), []byte("bad value"), 0644))
321+
assert.Equal(t, "blah", store.reloadSamplingStrategyFile(tempFile.Name(), "blah"))
322+
assert.Len(t, logs.FilterMessage("failed to update sampling strategies from file").All(), 1)
295323
}

0 commit comments

Comments
 (0)