This repository has been archived by the owner on Dec 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
421 lines (352 loc) · 10.4 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/* Apache v2 license
* Copyright (C) <2019> Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"context"
"database/sql"
"encoding/base64"
"encoding/json"
"fmt"
golog "log"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"time"
"github.com/edgexfoundry/app-functions-sdk-go/appcontext"
"github.com/edgexfoundry/app-functions-sdk-go/appsdk"
"github.com/edgexfoundry/go-mod-core-contracts/models"
"github.com/intel/rsp-sw-toolkit-im-suite-product-data-service/app/config"
"github.com/intel/rsp-sw-toolkit-im-suite-product-data-service/app/productdata"
"github.com/intel/rsp-sw-toolkit-im-suite-product-data-service/app/routes"
"github.com/intel/rsp-sw-toolkit-im-suite-utilities/go-metrics"
reporter "github.com/intel/rsp-sw-toolkit-im-suite-utilities/go-metrics-influxdb"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
const serviceKey = "product-data-service"
type myDB struct {
masterDB *sql.DB
}
func main() {
// Ensure simple text format
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
// Load config variables
if err := config.InitConfig(); err != nil {
log.WithFields(log.Fields{
"Method": "config.InitConfig",
"Action": "Load config",
}).Fatal(err.Error())
}
// Initialize metrics reporting
initMetrics()
setLoggingLevel(config.AppConfig.LoggingLevel)
// Metrics
mDbConnection := metrics.GetOrRegisterGauge(`Product-Data.Main.DB-Connection`, nil)
mDbErr := metrics.GetOrRegisterGauge(`Product-Data.Main.DB-Error`, nil)
log.WithFields(log.Fields{"Method": "main", "Action": "Start"}).Info("Starting application...")
////////////////////////
// Connect to PostgreSQL
///////////////////////
log.WithFields(log.Fields{"Method": "main", "Action": "Start"}).Info("Connecting to database...")
db, err := dbSetup(config.AppConfig.DbHost,
config.AppConfig.DbPort,
config.AppConfig.DbUser, config.AppConfig.DbPass,
config.AppConfig.DbName,
config.AppConfig.DbSSLMode,
)
if err != nil {
mDbErr.Update(1)
log.WithFields(log.Fields{
"Method": "main",
"Action": "Start database",
"Message": err.Error(),
}).Fatal("Unable to connect to database.")
}
defer db.Close()
mDbConnection.Update(1)
// Receive data from EdgeX core data
receiveZmqEvents(db)
// Initiate webserver and routes
startWebServer(db, config.AppConfig.Port, config.AppConfig.ResponseLimit, config.AppConfig.ServiceName)
log.WithField("Method", "main").Info("Completed.")
}
func startWebServer(db *sql.DB, port string, responseLimit int, serviceName string) {
// Start Webserver and pass additional data
router := routes.NewRouter(db, responseLimit)
// Create a new server and set timeout values.
server := http.Server{
Addr: ":" + port,
Handler: router,
ReadTimeout: 900 * time.Second,
WriteTimeout: 900 * time.Second,
MaxHeaderBytes: 1 << 20,
}
// We want to report the listener is closed.
var wg sync.WaitGroup
wg.Add(1)
// Start the listener.
go func() {
log.Infof("%s running!", serviceName)
log.Infof("Listener closed : %v", server.ListenAndServe())
wg.Done()
}()
// Listen for an interrupt signal from the OS.
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt)
// Wait for a signal to shutdown.
<-osSignals
// Create a context to attempt a graceful 5 second shutdown.
const timeout = 5 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Attempt the graceful shutdown by closing the listener and
// completing all inflight requests.
if err := server.Shutdown(ctx); err != nil {
log.WithFields(log.Fields{
"Method": "main",
"Action": "shutdown",
"Timeout": timeout,
"Message": err.Error(),
}).Error("Graceful shutdown did not complete")
// Looks like we timedout on the graceful shutdown. Kill it hard.
if err := server.Close(); err != nil {
log.WithFields(log.Fields{
"Method": "main",
"Action": "shutdown",
"Message": err.Error(),
}).Error("Error killing server")
}
}
// Wait for the listener to report it is closed.
wg.Wait()
}
/*
dataProcess takes incoming product data and formats the data into
a JSON object that we can consume and use.
We are expecting the data to be passed to us in the following format:
"value": {
"data": [
{
"sku": "12345679",
"upc": "123456789783",
"beingRead": 0.01,
"becomingReadable": 0.02,
"exitError": 0.03,
"dailyTurn": 0.04
"metadata": {
"color":"blue",
"size":"XS"
}
},
{
"sku": "12345679",
"upc": "123456789784",
"beingRead": "0.01",
"becomingReadable": 0.02,
"exitError": 0.03,
"dailyTurn": 0.04
"metadata": {
"color":"red",
"size":"M"
}
}
],
"sent_on": 1501872400247
}
We will transform the data into the following format:
"sku" : "12345679",
"productList" : [
{
"productId" : "123456789783",
"beingRead": 0.01,
"becomingReadable": 0.02,
"exitError": 0.03,
"dailyTurn": 0.04
"metadata" :
{
"color" : "blue",
"size" : "XS"
}
},
{
"productId": "123456789784",
"beingRead": "0.01",
"becomingReadable": 0.02,
"exitError": 0.03,
"dailyTurn": 0.04
"metadata":
{
"color":"red",
"size":"M"
}
}
]
*/
func dataProcess(jsonBytes []byte, masterDB *sql.DB) error {
// Metrics
metrics.GetOrRegisterGauge(`Product-Data.dataProcess.Attempt`, nil).Update(1)
mUnmarshalErr := metrics.GetOrRegisterGauge("Product-Data.dataProcess.Unmarshal-Error", nil)
mMappingSkuCount := metrics.GetOrRegisterGaugeCollection("Product-Data.dataProcess.MappingData-SKU-Count", nil)
mTotalLatency := metrics.GetOrRegisterTimer(`Product-Data.dataProcess.Total-Latency`, nil)
/*
TODO: Check with team on need to total latency.
Per Instrumentation Guidance: Collect a timer for CPU intensive operations.
[Should answer questions like:] How much time does your application spend rendering documents? Calculating hashes?
(De)serializing JSON documents?
*/
startTime := time.Now()
log.Debugf("Received data:\n%s", string(jsonBytes))
var bv []productdata.IncomingData
if err := json.Unmarshal(jsonBytes, &bv); err != nil {
mUnmarshalErr.Update(1)
return errors.Wrap(err, "unmarshal failed")
}
var incomingDataSlice = bv
// Transform mapping.IncomingData to map of sku -> list of mapping.SKUData
prodDataMap := make(map[string]productdata.SKUData)
for _, item := range incomingDataSlice {
productData := productdata.ProductData{
ProductID: item.ProductID,
Metadata: item.Metadata,
BeingRead: item.BeingRead,
BecomingReadable: item.BecomingReadable,
DailyTurn: item.DailyTurn,
ExitError: item.ExitError,
}
skuData, repeatSKU := prodDataMap[item.SKU]
if repeatSKU {
skuData.ProductList = append(skuData.ProductList, productData)
} else {
skuData = productdata.SKUData{
SKU: item.SKU,
ProductList: []productdata.ProductData{productData},
}
}
prodDataMap[item.SKU] = skuData
}
// extract the values to a list
prodDataList := make([]productdata.SKUData, 0, len(prodDataMap))
for _, skuData := range prodDataMap {
prodDataList = append(prodDataList, skuData)
}
if err := productdata.Insert(masterDB, prodDataList); err != nil {
// Metrics not instrumented as it is handled in the controller.
return err
}
log.WithFields(log.Fields{
"Length": len(prodDataList),
"Action": "Insert",
}).Info("Product data inserted")
mMappingSkuCount.Add(int64(len(prodDataList)))
mTotalLatency.Update(time.Since(startTime))
return nil
}
func initMetrics() {
// setup metrics reporting
if config.AppConfig.TelemetryEndpoint != "" {
go reporter.InfluxDBWithTags(
metrics.DefaultRegistry,
time.Second*10,
config.AppConfig.TelemetryEndpoint,
config.AppConfig.TelemetryDataStoreName,
"",
"",
nil,
)
}
}
func receiveZmqEvents(masterDB *sql.DB) {
db := myDB{masterDB: masterDB}
go func() {
//Initialized EdgeX apps functionSDK
edgexSdk := &appsdk.AppFunctionsSDK{ServiceKey: serviceKey}
if err := edgexSdk.Initialize(); err != nil {
edgexSdk.LoggingClient.Error(fmt.Sprintf("SDK initialization failed: %v\n", err))
os.Exit(-1)
}
// Filter data by value descriptors
deviceFilter := []string{"SKU_Data_Device"}
edgexSdk.SetFunctionsPipeline(
edgexSdk.DeviceNameFilter(deviceFilter),
db.processEvents,
)
err := edgexSdk.MakeItRun()
if err != nil {
edgexSdk.LoggingClient.Error("MakeItRun returned error: ", err.Error())
os.Exit(-1)
}
}()
}
func (db myDB) processEvents(edgexcontext *appcontext.Context, params ...interface{}) (bool, interface{}) {
if len(params) < 1 {
return false, nil
}
event := params[0].(models.Event)
if len(event.Readings) < 1 {
return false, nil
}
// Value is base64 encoded
data, err := base64.StdEncoding.DecodeString(event.Readings[0].Value)
if err != nil {
log.WithFields(log.Fields{
"Method": "receiveZmqEvents",
"Action": "product data ingestion",
"Error": err.Error(),
}).Error("error decoding base64 value")
return false, nil
}
if err := dataProcess(data, db.masterDB); err != nil {
log.WithFields(log.Fields{
"Method": "receiveZmqEvents",
"Action": "product data ingestion",
"Error": err.Error(),
}).Error("error processing product data")
return false, nil
}
return false, nil
}
func setLoggingLevel(loggingLevel string) {
switch strings.ToLower(loggingLevel) {
case "error":
log.SetLevel(log.ErrorLevel)
case "warn":
log.SetLevel(log.WarnLevel)
case "info":
log.SetLevel(log.InfoLevel)
case "debug":
log.SetLevel(log.DebugLevel)
default:
log.SetLevel(log.InfoLevel)
}
// Not using filtered func (Info, etc ) so that message is always logged
golog.Printf("Logging level set to %s\n", loggingLevel)
}
func dbSetup(host, port, user, password, dbname, sslmode string) (*sql.DB, error) {
// Connect to PostgreSQL
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=%s", host, port, user, dbname, sslmode)
if password != "" {
psqlInfo += " password=" + password
}
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
return nil, err
}
log.Info("Connected to postgreSQL database...")
// Prepares database schema and indexes
_, errExec := db.Exec(productdata.DbSchema)
if errExec != nil {
return nil, errExec
}
return db, nil
}