This repository has been archived by the owner on Oct 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
service_mgr_broker.go
321 lines (272 loc) · 10.1 KB
/
service_mgr_broker.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/**
* (C) 2019 Volvo Cars
*
* All files and artifacts in the repository at https://github.com/MEAE-GOT/W3C_VehicleSignalInterfaceImpl
* are licensed under the provisions of the license provided by the LICENSE file in this repository.
*
**/
package main
import (
"bytes"
"fmt"
"io/ioutil"
//"log"
"github.com/gorilla/websocket"
"net/http"
"time"
"encoding/json"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"./server-core/util"
"./server-core/signal_broker"
//"strconv"
)
// one muxServer component for service registration, one for the data communication
var muxServer = []*http.ServeMux {
http.NewServeMux(), // 0 = for registration
http.NewServeMux(), // 1 = for data session
}
type RegRequest struct {
Rootnode string
}
type RegResponse struct {
Portnum int
Urlpath string
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func registerAsServiceMgr(regRequest RegRequest, regResponse *RegResponse) int {
url := "http://localhost:8082/service/reg"
data := []byte(`{"Rootnode": "` + regRequest.Rootnode + `"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
if err != nil {
log.Fatal("registerAsServiceMgr: Error creating request. ", err)
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Host", "localhost:8082")
// Set client timeout
client := &http.Client{Timeout: time.Second * 10}
// Validate headers are attached
fmt.Println(req.Header)
// Send request
resp, err := client.Do(req)
if err != nil {
log.Fatal("registerAsServiceMgr: Error reading response. ", err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error reading response. ", err)
}
fmt.Printf("%s\n", body)
err = json.Unmarshal(body, regResponse)
if (err != nil) {
log.Fatal("Service mgr: Error JSON decoding of response. ", err)
}
if (regResponse.Portnum <= 0) {
fmt.Printf("Service registration denied.\n")
return 0
}
return 1
}
func frontendWSdataSession(conn *websocket.Conn, clientChannel chan string, backendChannel chan string){
defer conn.Close()
for {
_, msg, err := conn.ReadMessage()
if err != nil {
log.Print("Service data read error:", err)
break
}
fmt.Printf("%s request: %s \n", conn.RemoteAddr(), string(msg))
clientChannel <- string(msg) // forward to mgr hub,
message := <- clientChannel // and wait for response
backendChannel <- message
}
}
func backendWSdataSession(conn *websocket.Conn, backendChannel chan string){
defer conn.Close()
for {
message := <- backendChannel
fmt.Printf("Service:backendWSdataSession(): message received=%s\n", message)
// Write message back to server core
response := []byte(message)
err := conn.WriteMessage(websocket.TextMessage, response)
if err != nil {
log.Print("Service data write error:", err)
break
}
}
}
func makeServiceDataHandler(dataChannel chan string, backendChannel chan string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
if req.Header.Get("Upgrade") == "websocket" {
fmt.Printf("we are upgrading to a websocket connection.\n")
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
conn, err := upgrader.Upgrade(w, req, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
go frontendWSdataSession(conn, dataChannel, backendChannel)
go backendWSdataSession(conn, backendChannel)
} else {
fmt.Printf("Client must set up a Websocket session.\n")
}
}
}
func initDataServer(muxServer *http.ServeMux, dataChannel chan string, backendChannel chan string, regResponse RegResponse) {
serviceDataHandler := makeServiceDataHandler(dataChannel, backendChannel)
muxServer.HandleFunc(regResponse.Urlpath, serviceDataHandler)
fmt.Printf("initDataServer: URL:%s, Portno:%d\n", regResponse.Urlpath, regResponse.Portnum)
log.Fatal(http.ListenAndServe("localhost:"+strconv.Itoa(regResponse.Portnum), muxServer))
}
func removeQuery(path string) string {
pathEnd := strings.Index(path, "?$spec")
if (pathEnd != -1) {
return path[:pathEnd]
}
return path
}
type SubscribePath struct {
path string
index int
}
var subscribePaths = []SubscribePath{{"Vehicle.Drivetrain.Transmission.Speed", 0}, {"Vehicle.x.y.z", 1}, {"Vehicle.a.b.c", 2}}
var inSubscription = false
var subscriptionId int
func activateSubscription(requestPath string, subscriptionChannel chan string) int {
if (inSubscription == true) {
return -1
}
path := removeQuery(requestPath)
signalIndex := -1
for i := 0 ; i < len(subscribePaths) ; i++ {
if (subscribePaths[i].path == path) {
signalIndex = subscribePaths[i].index
inSubscription = true
}
}
if (signalIndex != -1) {
go func() {
conn, response := signal_broker.GetResponseReceiver();
defer conn.Close();
for {
if (inSubscription == false) {
break
}
//log.Info("WAIT FOR RESPONSE...")
msg, err := response.Recv(); // wait for a subscription msg
if (err != nil) {
log.Debug(" error ", err);
break;
}
values := msg.GetSignal();
asig := values[signalIndex];
var val = strconv.FormatInt(int64(asig.GetInteger()), 10)
//log.Info(asig.Id.Namespace);
//log.Info(asig.Id.Name);
//log.Info( "val: ", val );
subscriptionChannel <- val
}
}()
subscriptionId++
return subscriptionId-1
}
return -1
}
func deactivateSubscription() {
inSubscription = false // breaks after next receive from signal broker
}
func checkSubscription(subscriptionChannel chan string, backendChannel chan string, subscriptionMap map[string]interface{}) {
select {
case value := <- subscriptionChannel:
//log.Debug("checkSubscription - we got new value!!!!");
subscriptionMap["value"] = value
backendChannel <- finalizeResponse(subscriptionMap, true)
default: // no subscription, so return
}
}
func extractPayload(request string, rMap *map[string]interface{}) {
decoder := json.NewDecoder(strings.NewReader(request))
err := decoder.Decode(rMap)
if err != nil {
fmt.Printf("Service manager-extractPayload: JSON decode failed for request:%s\n", request)
return
}
}
func finalizeResponse(responseMap map[string]interface{}, responseStatus bool) string {
if (responseStatus == false) {
responseMap["error"] = "{\"number\":99, \"reason\": \"BBB\", \"message\": \"CCC\"}" // TODO
}
responseMap["timestamp"] = 1234
response, err := json.Marshal(responseMap)
if err != nil {
fmt.Printf("Server core-finalizeResponse: JSON encode failed.\n")
return ""
}
return string(response)
}
var dummyValue int // used as return value in get
func main() {
var regResponse RegResponse
dataChan := make(chan string)
backendChan := make(chan string)
regRequest := RegRequest{Rootnode: "Vehicle"}
subscriptionChan := make(chan string)
util.InitLogger()
if (registerAsServiceMgr(regRequest, ®Response) == 0) {
return
}
go initDataServer(muxServer[1], dataChan, backendChan, regResponse)
fmt.Printf("initDataServer() done\n")
var subscriptionMap = make(map[string]interface{}) // only one subscription is supported!
for {
select {
case request := <- dataChan: // request from server core
fmt.Printf("Service manager: Request from Server core:%s\n", request)
// use template as response TODO: 1. update template, 2. include error handling, 3. connect to a vehicle data source
var requestMap = make(map[string]interface{})
var responseMap = make(map[string]interface{})
extractPayload(request, &requestMap)
responseMap["MgrId"] = requestMap["MgrId"]
responseMap["ClientId"] = requestMap["ClientId"]
responseMap["action"] = requestMap["action"]
responseMap["requestId"] = requestMap["requestId"]
var responseStatus bool
switch requestMap["action"] {
case "get":
responseMap["value"] = strconv.Itoa(dummyValue)
dummyValue++
responseStatus = true
case "set":
// interact with underlying subsystem to set the value
responseStatus = true
case "subscribe":
subscrId := activateSubscription(requestMap["path"].(string), subscriptionChan)
// if subscrId == -1, then send error response
for k, v := range responseMap {
subscriptionMap[k] = v
}
subscriptionMap["action"] = "subscription"
subscriptionMap["subscriptionId"] = strconv.Itoa(subscrId)
responseMap["subscriptionId"] = strconv.Itoa(subscrId)
responseStatus = true
case "unsubscribe":
deactivateSubscription()
responseStatus = true
default:
responseStatus = false
}
dataChan <- finalizeResponse(responseMap, responseStatus)
default:
checkSubscription(subscriptionChan, backendChan, subscriptionMap)
time.Sleep(50*time.Millisecond)
} // select
} // for
}