This repository has been archived by the owner on Jun 7, 2020. It is now read-only.
/
model.go
350 lines (296 loc) · 7.37 KB
/
model.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package surge
import (
"bufio"
"fmt"
"math/rand"
"os"
"runtime"
"sort"
"strings"
"time"
)
// constants
const maxModels int = 16
const GWY = "I"
const SRV = "T"
// each model self-registers at startup
type ModelName string
// registration cb
func RegisterModel(name ModelName, model ModelInterface, props ...map[string]interface{}) {
if !inited {
__init()
}
assert(allModels[name] == nil, "already registered")
allModels[name] = model
allNamesSorted = append(allNamesSorted, string(name))
if len(props) > 0 {
allModelProps[name] = props[0]
// FIXME: either warn len > 1 or merge maps..
} else {
allModelProps[name] = make(map[string]interface{}, 0)
}
}
//
// globals & init
//
var inited = false
var allModels map[ModelName]ModelInterface // all registered models
var allModelProps map[ModelName]map[string]interface{}
var allNamesSorted []string
var Now = time.Time{}
var TimeNil = time.Time{}.Add(time.Hour * 10000)
var allGateways []NodeRunnerInterface
var allServers []NodeRunnerInterface
var allNodes []NodeRunnerInterface // a union of the previous two, for common ops
var eventsPastDeadline = 0
func init() {
if !inited {
__init()
}
}
func __init() {
allModels = make(map[ModelName]ModelInterface, maxModels)
allModelProps = make(map[ModelName]map[string]interface{}, maxModels)
if config.srand == 0 {
rand.Seed(time.Now().UTC().UnixNano())
} else {
rand.Seed(int64(config.srand))
}
inited = true
}
//
// all models implement the following interfaces
//
type ModelInterface interface {
NewGateway(id int) NodeRunnerInterface
NewServer(id int) NodeRunnerInterface
Configure() // model specific config
PreBuild()
PostBuild()
}
// Model Template
type ModelGeneric struct {
}
// abstract method
func (mg *ModelGeneric) NewGateway(id int) NodeRunnerInterface {
assert(false)
return nil
}
// abstract method
func (mg *ModelGeneric) NewServer(id int) NodeRunnerInterface {
assert(false)
return nil
}
func (mg *ModelGeneric) Configure() {}
func (mg *ModelGeneric) PreBuild() {}
func (mg *ModelGeneric) PostBuild() {}
//============================================================================
// common functions and main loop
//============================================================================
func NowIsDone() bool {
runtime.Gosched()
for ij := 0; ij < config.numGateways+config.numServers; ij++ {
r := allNodes[ij]
if !r.NowIsDone() {
return false
}
}
return true
}
//
// construct and container-ize all model's runners
//
func buildModel(model ModelInterface, name ModelName) {
ij := 0
allGateways = make([]NodeRunnerInterface, config.numGateways)
allServers = make([]NodeRunnerInterface, config.numServers)
allNodes = make([]NodeRunnerInterface, config.numGateways+config.numServers)
for i := 0; i < config.numGateways; i++ {
runnerid := i + 1
allGateways[i] = model.NewGateway(runnerid)
assert(allGateways[i] != nil)
allNodes[ij] = allGateways[i]
ij++
}
for j := 0; j < config.numServers; j++ {
runnerid := j + 1
allServers[j] = model.NewServer(runnerid)
assert(allServers[j] != nil)
allNodes[ij] = allServers[j]
ij++
}
for i := 0; i < config.numGateways; i++ {
gw := allGateways[i]
for j := 0; j < config.numServers; j++ {
sr := allServers[j]
txch := make(chan EventInterface, config.channelBuffer)
rxch := make(chan EventInterface, config.channelBuffer)
gw.setChannels(sr, txch, rxch)
sr.setChannels(gw, rxch, txch)
}
}
// init stats counters for the named model
mstats.init(name)
}
//
// graceful termination
//
func prepareToStopModel(model ModelInterface) {
for ij := 0; ij < config.numGateways+config.numServers; ij++ {
allNodes[ij].PrepareToStop()
}
}
//
// MAIN LOOP
//
func RunAllModels() {
// CLI and global defaults
Configure()
cnt := 0
onename := ""
for _, mname := range allNamesSorted {
if !strings.HasPrefix(mname, config.mprefix) {
continue
}
cnt++
onename = mname
}
if cnt == 1 {
nameLog(onename)
}
initLog()
defer terminateLog()
stdout := bufio.NewWriter(os.Stdout)
defer stdout.Flush()
hasprefix := 0
sort.Strings(allNamesSorted)
// shallow copy global config, restore prior to each model-run
configCopy := config
configNetworkCopy := configNetwork
configStorageCopy := configStorage
for _, sname := range allNamesSorted {
if !strings.HasPrefix(sname, config.mprefix) {
continue
}
if hasprefix > 0 {
log(LogBoth, "====")
}
hasprefix++
runtime.GC()
name := ModelName(sname)
props := allModelProps[name]
namedesc := "@" + string(name)
if desc, ok := props["description"]; ok {
namedesc += " [ " + desc.(string) + " ]"
}
log(LogBoth, "Model "+namedesc)
if maxprocs, ok := props["GOMAXPROCS"]; ok {
runtime.GOMAXPROCS(maxprocs.(int))
} else {
runtime.GOMAXPROCS(runtime.NumCPU()) // the default
}
eventsPastDeadline = 0
config = configCopy
configNetwork = configNetworkCopy
configStorage = configStorageCopy
model, _ := allModels[name]
model.Configure()
model.PreBuild() // Model specific build steps before generic build
buildModel(model, name)
model.PostBuild() // Model specific build steps after generic build
//
// log configuration
//
timestampLog(false)
configLog(true)
configLog(false)
timestampLog(true)
//
// run it servers first (as they typically do not start generating load)
//
Now = time.Time{}
for j := 0; j < config.numServers; j++ {
srv := allServers[j]
srv.Run()
}
time.Sleep(time.Microsecond)
Now = time.Time{}
// now the gateways..
for i := 0; i < config.numGateways; i++ {
gwy := allGateways[i]
gwy.Run()
}
//
// ONE MODEL MAIN LOOP
//
oneModelTimeLoop(model, stdout)
fmt.Printf("\r")
// benchmark results
timestampLog(false)
configLog(false)
mstats.log(true)
timestampLog(true)
}
if hasprefix == 0 {
fmt.Printf("No registered models matched prefix '%s': nothing to do\n", config.mprefix)
}
}
func oneModelTimeLoop(model ModelInterface, stdout *bufio.Writer) {
nextStatsTime := Now.Add(config.timeStatsIval)
nextTrackTime := Now.Add(config.timeTrackIval)
endtime := Now.Add(config.timeToRun)
realtime := time.Now()
pct := 0
timestampLog(false)
log(realtime.Format(time.RFC822))
timestampLog(true)
// advance the model's TIME and report stats periodically
for {
if !Now.Before(nextTrackTime) {
pct += 10
fmt.Printf("\r==== %2d%% done", pct)
stdout.Flush()
nextTrackTime = nextTrackTime.Add(config.timeTrackIval)
}
if NowIsDone() {
if !Now.Before(nextStatsTime) {
// new stats iteration
mstats.update(config.timeStatsIval)
nextStatsTime = Now.Add(config.timeStatsIval)
rt := time.Now()
if rt.Sub(realtime) > config.realtimeLogStats {
mstats.log(false)
realtime = rt
log(realtime.Format(time.RFC822) + " ====")
flushLog()
}
}
Now = Now.Add(config.timeIncStep)
} else {
time.Sleep(config.timeIncStep)
}
// past time-to-run gracefully terminate all model's runners
if !Now.Before(endtime) {
prepareToStopModel(model)
break
}
// Or, the model itself may have decided to stop running
if finishedRunning() {
break
}
}
if Now.Before(endtime) && endtime.Sub(Now) < config.timeClusterTrip {
Now = endtime
}
fmt.Printf("\r ")
stdout.Flush()
}
func finishedRunning() bool {
for ij := 0; ij < config.numGateways+config.numServers; ij++ {
r := allNodes[ij]
if r.GetState() <= RstateRunning {
return false
}
}
return true
}