/
zeus_simulator.go
128 lines (113 loc) · 2.59 KB
/
zeus_simulator.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
package main
import (
"errors"
"fmt"
"log"
"net"
"sync"
"github.com/formicidae-tracker/olympus/pkg/tm"
"github.com/formicidae-tracker/zeus/internal/zeus"
"github.com/formicidae-tracker/zeus/pkg/zeuspb"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc"
)
type ZeusSimulator struct {
zeuspb.UnimplementedZeusServer
stop, idle chan struct{}
mx sync.RWMutex
zones map[string]ZoneClimateRunner
server *grpc.Server
}
type ZeusSimulatorArgs struct {
hostname string
season zeus.SeasonFile
timeRatio float64
olympusAddress string
rpcPort int
}
func NewZeusSimulator(a ZeusSimulatorArgs) (s *ZeusSimulator, err error) {
res := &ZeusSimulator{
stop: make(chan struct{}),
idle: make(chan struct{}),
zones: make(map[string]ZoneClimateRunner),
}
address := fmt.Sprintf(":%d", a.rpcPort)
l, err := res.setUpServer(address)
if err != nil {
return nil, err
}
go res.serve(l)
defer func() {
if err != nil {
res.shutdown()
}
}()
for zoneName, climate := range a.season.Zones {
if err := func() error {
res.mx.Lock()
defer res.mx.Unlock()
runner, err := NewZoneClimateStub(ZoneClimateStubArgs{
hostname: a.hostname,
zoneName: zoneName,
climate: climate,
timeRatio: a.timeRatio,
olympusAddress: a.olympusAddress,
rpcPort: a.rpcPort,
})
if err != nil {
return err
}
res.zones[zoneName] = runner
go runner.Run()
return nil
}(); err != nil {
return nil, err
}
}
return res, nil
}
func (s *ZeusSimulator) shutdown() (err error) {
var errs []error
s.mx.Lock()
defer func() {
s.mx.Unlock()
if recover() != nil {
errs = append(errs, errors.New("already closed"))
}
<-s.idle
err = errors.Join(errs...)
}()
for _, r := range s.zones {
errs = append(errs, r.Close())
}
s.zones = make(map[string]ZoneClimateRunner)
close(s.stop)
return nil
}
func (s *ZeusSimulator) setUpServer(address string) (net.Listener, error) {
l, err := net.Listen("tcp", address)
if err != nil {
return nil, err
}
options := []grpc.ServerOption{}
if tm.Enabled() {
options = append(options,
grpc.UnaryInterceptor(otelgrpc.UnaryServerInterceptor()),
grpc.StreamInterceptor(otelgrpc.StreamServerInterceptor()),
)
}
s.server = grpc.NewServer(options...)
zeuspb.RegisterZeusServer(s.server, s)
return l, nil
}
func (s *ZeusSimulator) serve(l net.Listener) {
go func() {
<-s.stop
s.server.GracefulStop()
close(s.idle)
}()
err := s.server.Serve(l)
if err != nil {
log.Printf("server error: %s", err)
}
}