-
Notifications
You must be signed in to change notification settings - Fork 103
/
server.go
252 lines (220 loc) · 6.17 KB
/
server.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
// Copyright (c) 2018 PT Defender Nusa Semesta and contributors, All rights reserved.
//
// This file is part of Dsiem.
//
// Dsiem is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation version 3 of the License.
//
// Dsiem is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Dsiem. If not, see <https://www.gnu.org/licenses/>.
package server
import (
"errors"
"fmt"
"net"
"runtime"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/defenxor/dsiem/internal/pkg/dsiem/event"
log "github.com/defenxor/dsiem/internal/pkg/shared/logger"
"github.com/defenxor/dsiem/internal/pkg/dsiem/limiter"
"github.com/defenxor/dsiem/internal/pkg/dsiem/vice/nats"
"github.com/fasthttp-contrib/websocket"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/reuseport"
"context"
"github.com/buaazp/fasthttprouter"
rc "github.com/paulbellamy/ratecounter"
)
var connCounter uint64
var webDir, confDir string
var wss *wsServer
var upgrader websocket.Upgrader
var mode string
var transport nats.Transport
var epsLimiter *limiter.Limiter
var errChan <-chan error
var eventChan chan<- event.NormalizedEvent
var bpChan <-chan bool
// var msq string
var overloadFlag bool
var rateCounter = rc.NewRateCounter(1 * time.Second)
// Start starts the server
func Start(ch chan<- event.NormalizedEvent, bpCh <-chan bool, confd string, webd string,
writeableConfig bool, pprof bool, serverMode string, maxEPS int, minEPS int, msqCluster string,
msqPrefix string, nodeName string, addr string, port int) (err error) {
if a := net.ParseIP(addr); a == nil {
err = errors.New(addr + " is not a valid IP address")
return
}
if port < 1 || port > 65535 {
err = errors.New("Invalid TCP port number")
return
}
mode = serverMode
if mode == "cluster-frontend" {
initMsgQueue(msqCluster, msqPrefix, nodeName)
} else {
eventChan = ch
bpChan = bpCh
errChan = nil
}
// no need to check this, toctou issue
confDir = confd
webDir = webd
p := strconv.Itoa(port)
log.Info(log.M{Msg: "Server listening on " + addr + ":" + p})
router := fasthttprouter.New()
router.GET("/config/:filename", handleConfFileDownload)
router.GET("/config/", handleConfFileList)
router.GET("/debug/vars/", expVarHandler)
if pprof {
router.GET("/debug/pprof/:name", pprofHandler)
router.GET("/debug/pprof/", pprofHandler)
}
if writeableConfig {
router.POST("/config/:filename", handleConfFileUpload)
router.DELETE("/config/:filename", handleConfFileDelete)
}
if mode != "cluster-backend" {
initWSServer()
if maxEPS == 0 || minEPS == 0 {
router.POST("/events", handleEvents)
} else {
epsLimiter, err = limiter.New(maxEPS, minEPS)
if err != nil {
return
}
router.POST("/events", rateLimit(epsLimiter.Limit(), 3*time.Second, handleEvents))
}
router.GET("/eps/", wsHandler)
router.ServeFiles("/ui/*filepath", webDir)
overloadManager()
}
if runtime.GOOS == "windows" {
err = fasthttp.ListenAndServe(addr+":"+p, router.Handler)
} else {
ln, e := reuseport.Listen("tcp4", addr+":"+p)
if e != nil {
return e
}
err = fasthttp.Serve(ln, router.Handler)
}
return
}
// CounterRate return the rate of EPS
func CounterRate() int64 {
return rateCounter.Rate()
}
func increaseConnCounter() uint64 {
atomic.AddUint64(&connCounter, 1)
i := atomic.LoadUint64(&connCounter)
return i
}
func overloadManager() {
mu := sync.RWMutex{}
detector := func() {
for {
m := <-bpChan
if m != overloadFlag {
log.Info(log.M{Msg: "Received overload status change from " + strconv.FormatBool(overloadFlag) +
" to " + strconv.FormatBool(m) + " from backend"})
}
mu.Lock()
overloadFlag = m
mu.Unlock()
}
}
modifier := func() {
ticker := time.NewTicker(5 * time.Second)
go func() {
for {
res, current := 0, 0
<-ticker.C
if epsLimiter == nil {
continue
}
current = epsLimiter.Limit()
mu.RLock()
if overloadFlag {
res = epsLimiter.Lower()
} else {
res = epsLimiter.Raise()
}
if current != res {
log.Info(log.M{Msg: "Overload status is " + strconv.FormatBool(overloadFlag) +
", EPS limit changed from " + strconv.Itoa(current) + " to " + strconv.Itoa(res)})
}
mu.RUnlock()
}
}()
}
go detector()
go modifier()
}
func rateLimit(rps int, wait time.Duration, h fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(c *fasthttp.RequestCtx) {
// create a new context from the request with the wait timeout
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
// Wait errors out if the request cannot be processed within
// the deadline. This is preemptive, instead of waiting the
// entire duration.
if err := epsLimiter.Wait(ctx); err != nil {
fmt.Fprintf(c, "Too many requests\n")
c.SetStatusCode(fasthttp.StatusTooManyRequests)
return
}
h(c)
}
}
func initMsgQueue(msq string, prefix, nodeName string) {
const reconnectSecond = 3
initMsq := func() (err error) {
transport := nats.New()
transport.NatsAddr = msq
eventChan = transport.Send(prefix + "_" + "events")
errChan = transport.ErrChan()
bpChan = transport.ReceiveBool(prefix + "_" + "overload_signals")
select {
case err = <-errChan:
default:
}
return err
}
for {
err := initMsq()
if err != nil {
log.Info(log.M{Msg: "Error from message queue " + err.Error()})
log.Info(log.M{Msg: "Reconnecting in " + strconv.Itoa(reconnectSecond) + " seconds.."})
time.Sleep(reconnectSecond * time.Second)
continue
}
log.Info(log.M{Msg: "Successfully connected to message queue " + msq})
break
}
}
func initWSServer() {
wss = newWSServer()
go func() {
var c int
for {
c = len(wss.clients)
if c == 0 {
log.Debug(log.M{Msg: "WS server waiting for client connection."})
// wait until new client connected
<-wss.cConnectedCh
}
wss.sendAll(&message{rateCounter.Rate()})
time.Sleep(250 * time.Millisecond)
}
}()
}