forked from metrico/promcasa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
450 lines (377 loc) · 13.3 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package main
import (
"crypto/tls"
"flag"
"fmt"
"os"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/metrico/promcasa/aggregator"
"github.com/metrico/promcasa/utils/helpers"
"github.com/metrico/promcasa/utils/jobqueue"
"github.com/metrico/promcasa/utils/promcasautils"
"github.com/ansrivas/fiberprometheus/v2"
"github.com/gofiber/fiber/v2"
"github.com/jmoiron/sqlx"
"github.com/mcuadros/go-defaults"
"github.com/metrico/promcasa/config"
"github.com/metrico/promcasa/model"
"github.com/metrico/promcasa/utils/logger"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
"gopkg.in/go-playground/validator.v9"
)
// params for Services
type ServicesObject struct {
dataDBSession []*sqlx.DB
databaseNodeMap []model.DataDatabasesMap
}
type CustomValidator struct {
validator *validator.Validate
}
// validate function
func (cv *CustomValidator) Validate(i interface{}) error {
return cv.validator.Struct(i)
}
var appFlags CommandLineFlags
var servicesObject ServicesObject
// params for Flags
type CommandLineFlags struct {
InitializeDB *bool `json:"initialize_db"`
ShowHelpMessage *bool `json:"help"`
ShowVersion *bool `json:"version"`
ConfigPath *string `json:"config_path"`
LogPath *string `json:"log_path"`
LogName *string `json:"log_name"`
}
/* init flags */
func initFlags() {
appFlags.InitializeDB = flag.Bool("initialize_db", false, "initialize the database and create all tables")
appFlags.ShowHelpMessage = flag.Bool("help", false, "show help")
appFlags.ShowVersion = flag.Bool("version", false, "show version")
appFlags.ConfigPath = flag.String("config-path", "/usr/local/promcasa/etc", "the path to the promcasaapp config directory")
appFlags.LogName = flag.String("log-name", "", "the name prefix of the log file.")
appFlags.LogPath = flag.String("log-path", "", "the path for the log file.")
flag.Parse()
}
func main() {
//init flags
initFlags()
cfg := new(config.PromCasaSettingServer)
defaults.SetDefaults(cfg) //<-- This set the defaults values
config.Setting = *cfg
/* first check admin flags */
checkHelpVersionFlags()
promcasautils.Colorize(promcasautils.ColorRed, promcasautils.PromCasaLogo)
//ReadConfig
readConfig()
//SystemParams
setFastConfigSettings()
//Set to max cpu if the value is equals 0
if config.Setting.SYSTEM_SETTINGS.CPUMaxProcs == 0 {
runtime.GOMAXPROCS(runtime.NumCPU())
} else {
runtime.GOMAXPROCS(config.Setting.SYSTEM_SETTINGS.CPUMaxProcs)
}
// initialize logger
logger.InitLogger()
// configure new db session
servicesObject.dataDBSession, servicesObject.databaseNodeMap = getDataDBSession()
for val := range servicesObject.dataDBSession {
defer servicesObject.dataDBSession[val].Close()
}
if len(servicesObject.dataDBSession) == 0 {
promcasautils.Colorize(promcasautils.ColorRed, "\r\nWe don't have any active DB session configured. Please check your config\r\n")
os.Exit(0)
}
/* init job push queue channel */
if config.Setting.PROMETHEUS_CLIENT.EnablePush {
jobqueue.InitQueue(config.Setting.PROMETHEUS_CLIENT.QueueJobELements)
}
//Api
// configure to serve WebServices
configureAsHTTPServer()
}
func checkHelpVersionFlags() {
if *appFlags.ShowHelpMessage {
flag.Usage()
os.Exit(0)
}
if *appFlags.ShowVersion {
fmt.Printf("VERSION: %s\r\n", VERSION_APPLICATION)
os.Exit(0)
}
}
// https://github.com/atreugo/examples/blob/master/basic/main.go
// https://github.com/jackwhelpton/fasthttp-routing
func readConfig() {
// Getting constant values
if configEnv := os.Getenv("PROMCASA_APPENV"); configEnv != "" {
viper.SetConfigName("promcasa_" + configEnv)
} else {
viper.SetConfigName("promcasa")
}
viper.SetConfigType("json")
if configPath := os.Getenv("PROMCASA_APPPATH"); configPath != "" {
viper.AddConfigPath(configPath)
} else {
viper.AddConfigPath(*appFlags.ConfigPath)
}
viper.AddConfigPath(".")
//Default value
err := viper.ReadInConfig()
if err != nil {
fmt.Println("No configuration file loaded - checking env: ", err)
logger.Error("No configuration file loaded - using defaults - checking env")
}
viper.SetConfigName("promcasa_custom")
err = viper.MergeInConfig()
if err != nil {
logger.Debug("No custom configuration file loaded.")
}
//Env variables
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "[", "_", "]", ""))
viper.SetEnvPrefix(config.Setting.EnvPrefix)
SetEnvironDataBase()
//Bind Env from Config
BindEnvs(config.Setting)
err = viper.Unmarshal(&config.Setting, func(config *mapstructure.DecoderConfig) {
config.TagName = "json"
})
if err != nil {
logger.Debug("couldn't unmarshal viper.")
}
/* database data connection */
/* database queries */
var reData = regexp.MustCompile(`database_data\[(\d)\]`)
var reQueries = regexp.MustCompile(`database_metrics\[(\d)\]`)
envParamsData := []int{}
envParamsQueries := []int{}
allSettings := viper.AllSettings()
for key, _ := range allSettings {
if strings.HasPrefix(key, "database_data[") {
key = reData.ReplaceAllString(key, "$1")
i, err := strconv.Atoi(key)
if err == nil {
envParamsData = append(envParamsData, i)
}
} else if strings.HasPrefix(key, "database_queries[") {
key = reQueries.ReplaceAllString(key, "$1")
i, err := strconv.Atoi(key)
if err == nil {
envParamsQueries = append(envParamsQueries, i)
}
}
}
//Read the data db connection from config. This is fix because defaults doesn't know the size of array
if viper.IsSet("database_data") {
config.Setting.DATABASE_DATA = nil
dataConfig := viper.Get("database_data")
dataVal := dataConfig.([]interface{})
for idx := range dataVal {
val := dataVal[idx].(map[string]interface{})
data := config.PromCasaDataBase{}
defaults.SetDefaults(&data) //<-- This set the defaults values
err := mapstructure.Decode(val, &data)
if err != nil {
logger.Error("ERROR during mapstructure decode[1]:", err)
}
config.Setting.DATABASE_DATA = append(config.Setting.DATABASE_DATA, data)
}
}
//We should do extraction and after sorting 0,1,2,3
sort.Ints(envParamsData[:])
//Here we do ENV check
for _, idx := range envParamsData {
value := allSettings[fmt.Sprintf("database_data[%d]", idx)]
val := value.(map[string]interface{})
//If the configuration already exists - we replace only existing params
if len(config.Setting.DATABASE_DATA) > idx {
err := mapstructure.Decode(val, &config.Setting.DATABASE_DATA[idx])
if err != nil {
logger.Error("ERROR during mapstructure decode[0]:", err)
}
} else {
data := config.PromCasaDataBase{}
defaults.SetDefaults(&data) //<-- This set the defaults values
err := mapstructure.Decode(val, &data)
if err != nil {
logger.Error("ERROR during mapstructure decode[1]:", err)
}
config.Setting.DATABASE_DATA = append(config.Setting.DATABASE_DATA, data)
}
}
//queries
if viper.IsSet("database_metrics") {
config.Setting.DATABASE_METRICS = nil
dataConfig := viper.Get("database_metrics")
dataVal := dataConfig.([]interface{})
for idx := range dataVal {
val := dataVal[idx].(map[string]interface{})
data := config.PromCasaMetrics{}
defaults.SetDefaults(&data) //<-- This set the defaults values
err := mapstructure.Decode(val, &data)
if err != nil {
logger.Error("ERROR during mapstructure decode[1]:", err)
}
config.Setting.DATABASE_METRICS = append(config.Setting.DATABASE_METRICS, data)
}
}
//We should do extraction and after sorting 0,1,2,3
sort.Ints(envParamsQueries[:])
//Here we do ENV check
for _, idx := range envParamsQueries {
value := allSettings[fmt.Sprintf("database_metrics[%d]", idx)]
val := value.(map[string]interface{})
//If the configuration already exists - we replace only existing params
if len(config.Setting.DATABASE_METRICS) > idx {
err := mapstructure.Decode(val, &config.Setting.DATABASE_METRICS[idx])
if err != nil {
logger.Error("ERROR during mapstructure decode[0]:", err)
}
} else {
data := config.PromCasaMetrics{}
defaults.SetDefaults(&data) //<-- This set the defaults values
err := mapstructure.Decode(val, &data)
if err != nil {
logger.Error("ERROR during mapstructure decode[1]:", err)
}
config.Setting.DATABASE_METRICS = append(config.Setting.DATABASE_METRICS, data)
}
}
//Set to 0
for index, qObj := range config.Setting.DATABASE_METRICS {
config.Setting.DATABASE_METRICS[index].RefreshTimeout, _ = time.ParseDuration(qObj.RefreshString)
}
//Check the command line
if *appFlags.LogName != "" {
config.Setting.LOG_SETTINGS.Name = *appFlags.LogName
}
if *appFlags.LogPath != "" {
config.Setting.LOG_SETTINGS.Path = *appFlags.LogPath
}
//viper.Debug()
}
// system params for replications, groups
func setFastConfigSettings() {
/***********************************/
minVersion := config.Setting.HTTPS_SETTINGS.MinTLSVersionString
if minVersion == "TLS1.0" {
config.Setting.HTTPS_SETTINGS.MinTLSVersion = tls.VersionTLS10
} else if minVersion == "TLS1.1" {
config.Setting.HTTPS_SETTINGS.MinTLSVersion = tls.VersionTLS11
} else if minVersion == "TLS1.2" {
config.Setting.HTTPS_SETTINGS.MinTLSVersion = tls.VersionTLS12
} else if minVersion == "TLS1.3" {
config.Setting.HTTPS_SETTINGS.MinTLSVersion = tls.VersionTLS13
}
maxVersion := config.Setting.HTTPS_SETTINGS.MaxTLSVersionString
if maxVersion == "TLS1.0" {
config.Setting.HTTPS_SETTINGS.MaxTLSVersion = tls.VersionTLS10
} else if maxVersion == "TLS1.1" {
config.Setting.HTTPS_SETTINGS.MaxTLSVersion = tls.VersionTLS11
} else if maxVersion == "TLS1.2" {
config.Setting.HTTPS_SETTINGS.MaxTLSVersion = tls.VersionTLS12
} else if maxVersion == "TLS1.3" {
config.Setting.HTTPS_SETTINGS.MaxTLSVersion = tls.VersionTLS13
}
}
// getSession creates a new mongo session and panics if connection error occurs
func getDataDBSession() ([]*sqlx.DB, []model.DataDatabasesMap) {
dbMap := []*sqlx.DB{}
dbNodeMap := []model.DataDatabasesMap{}
for _, dbObject := range config.Setting.DATABASE_DATA {
logger.Info(fmt.Sprintf("Connecting to Proto: [%s] Host: [%s], User:[%s], Name:[%s], Node:[%s], Port:[%d], Timeout: [%s, %s]\n",
dbObject.Proto, dbObject.Host, dbObject.User, dbObject.Name, dbObject.Node,
dbObject.Port, dbObject.ReadTimeout, dbObject.DialTimeout))
connectString := fmt.Sprintf("%s://%s:%d/%s?username=%s&password=%s&read_timeout=%s&dial_timeout=%s&compress=true&debug=%t",
dbObject.Proto, dbObject.Host, dbObject.Port, dbObject.Name, dbObject.User, dbObject.Password,
dbObject.ReadTimeout, dbObject.DialTimeout, dbObject.Debug)
db, err := sqlx.Open("clickhouse", connectString)
dbMap = append(dbMap, db)
dbNodeMap = append(dbNodeMap, model.DataDatabasesMap{Name: dbObject.Name, DBname: dbObject.Name, Host: dbObject.Host,
TableSeries: dbObject.TableSeries, TableSamples: dbObject.TableSamples, Online: false})
if err != nil {
logger.Error(fmt.Sprintf("couldn't make connection to [Proto: %s, Host: %s, Node: %s, Port: %d]: \n", dbObject.Proto, dbObject.Host, dbObject.Node, dbObject.Port), err)
continue
}
//Set some limit
db.SetMaxIdleConns(dbObject.MaxIdleConn)
db.SetMaxOpenConns(dbObject.MaxOpenConn)
logger.Info("----------------------------------- ")
logger.Info("*** Database Session created *** ")
logger.Info("----------------------------------- ")
}
return dbMap, dbNodeMap
}
func configureAsHTTPServer() {
helpers.SetGlobalLimit(50 * 1024 * 1024)
httpURL := fmt.Sprintf("%s:%d", config.Setting.HTTP_SETTINGS.Host, config.Setting.HTTP_SETTINGS.Port)
configFiber := fiber.Config{
Prefork: config.Setting.HTTP_SETTINGS.Prefork,
StreamRequestBody: true,
//Addr: httpURL,
}
config.Setting.Validate = validator.New()
serverFiber := fiber.New(configFiber)
/* check if we should enable prometheus client here */
if config.Setting.PROMETHEUS_CLIENT.Enable {
prometheus := fiberprometheus.New(config.Setting.PROMETHEUS_CLIENT.ServiceName)
prometheus.RegisterAt(serverFiber, config.Setting.PROMETHEUS_CLIENT.MetricsPath)
serverFiber.Use(prometheus.Middleware)
}
/* fractionLost := promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "custom_data_fraction_lost",
Help: "fraction lost"},
[]string{"node_id"})
fractionLost.WithLabelValues("test").Inc()
*/
runSchedularPopulation()
if err := serverFiber.Listen(httpURL); err != nil {
panic(err)
}
}
func runSchedularPopulation() {
aggregator.ActivateTimer(servicesObject.dataDBSession, &servicesObject.databaseNodeMap)
}
// this function will check PROMCASA_DATABASE_DATA and set internal bind for viper
// i.e. PROMCASA_DATABASE_DATA_0_HOSTNAME -> database_data[0].hostname
func SetEnvironDataBase() bool {
var re = regexp.MustCompile(`_(\d)_`)
for _, s := range os.Environ() {
if strings.HasPrefix(s, config.Setting.EnvPrefix+"_DATABASE_DATA") {
a := strings.Split(s, "=")
key := strings.TrimPrefix(a[0], config.Setting.EnvPrefix+"_")
key = re.ReplaceAllString(key, "[$1].")
viper.BindEnv(key)
}
}
return true
}
// Now we should bind the ENV params
func BindEnvs(iface interface{}, parts ...string) {
ifv := reflect.ValueOf(iface)
ift := reflect.TypeOf(iface)
for i := 0; i < ift.NumField(); i++ {
v := ifv.Field(i)
t := ift.Field(i)
tv, ok := t.Tag.Lookup("mapstructure")
if !ok {
continue
}
switch v.Kind() {
case reflect.Struct:
BindEnvs(v.Interface(), append(parts, tv)...)
case reflect.Slice:
continue
default:
viper.BindEnv(strings.Join(append(parts, tv), "."))
}
}
}