-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
176 lines (145 loc) · 4.65 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
package main
import (
"errors"
"math/rand"
"net"
"os"
"strings"
"sync"
"time"
"github.com/Shopify/sarama"
log "github.com/Sirupsen/logrus"
"github.com/golang/protobuf/proto"
"github.com/larskluge/babl-server/kafka"
u "github.com/larskluge/babl-server/utils"
"github.com/larskluge/babl/bablmodule"
bn "github.com/larskluge/babl/bablnaming"
pb "github.com/larskluge/babl/protobuf"
pbm "github.com/larskluge/babl/protobuf/messages"
"golang.org/x/net/context"
)
type server struct {
kafkaClient *sarama.Client
kafkaProducer *sarama.SyncProducer
}
type responses struct {
channels map[uint64]chan *[]byte
mux sync.Mutex
}
const (
Version = "2.3.1"
ModuleExecutionTimeout = 3 * time.Minute
ModuleExecutionGrace = 1 * time.Minute
MaxGrpcMessageSize = 1024 * 1024 * 1 // 1mb
)
var (
debug bool
hostname string
resp responses
Random = rand.New(rand.NewSource(time.Now().UnixNano()))
)
func main() {
log.SetOutput(os.Stderr)
log.SetFormatter(&log.JSONFormatter{})
app := configureCli()
app.Run(os.Args)
}
func run(listen, kafkaBrokers string, dbg bool) {
debug = dbg
if debug {
log.SetLevel(log.DebugLevel)
}
hostname = Hostname()
resp = responses{channels: make(map[uint64]chan *[]byte)}
lis, err := net.Listen("tcp", listen)
if err != nil {
log.WithFields(log.Fields{"error": err, "listen": listen}).Fatal("Failed to listen at port")
}
s := server{}
server := NewServer()
brokers := strings.Split(kafkaBrokers, ",")
clientID := "supervisor." + hostname
s.kafkaClient = kafka.NewClient(brokers, clientID, debug)
defer (*s.kafkaClient).Close()
s.kafkaProducer = kafka.NewProducer(brokers, clientID+".producer")
defer (*s.kafkaProducer).Close()
newModulesChan := make(chan string)
go discoverModules(s.kafkaClient, newModulesChan)
go func() {
for module := range newModulesChan {
log.Infof("New Module Discovered: %s", module)
m := bablmodule.New(module)
pb.RegisterBinaryServer(m.GrpcServiceName(), server, &s)
}
}()
go listenToModuleResponses(s.kafkaClient)
log.Warnf("Server started at %s", listen)
server.Serve(lis)
}
func (s *server) IO(ctx context.Context, req *pbm.BinRequest) (*pbm.BinReply, error) {
start := time.Now()
res := &pbm.BinReply{}
rid := uint64(Random.Uint32())<<32 + uint64(Random.Uint32())
req.Id = rid
_, async := req.Env["BABL_ASYNC"]
key := hostname + "." + u.FmtRid(rid)
// Sends message to the babl module topic: e.g. "babl.larskluge.ImageResize.IO"
topic := bn.RequestPathToTopic(MethodFromContext(ctx))
module := bn.TopicToModule(topic)
req.Module = module
l := log.WithFields(log.Fields{"module": module, "rid": u.FmtRid(rid)})
msg, err := proto.Marshal(req)
if err != nil {
return nil, err
}
l.WithFields(log.Fields{"message_size": len(msg), "code": "req-enqueued"}).Info("Send message to module")
kafka.SendMessage(s.kafkaProducer, key, topic, &msg)
if async {
elapsed := float64(time.Since(start).Seconds() * 1000)
l.WithFields(log.Fields{"duration_ms": elapsed}).Info("Request processed async")
return res, nil
}
resp.mux.Lock()
resp.channels[rid] = make(chan *[]byte, 1)
resp.mux.Unlock()
defer func() {
resp.mux.Lock()
close(resp.channels[rid])
delete(resp.channels, rid)
resp.mux.Unlock()
}()
timeLeft := ModuleExecutionTimeout
gracePeriodOver := false
for {
select {
case data := <-resp.channels[rid]:
elapsed := float64(time.Since(start).Seconds() * 1000)
if err := proto.Unmarshal(*data, res); err != nil {
return nil, err
}
if res.Error != "" {
l = l.WithFields(log.Fields{"error": res.Error})
}
l.WithFields(log.Fields{"duration_ms": elapsed, "code": "completed", "status": res.Status.String()}).Info("Module responded")
return res, nil
case <-time.After(timeLeft):
if gracePeriodOver {
errorMsg := "Module did not respond in grace period,timeout"
l.WithFields(log.Fields{"timeout": ModuleExecutionTimeout + ModuleExecutionGrace, "rid": rid, "code": "completed", "status": pbm.BinReply_MODULE_RESPONSE_TIMEOUT.String(), "error": errorMsg}).Error(errorMsg)
return nil, errors.New("Module execution timed out")
} else {
l.WithFields(log.Fields{"timeout": ModuleExecutionTimeout, "rid": rid, "code": "req-execution-canceling"}).Warn("Module did not respond in time, cancelling request execution")
if err := s.BroadcastCancelRequest(module, rid); err != nil {
l.WithError(err).Warn("Broadcasting cancel request failed")
}
// start over with grace period
timeLeft = ModuleExecutionGrace
gracePeriodOver = true
continue
}
}
}
}
func (s *server) Ping(ctx context.Context, req *pbm.Empty) (*pbm.Pong, error) {
return &pbm.Pong{Val: "pong from supervisor"}, nil
}