-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstorage.go
100 lines (88 loc) · 2.56 KB
/
storage.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
package main
import (
"encoding/json"
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/oschwald/geoip2-golang"
"github.com/satori/go.uuid"
"gopkg.in/olivere/elastic.v3"
)
func ListBins(redisClient redis.Conn) []string {
bins, err := redis.Strings(redisClient.Do("SMEMBERS", "bins"))
if err != nil {
panic(err)
}
return bins
}
func ListRequestsFromBin(redisClient redis.Conn, binId string) []HttpRequest {
raw_requests, err := redis.Strings(redisClient.Do("LRANGE", "bins:"+binId, 0, 10))
if err != nil {
panic(err)
}
var requests = make([]HttpRequest, len(raw_requests))
for i, item := range raw_requests {
if err = json.Unmarshal([]byte(item), &requests[i]); err != nil {
panic(err)
}
}
return requests
}
type HttpRequestWriter interface {
WriteHttpRequest(request HttpRequest) error
}
type TcpRequestWriter interface {
WriteTcpRequest(request TcpRequest) error
}
type RedisHttpRequestWriter struct {
client redis.Conn
}
func (w RedisHttpRequestWriter) WriteHttpRequest(request HttpRequest) error {
serialised, err := json.Marshal(request)
if err != nil {
panic(err)
}
binKey := "bins:" + request.BinId
if _, err := w.client.Do("SADD", "bins", request.BinId); err != nil {
fmt.Println(err)
}
if _, err := w.client.Do("LPUSH", binKey, string(serialised)); err != nil {
fmt.Println(err)
}
if _, err := w.client.Do("EXPIRE", binKey, 3600*24); err != nil {
fmt.Println(err)
}
return nil
}
type ElasticsearchRequestWriter struct {
client *elastic.Client
GeoIPDB *geoip2.Reader
}
func (w ElasticsearchRequestWriter) WriteJSONRequest(requestType string, request interface{}) error {
_, err := w.client.Index().
Index("requestbin").
Type(requestType).
BodyJson(request).
Id(uuid.NewV4().String()).
Do()
if err != nil {
fmt.Println("Failed to save to ElasticSearch")
fmt.Println(err)
}
return err
}
func (w ElasticsearchRequestWriter) WriteTcpRequest(request TcpRequest) error {
lat, lon, _ := RemoteAddrToGeoIP(w.GeoIPDB, request.RemoteAddr)
record := struct {
Request interface{} `json:"request"`
Location elastic.GeoPoint `json:"location"`
}{Request: request, Location: *elastic.GeoPointFromLatLon(lat, lon)}
return w.WriteJSONRequest("tcp", record)
}
func (w ElasticsearchRequestWriter) WriteHttpRequest(request HttpRequest) error {
lat, lon, _ := RemoteAddrToGeoIP(w.GeoIPDB, request.RemoteAddr)
record := struct {
Request interface{} `json:"request"`
Location elastic.GeoPoint `json:"location"`
}{Request: request, Location: *elastic.GeoPointFromLatLon(lat, lon)}
return w.WriteJSONRequest("http", record)
}