-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
261 lines (216 loc) · 7.7 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
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
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"sync/atomic"
"time"
commonlib "github.com/kurtd5105/SENG-468-Common-Lib"
)
// ServerNetwork holds information about the system's servers' network addresses
type ServerNetwork struct {
databaseServerAddressAndPort string
loggingServerAddressAndPort string
transactionServerAddressAndPort string
webServerPort int
handled int
errors int
debugOutput int
}
var state = ServerNetwork{}
func heartbeat() {
time.Sleep(30 * time.Second)
log.Printf("HTTP server stats - served: %d, errored: %d\n", state.handled, state.errors)
}
func init() {
// Parse and process CLI flags
flag.StringVar(&state.databaseServerAddressAndPort, "db", "",
"[REQUIRED] the IP address and port on which the USER ACCOUNT DATABASE server is running, eg. -db=localhost:8080")
flag.StringVar(&state.loggingServerAddressAndPort, "log", "",
"[REQUIRED] the IP address and port on which the LOGGING DATABASE server is running, eg. -log=localhost:8081")
flag.IntVar(&state.webServerPort, "port", -1,
"[REQUIRED] the port on which *this* HTTP server is running, eg. -port=localhost:80")
flag.StringVar(&state.transactionServerAddressAndPort, "tx", "",
"[REQUIRED] the IP address and port on which the TRANSACTION server is running, eg. -tx=localhost:8082")
flag.Parse()
// Enforce required flags
if state.databaseServerAddressAndPort == "" ||
state.transactionServerAddressAndPort == "" ||
state.loggingServerAddressAndPort == "" ||
state.webServerPort < 0 {
log.Println("Error: Required flags were not provided at runtime")
flag.PrintDefaults()
os.Exit(1)
}
go heartbeat()
commonlib.ServerName = "http-server"
}
func main() {
portString := strconv.Itoa(state.webServerPort)
// Fire up server
log.Printf("HTTP server listening on http://localhost:%d/\n\n", state.webServerPort)
// TODO: figure out why commonlib.StartServer doesn't work for this
http.HandleFunc("/", requestRouter)
log.Fatal(http.ListenAndServe(":"+portString, nil))
}
// requestRouter routes the request to the appropriate handler based on its HTTP method
func requestRouter(w http.ResponseWriter, r *http.Request) {
state.handled++
if state.debugOutput >= 2 {
log.Printf("Received %s request\n", r.Method)
}
switch r.Method {
case http.MethodPost:
// POST requests come from UI and/or workload generator:
if state.debugOutput >= 2 {
log.Println("Routing POST request to commandHandler")
}
commandHandler(w, r)
// GET requests are only expected from UI:
case http.MethodGet:
if state.debugOutput >= 2 {
log.Println("Routing GET request to userInterfaceHandler")
}
userInterfaceHandler(w, r)
default:
// No other HTTP methods are supported
errorMessage := fmt.Sprintf("HTTP method not supported: %s\n", r.Method)
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte(errorMessage))
if state.debugOutput >= 1 {
log.Fatalln(errorMessage)
}
state.errors++
}
}
// JSONPayload represents the expected JSON body of a request
type JSONPayload struct {
Message string `json: "message"` // HACK
UserID string `json: "userID,omitempty"`
Amount string `json: "amount,omitempty"`
StockSymbol string `json: "stockSymbol,omitempty"`
Filename string `json: "filename,omitempty"`
}
// commandHandler decodes a JSON command and forwards it appropriately
func commandHandler(w http.ResponseWriter, r *http.Request) {
if state.debugOutput >= 2 {
log.Printf("Handling JSON body of %s request", r.Method)
}
// Read request body
requestBody, err := ioutil.ReadAll(r.Body)
if err != nil {
errorMessage := fmt.Sprintf("Error reading request body: %s\n", err.Error())
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(errorMessage))
if state.debugOutput >= 1 {
log.Fatalln(errorMessage)
}
state.errors++
}
defer r.Body.Close()
// Unmarshal JSON directly into JSONPayload struct
var requestBodyJSON = JSONPayload{}
if err = json.Unmarshal(requestBody, &requestBodyJSON); err != nil {
errorMessage := fmt.Sprintf("Error unmarshaling request body: %s\n", err.Error())
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(errorMessage))
if state.debugOutput >= 1 {
log.Fatalln(errorMessage)
}
state.errors++
}
//Increment global transaction counter
transactionNumString := strconv.FormatUint(incrementTransactionNum(), 10)
// Extract commandID from message
message, err := strconv.ParseInt(requestBodyJSON.Message, 10, 8)
if err != nil {
errorMessage := fmt.Sprintf("Error parsing message content: %s\n", err.Error())
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(errorMessage))
if state.debugOutput >= 1 {
log.Fatalln(errorMessage)
}
state.errors++
}
commandID := uint8(message)
// Build a CommandParameter to send to Transaction Server
parameters := commonlib.CommandParameter{
UserID: requestBodyJSON.UserID,
Amount: requestBodyJSON.Amount,
Filename: requestBodyJSON.Filename,
StockSymbol: requestBodyJSON.StockSymbol,
TransactionNum: transactionNumString,
}
// Build a LogCommandParameter to send to Logging Server
loggingParameters := commonlib.LogCommandParameter{
Username: requestBodyJSON.UserID,
Funds: requestBodyJSON.Amount,
LogFilename: requestBodyJSON.Filename,
LogStockSymbol: requestBodyJSON.StockSymbol,
Server: "Web",
TransactionNum: transactionNumString,
Timestamp: commonlib.GetTimeStampString(),
Command: commonlib.CommandNames[commandID],
}
if commandID == commonlib.DumplogCommand || commandID == commonlib.DumplogAllCommand {
fmt.Println("Sending dumplog to transaction server...")
commonlib.SendCommand(
"POST",
"application/json",
state.transactionServerAddressAndPort,
commonlib.GetSendableCommand(commandID, parameters))
}
if state.debugOutput >= 2 {
sendLog(buildLog(fmt.Sprintf("Received request: %s", requestBodyJSON),
commonlib.DebugType,
loggingParameters))
}
// Destination depends on type of command
destinationServer := getDestinationServer(commandID)
sendLog(buildLog(fmt.Sprintf("Forwarding #%s command to %s with parameters: %+v\n",
requestBodyJSON.Message, destinationServer, parameters),
commonlib.SystemEventType,
loggingParameters))
response, err := commonlib.SendCommand(
"POST",
"application/json",
destinationServer,
commonlib.GetSendableCommand(commandID, parameters))
if err != nil {
errorMessage := fmt.Sprintf("Error sending command: %s\n\n Server response: %s\n",
err.Error(), response)
sendLog(buildLog(
errorMessage,
commonlib.ErrorEventType,
loggingParameters))
if state.debugOutput >= 1 {
log.Fatalln(errorMessage)
}
state.errors++
}
if state.debugOutput >= 2 {
sendLog(buildLog(
fmt.Sprintf("%s responded: %s\n", destinationServer, response),
commonlib.DebugType,
loggingParameters))
}
// Request received intact
w.WriteHeader(http.StatusOK)
w.Write([]byte(response))
}
// userInterfaceHandler serves the user interface HTML file
func userInterfaceHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Serving user interface")
http.ServeFile(w, r, "www/index.html")
}
// Global transactionNum initialized to 0 by default
var transactionNum uint64
// incrementTransactionNum atomically increments the global transaction counter and returns its value
func incrementTransactionNum() uint64 {
return atomic.AddUint64(&transactionNum, 1)
}