forked from hazelcast/hazelcast-go-client
/
main.go
230 lines (207 loc) · 5.55 KB
/
main.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
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"os/signal"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
"github.com/JorgenPo/hazelcast-go-client"
"github.com/JorgenPo/hazelcast-go-client/predicate"
"github.com/JorgenPo/hazelcast-go-client/serialization"
)
const displayDur = 10 * time.Second
const entryCount = 10_000
const goroutineCount = 10
var remainingGoroutines = int32(goroutineCount)
var tic time.Time
type Stats struct {
Id int
opCount int64
}
func (s *Stats) IncOpCount() {
atomic.AddInt64(&s.opCount, 1)
}
func (s *Stats) OpCountAndReset() int64 {
return atomic.SwapInt64(&s.opCount, 0)
}
const simpleEntryProcessorFactoryID = 66
const simpleEntryProcessorClassID = 1
type SimpleEntryProcessor struct {
value string
}
func (s SimpleEntryProcessor) FactoryID() int32 {
return simpleEntryProcessorFactoryID
}
func (s SimpleEntryProcessor) ClassID() int32 {
return simpleEntryProcessorClassID
}
func (s SimpleEntryProcessor) WriteData(output serialization.DataOutput) {
output.WriteString(s.value)
}
func (s *SimpleEntryProcessor) ReadData(input serialization.DataInput) {
s.value = input.ReadString()
}
type Factory struct {
}
func (f Factory) Create(id int32) serialization.IdentifiedDataSerializable {
if id == simpleEntryProcessorClassID {
return &SimpleEntryProcessor{}
}
panic(fmt.Sprintf("unknown class ID: %d", id))
}
func (f Factory) FactoryID() int32 {
return simpleEntryProcessorFactoryID
}
func displayStats(sts []*Stats) {
log.Println(strings.Repeat("*", 40))
totalOp := int64(0)
hanged := []int{}
toc := time.Now()
period := toc.Sub(tic)
tic = toc
for _, st := range sts {
total := st.OpCountAndReset()
totalOp += total
if total == 0 {
hanged = append(hanged, st.Id)
}
}
if len(hanged) == 0 {
log.Println("All goroutines worked without blocking")
} else {
log.Printf("%d goroutines hanged with ids: %v", len(hanged), hanged)
}
log.Println(strings.Repeat("-", 40))
log.Printf("OPS: %.2f (%d / %.2f)", float64(totalOp)/period.Seconds(), totalOp, period.Seconds())
}
func loadConfig(path string, cfg *hazelcast.Config) error {
text, err := ioutil.ReadFile(path)
if err != nil {
return err
}
if err = json.Unmarshal(text, cfg); err != nil {
return err
}
return nil
}
func createClient(ctx context.Context, configPath string) *hazelcast.Client {
config := hazelcast.NewConfig()
if configPath != "" {
log.Println("Configuration Path : ", configPath)
if err := loadConfig(configPath, &config); err != nil {
log.Fatal(err)
}
}
config.Serialization.SetIdentifiedDataSerializableFactories(&Factory{})
client, err := hazelcast.StartNewClientWithConfig(ctx, config)
if err != nil {
log.Fatal(err)
}
return client
}
func run(ctx context.Context, m *hazelcast.Map, st *Stats) {
var err error
for {
key := strconv.Itoa(rand.Intn(entryCount))
value := strconv.Itoa(rand.Intn(entryCount))
op := rand.Intn(100)
if op < 30 {
_, err = m.Get(ctx, key)
} else if op < 60 {
_, err = m.Put(ctx, key, value)
} else if op < 80 {
_, err = m.GetValuesWithPredicate(ctx, predicate.Between("this", 0, 10))
} else {
_, err = m.ExecuteOnEntries(ctx, &SimpleEntryProcessor{value: "test"})
}
if err != nil {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
break
}
log.Fatal(err)
}
st.IncOpCount()
}
log.Printf("Goroutine %d exited", st.Id)
atomic.AddInt32(&remainingGoroutines, -1)
}
func main() {
configPath := flag.String("c", "", "Path of the JSON configuration file.")
durStr := flag.String("d", "48h",
"Running time. You can use the following prefixes: s -> seconds, m -> minutes, h -> hours and their combinations, e.g., 2h30m")
flag.Parse()
dur, err := time.ParseDuration(*durStr)
if err != nil {
log.Fatal(err)
}
log.Println("Duration : ", dur)
log.Println("Goroutine Count : ", goroutineCount)
ctx, cancel := context.WithTimeout(context.Background(), dur)
defer cancel()
client := createClient(ctx, *configPath)
testMap, err := client.GetMap(ctx, "-test-map")
if err != nil {
log.Fatal(err)
}
tic = time.Now()
sts := make([]*Stats, goroutineCount)
for i := 0; i < goroutineCount; i++ {
st := &Stats{Id: i}
sts[i] = st
go run(ctx, testMap, st)
}
go func(ctx context.Context, sts []*Stats) {
ticker := time.NewTicker(displayDur)
defer ticker.Stop()
for {
select {
case <-ticker.C:
displayStats(sts)
case <-ctx.Done():
return
}
}
}(ctx, sts)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
select {
case <-ctx.Done():
case <-c:
}
displayStats(sts)
time.Sleep(10 * time.Second)
client.Shutdown(ctx)
log.Println(strings.Repeat("*", 40))
resultText := "SUCCESS"
if remainingGoroutines > 0 {
resultText = "FAILURE"
}
log.Printf("Soak test finished with %s.\n", resultText)
log.Printf("Remaining goroutine count: %d", remainingGoroutines)
log.Println(strings.Repeat("-", 40))
}