forked from idekerlab/cxmateold
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
180 lines (166 loc) · 4.87 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
177
178
179
180
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"github.com/ericsage/cxmate/cxpb"
"github.com/ericsage/cxmate/metrics"
"github.com/golang/protobuf/jsonpb"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc"
)
var (
requestsCounter = metrics.NewCounter(
"cxmate_requests_total",
"Number of total requests processed by cxmate",
[]string{},
)
errorCounter = metrics.NewCounter(
"cxmate_response_with_errors_total",
"Number of responses that contained at least one error",
[]string{},
)
errorsCounter = metrics.NewCounter(
"cxmate_sent_errors_total",
"Total number of errors sent by cxmate to clients",
[]string{},
)
sentParametersCounter = metrics.NewCounter(
"cxmate_recieved_parameter_total",
"Number of times each parameter key/value recieved by cxmate",
[]string{"name", "value"},
)
)
var (
listeningAddress = getenv("LISTENING_ADDRESS", "0.0.0.0")
listeningPort = getenv("LISTENING_PORT", "80")
serverAddress = getenv("SERVICE_ADDRESS", "127.0.0.1")
serverPort = getenv("SERVICE_PORT", "8080")
requiresCollection, _ = strconv.ParseBool(getenv("RECEIVES_COLLECTION", "false"))
requiredNumNetworks, _ = strconv.ParseInt(getenv("EXPECTED_NUM_NETWORKS", "1"), 10, 64)
requiredAspects = strings.Split(getenv("RECEIVES_ASPECTS", "edges, nodes, nodeAttributes, edgeAttributes, networkAttributes"), ",")
sendsCollection, _ = strconv.ParseBool(getenv("SENDS_COLLECTION", "false"))
sendNumNetworks, _ = strconv.ParseInt(getenv("SENDS_NUM_NETWORKS", "1"), 10, 64)
sendingAspects = strings.Split(getenv("SENDS_ASPECTS", "edges, nodes, nodeAttributes, edgeAttributes, networkAttributes"), ",")
)
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
func main() {
handler := CXHandler
address := listeningAddress + ":" + listeningPort
s := &http.Server{
Addr: address,
Handler: http.HandlerFunc(handler),
}
fmt.Println("Config:")
fmt.Println("Listening at address:", listeningAddress)
fmt.Println("Listening on port:", listeningPort)
fmt.Println("Proxying for service at address", serverAddress)
fmt.Println("Proxying for service on port", serverPort)
fmt.Println("Receiving a collection:", requiresCollection)
fmt.Println("Receives", requiredNumNetworks, "network(s)")
fmt.Println("Receiving aspects:", requiredAspects)
fmt.Println("Sending a collection:", sendsCollection)
fmt.Println("Sends", sendNumNetworks, "network(s)")
fmt.Println("Sending aspects:", sendingAspects)
fmt.Println("Now listening...")
go metrics.Serve()
log.Fatal(s.ListenAndServe())
}
//CXHandler handles CX
func CXHandler(res http.ResponseWriter, req *http.Request) {
requestsCounter.With(prometheus.Labels{}).Inc()
params := req.URL.Query()
streamNetwork(req.Body, res, params)
}
func streamNetwork(in io.Reader, out io.Writer, params map[string][]string) {
address := serverAddress + ":" + serverPort
conn, err := grpc.Dial(address, grpc.WithInsecure())
defer conn.Close()
if err != nil {
panic("Could not establish connection")
}
client := cxpb.NewCyServiceClient(conn)
stream, err := client.StreamElements(context.Background())
if err != nil {
panic("Could not open stream")
}
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
decOpt := &cxpb.DecoderOptions{
RequiredAspects: requiredAspects,
IsCollection: requiresCollection,
NumNetworks: requiredNumNetworks,
}
sendParams(stream.Send, params)
decoder := cxpb.NewDecoder(in, decOpt, stream.Send)
decoder.Decode()
stream.CloseSend()
}()
go func() {
defer wg.Done()
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in encoder, panic:", r)
}
}()
encOpt := &cxpb.EncoderOptions{
RequiredAspects: sendingAspects,
IsCollection: sendsCollection,
NumNetworks: sendNumNetworks,
}
encoder := cxpb.NewEncoder(out, encOpt, stream.Recv)
io.WriteString(out, "{\"data\":")
errors := encoder.Encode()
io.WriteString(out, ",\"errors\":[")
m := jsonpb.Marshaler{}
if len(errors) != 0 {
errorCounter.With(prometheus.Labels{}).Inc()
}
for index, error := range errors {
if index != 0 {
io.WriteString(out, ",")
}
m.Marshal(out, error)
errorsCounter.With(prometheus.Labels{}).Inc()
}
io.WriteString(out, "]}")
}()
wg.Wait()
}
func sendParams(streamer func(*cxpb.Element) error, params map[string][]string) {
for name, values := range params {
for _, value := range values {
p := &cxpb.Element{
NetworkId: 0,
Value: &cxpb.Element_Parameter{
Parameter: &cxpb.Parameter{
Name: name,
Value: value,
},
},
}
err := streamer(p)
if err != nil {
panic("Could not send parameter")
}
sentParametersCounter.With(prometheus.Labels{
"name": name,
"value": value,
}).Inc()
}
}
}