-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhealth.go
383 lines (338 loc) · 9.16 KB
/
health.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strconv"
"time"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/gomodule/redigo/redis"
log "github.com/sirupsen/logrus"
)
//Errcodes Error Codes
type Errcodes int
//Error Code Enum
const (
SystemErr = iota
InputJSONInvalid
AgeRangeInvalid
RiskDetailsInvalid
InvalidRestMethod
InvalidContentType
)
//Redis k8s service
var redissvc = os.Getenv("redissvc")
type healthreq struct {
Code string `json:"code"`
SumInsured string `json:"sumInsured"`
DateOfBirth string `json:"dateOfBirth"`
}
type response struct {
Premium string `json:"premium"`
}
type erroresponse struct {
Code int `json:"errorCode"`
Message string `json:"errorMessage"`
}
func init() {
log.SetFormatter(&log.JSONFormatter{})
log.SetLevel(log.DebugLevel)
log.SetOutput(os.Stdout)
//log.SetReportCaller(true)
}
func main() {
/* file, err := os.OpenFile("premium.log", os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.SetOutput(os.Stdout)
} else {
log.SetOutput(file)
defer file.Close()
} */
log.Info("premium api starting...")
mux := http.NewServeMux()
mux.HandleFunc("/", healthz)
mux.HandleFunc("/api/v1/healths/premiums", premium)
mux.HandleFunc("/api/v1/healths/premiums/loads", loadMatrix)
mux.HandleFunc("/api/v1/healths/premiums/unloads", unloadMatrix)
mux.HandleFunc("/api/v1/healths/premiums/checks", checkMatrix)
srv := http.Server{Addr: ":8000", Handler: mux}
ctx := context.Background()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
log.Info("shutting down health premium server...")
srv.Shutdown(ctx)
<-ctx.Done()
}
}()
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("ListenAndServe(): %s", err)
}
}
//call by k8s liveness probe
func healthz(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
data := (time.Now()).String()
log.Debug("health ok")
w.Write([]byte(data))
}
func validateReq(w http.ResponseWriter, req *http.Request) (*healthreq, *erroresponse) {
if req.Method != http.MethodPost {
return nil, &erroresponse{Code: InvalidRestMethod, Message: fmt.Sprintf("Invalid method %s", req.Method)}
}
if req.Header.Get("Content-Type") != "application/json" {
msg := fmt.Sprintf("Invalid content-type %s require %s", req.Header.Get("Content-Type"), "application/json")
return nil, &erroresponse{Code: InvalidContentType, Message: msg}
}
body, _ := ioutil.ReadAll(req.Body)
h, err := marshallReq(string(body))
if err != nil {
return nil, err
}
return h, nil
}
//calculates premium for the risk
func premium(w http.ResponseWriter, req *http.Request) {
h, err := validateReq(w, req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
data, _ := json.Marshal(err)
fmt.Fprintf(w, "%s", data)
} else {
premium, calErr := calPremium(h)
if calErr != nil {
if calErr.Code == SystemErr {
w.WriteHeader(http.StatusServiceUnavailable)
} else {
data, _ := json.Marshal(calErr)
fmt.Fprintf(w, "%s", data)
}
} else {
data, _ := json.Marshal(response{Premium: premium})
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%s", data)
}
}
}
//loads premium matrix from xls file via the k8s readiness probe.
//If premium matrix already loaded load is ignored.
func loadMatrix(w http.ResponseWriter, req *http.Request) {
keys, err := keysExists()
if err != nil {
log.Error("Error while keys exists check", err)
} else if err == nil && keys == 0 {
if err := load(); err != nil {
log.Error(err)
w.WriteHeader(http.StatusServiceUnavailable)
} else {
log.Debug("Matix loaded...")
w.WriteHeader(http.StatusOK)
}
} else {
log.Debug("Matrix already loaded....")
w.WriteHeader(http.StatusOK)
}
}
//flushes the keys in redis for the loaded premium matrix. This is for mantainence only.
func unloadMatrix(w http.ResponseWriter, req *http.Request) {
if err := unload(); err != nil {
log.Error(err)
w.WriteHeader(http.StatusServiceUnavailable)
} else {
w.WriteHeader(http.StatusOK)
}
}
//Check if premium is loaded.
func checkMatrix(w http.ResponseWriter, req *http.Request) {
keys, err := keysExists()
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusServiceUnavailable)
} else if keys != 1 {
w.WriteHeader(http.StatusNotFound)
} else {
w.WriteHeader(http.StatusOK)
}
}
func marshallReq(data string) (*healthreq, *erroresponse) {
var h healthreq
err := json.Unmarshal([]byte(data), &h)
if err != nil {
log.Errorf("err %v during unmarshalling data %s ", err, data)
return nil, &erroresponse{Code: SystemErr, Message: "input invalid"}
}
_, errDob := calculateAge(h.DateOfBirth)
if errDob != nil {
return nil, &erroresponse{Code: InputJSONInvalid, Message: "Invalid Date of birth enter for yyyy-mm-dd"}
}
if len(h.Code) == 0 || err != nil || len(h.SumInsured) == 0 {
return nil, &erroresponse{Code: InputJSONInvalid, Message: "Invalid Input"}
}
return &h, nil
}
func calulateScore(age int) int {
if age >= 18 && age <= 35 {
return 1
} else if age >= 36 && age <= 45 {
return 2
} else if age >= 46 && age <= 55 {
return 3
} else if age >= 56 && age <= 60 {
return 4
} else if age >= 61 && age <= 65 {
return 5
} else if age >= 66 && age <= 70 {
return 6
} else if age > 70 {
return 7
}
return 0
}
func calculateAge(bdate string) (int, error) {
const layoutISO = "2006-01-02"
dob, err := time.Parse(layoutISO, bdate)
if err != nil {
return 0, err
}
now := time.Now()
years := now.Year() - dob.Year()
if now.YearDay() < dob.YearDay() {
years--
}
log.Debug("Years calulated ", years)
return years, nil
}
//read the premium age matrix and gives back the premium for particular age range.
func calPremium(h *healthreq) (string, *erroresponse) {
c, err := connRead()
if err != nil {
log.Errorf(err.Error())
return "", &erroresponse{Code: SystemErr, Message: "system err"}
}
defer c.Close()
age, _ := calculateAge(h.DateOfBirth)
/*if age > 70 {
log.Errorf("age %v not in range of 18 to 70", age)
msg := fmt.Sprintf("Age should be between 18 and 70")
return "", &erroresponse{Code: AgeRangeInvalid, Message: msg}
} */
score := calulateScore(age)
key := h.Code + ":" + h.SumInsured
members, err := redis.Strings(c.Do("ZRANGEBYSCORE", key, score, score))
if err != nil {
log.Errorf("Cannot get premium for code %s error %v", key, err)
msg := fmt.Sprintf("Premium cannot be calculated risk details")
return "", &erroresponse{Code: RiskDetailsInvalid, Message: msg}
}
if len(members) != 1 {
log.Errorf("code %s dob %s sum assured %s combination not found ", h.Code, h.DateOfBirth, h.SumInsured)
msg := fmt.Sprintf("Premium cannot be calculated for risk details")
return "", &erroresponse{Code: RiskDetailsInvalid, Message: msg}
}
var discount int = 25
premium, _ := strconv.Atoi(members[0])
premium = premium - discount
return strconv.Itoa(premium), nil
}
//loads premium matrix in redis
func load() error {
xlsx, err := excelize.OpenFile("./premium_tables.xlsx")
if err != nil {
return fmt.Errorf("cannot load matrix file %v", err)
}
c, err := connWrite()
if err != nil {
return err
}
defer c.Close()
rows, _ := xlsx.GetRows("matrix")
var score = 0
for _, row := range rows {
score++
var key string
var premium int
for ci, cellv := range row {
if ci == 0 {
key = cellv
}
if ci == 1 {
key = key + ":" + cellv
}
if ci == 3 {
premium, _ = strconv.Atoi(cellv)
}
}
log.Debugf("key %v premium %v score %v ", key, premium, score)
_, err := c.Do("ZADD", key, score, premium)
if err != nil {
return fmt.Errorf("err adding key %v score %v premium %v to redis", key, score, premium)
}
if score == 8 {
score = 0
}
}
return nil
}
//unload redis premium matrix keys
func unload() error {
c, err := connWrite()
if err != nil {
return err
}
defer c.Close()
_, errFlush := c.Do("FLUSHALL")
if errFlush != nil {
return fmt.Errorf("err flusing all keys %v", errFlush)
}
return nil
}
func keysExists() (int, error) {
c, err := connRead()
if err != nil {
return 0, err
}
defer c.Close()
members, err := redis.Strings(c.Do("KEYS", "*"))
log.Println(len(members))
if err != nil {
log.Errorf("Error while Keys * %v ", err)
return 0, err
}
if len(members) != 1 {
log.Errorf("No keys found")
return 0, nil
}
return len(members), nil
}
//gives back a readonly connection for read replica
func connRead() (redis.Conn, error) {
c, err := redis.DialURL("redis://" + redissvc + ":6379/0")
if err != nil {
return nil, fmt.Errorf("Cannot connect to redis %v ", err)
}
return c, nil
}
//gives back a connection to master for writing or loading premium matrix
func connWrite() (redis.Conn, error) {
sc, err := redis.DialURL("redis://" + redissvc + ":26379/0")
if err != nil {
return nil, fmt.Errorf("Cannot connect to redis sentinel %v ", err)
}
defer sc.Close()
minfo, err := redis.Strings(sc.Do("sentinel", "get-master-addr-by-name", "redis-premium-master"))
log.Println(minfo)
if err != nil {
return nil, fmt.Errorf("Cannot find redis master %v ", err)
}
mc, err := redis.DialURL("redis://" + minfo[0] + ":6379/0")
if err != nil {
return nil, fmt.Errorf("Cannot connect to redis master %v ", err)
}
sc.Close()
return mc, nil
}