-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogicgate.go
311 lines (249 loc) · 6.72 KB
/
logicgate.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
package cloud_computer
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"reflect"
"strings"
"syscall"
"time"
)
var ErrEmptySignals = errors.New("empty signals")
const DebugChannelName = "CLOUD_COMPUTER_DEBUG"
var InvalidElement = errors.New("invalid element")
var Inputs = make([]string, 0)
var Outputs = make([]string, 0)
var Name string
var UseOptimization bool = true
var IsDebugging bool
var IsVerbose bool
type BoolHandler func(inputs ...bool) (o []bool)
func init() {
parseArguments()
}
func getSelectCaseSignals(signals ...os.Signal) (sc reflect.SelectCase, err error) {
if len(signals) == 0 {
err = ErrEmptySignals
return
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, signals...)
sc = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(sigs),
}
return
}
func RunGateWithRedis(ctx context.Context, gate Gater) (err error) {
client := ConnectRedis()
gate.Init(ctx, client)
if gate.GetType() == "input" {
addInput(ctx, client, gate.GetName(), gate.GetName())
addChildren(ctx, client, gate.GetName())
}
if gate.GetType() == "alias" {
addOutput(ctx, client, gate.GetName(), gate.GetName())
}
// TODO: inputs, outputs가 redis에 붙는 동작은 여기서 진행해야 한다.
// Gate type은 좀 더 게이트 동작 그 자체에 집중할 수 있도록 수정 필요
cases := gate.SelectCases()
sc, err := getSelectCaseSignals(syscall.SIGINT, syscall.SIGTERM)
if err != nil {
panic(err)
}
cases = append(cases, sc)
defer func() {
deleteRedis(ctx, client, gate.GetName()+".status")
for _, element := range gate.GetOutputs() {
element.GateName = gate.GetName()
deleteRedis(ctx, client, element.String()+".status")
}
if gate.GetType() == "input" {
parents := strings.Split(gate.GetName(), ".")
grandParent := strings.Join(parents[:len(parents)-1], ".")
deleteRedis(ctx, client, grandParent+".inputs")
deleteRedis(ctx, client, grandParent+".children")
}
if gate.GetType() == "alias" {
parents := strings.Split(gate.GetName(), ".")
deleteRedis(ctx, client, strings.Join(parents[:len(parents)-1], ".")+".outputs")
}
}()
for {
index, value, ok := reflect.Select(cases)
if !ok {
return nil
}
if index == len(cases)-1 {
return nil
}
outputs, changed := gate.Handler(index, value.Bool())
if !changed {
continue
}
err = writeRedis(ctx, client, gate.GetName()+".status", outputs[0])
if err != nil {
panic(err)
}
for i, ch := range gate.GetOutputChannels() {
ch <- outputs[i]
}
}
return nil
}
// TODO: make redis as interface
func RunRedis(handler BoolHandler, name string, inputElements []Element, outputElements []Element, useShortcut bool, isAlias, isInput bool) (err error) {
ctx := context.TODO()
client := ConnectRedis()
if isInput {
addInput(ctx, client, name, name)
addChildren(ctx, client, name)
}
previousValues := make([]bool, len(inputElements))
previousOutputs := make([]bool, len(outputElements))
inputs := make([]<-chan bool, 0)
for i, element := range inputElements {
if element.IsStaticValue {
previousValues[i] = element.StaticValue
continue
}
inputs = append(inputs, ReadAsyncRedis(ctx, client, element.String()))
v, err := ReadRedis(ctx, client, element.String()+".status")
if err != nil {
panic(err)
}
if IsVerbose {
log.Println(i, v)
}
previousValues[i] = v
}
if isAlias {
addOutput(ctx, client, name, name)
}
// TODO: inputs와 이름의 차이가 큼. 수정할 것
outputChannels := make([]chan<- bool, 0)
for _, element := range outputElements {
element.GateName = name
outputChannels = append(outputChannels, WriteAsyncRedis(ctx, client, element.String()))
}
// TODO: 여기서 문제가 없을지 확인 필요하다. 과연...
previousOutputs = handler(previousValues...)
for i, ch := range outputChannels {
ch <- previousOutputs[i]
}
cases := make([]reflect.SelectCase, 0)
if IsDebugging {
debugInput := ReadAsyncRedis(ctx, client, DebugChannelName)
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(debugInput),
})
}
for _, ch := range inputs {
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ch),
})
}
sc, err := getSelectCaseSignals(syscall.SIGINT, syscall.SIGTERM)
if err != nil {
panic(err)
}
cases = append(cases, sc)
for {
index, value, ok := reflect.Select(cases)
if !ok {
break
}
if index == len(cases)-1 {
deleteRedis(ctx, client, name+".status")
for _, element := range outputElements {
element.GateName = name
deleteRedis(ctx, client, element.String()+".status")
//log.Println("removing", element.String()+".status")
}
if isInput {
parents := strings.Split(name, ".")
grandParent := strings.Join(parents[:len(parents)-1], ".")
deleteRedis(ctx, client, grandParent+".inputs")
deleteRedis(ctx, client, grandParent+".children")
}
if isAlias {
parents := strings.Split(name, ".")
deleteRedis(ctx, client, strings.Join(parents[:len(parents)-1], ".")+".outputs")
}
break
}
if IsDebugging {
if index == 0 {
outputs := handler(previousValues...)
if useShortcut && equalOutputs(previousOutputs, outputs) {
continue
}
for i, ch := range outputChannels {
ch <- outputs[i]
}
previousOutputs = outputs
continue
}
index -= 1
}
previousValues[index] = value.Bool()
outputs := handler(previousValues...)
if IsVerbose {
log.Println(outputs)
}
if useShortcut && equalOutputs(previousOutputs, outputs) {
continue
}
if IsVerbose {
log.Println("write", outputs)
log.Println(name+".status", outputs[0])
}
// WARN: 임시 코드. 좀 더 우아하게 수정할 것
err = writeRedis(ctx, client, name+".status", outputs[0])
if err != nil {
panic(err)
}
if !IsDebugging {
for i, ch := range outputChannels {
ch <- outputs[i]
}
previousOutputs = outputs
}
}
return nil
}
func Clock(clk int, outputElements []Element) (err error) {
log.Println(clk, outputElements)
ctx := context.TODO()
client := ConnectRedis()
name := fmt.Sprintf("clock.%dHz", clk)
err = writeRedis(ctx, client, name+".status", false)
if err != nil {
panic(err)
}
defer deleteRedis(ctx, client, name+".status")
outputs := make([]chan<- bool, 0)
for _, element := range outputElements {
element.GateName = name
outputs = append(outputs, WriteAsyncRedis(ctx, client, element.String()))
}
previousValues := false
for {
start := time.Now()
curr := !previousValues
err = writeRedis(ctx, client, name+".status", curr)
if err != nil {
panic(err)
}
for _, ch := range outputs {
ch <- curr
}
previousValues = curr
time.Sleep(time.Second/time.Duration(clk) - time.Now().Sub(start))
}
}