2018-12-04 08:32:11 +04:00
|
|
|
// Fantasy World Zookeeper Bot
|
|
|
|
// Copyright (c) 2018 Vladimir "fat0troll" Hodakov
|
|
|
|
|
|
|
|
package context
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/rs/zerolog"
|
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
"io/ioutil"
|
2019-02-12 03:06:00 +04:00
|
|
|
"lab.wtfteam.pro/fat0troll/fw_zookeeper_helper/internal/config"
|
2018-12-04 08:32:11 +04:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"runtime"
|
|
|
|
)
|
|
|
|
|
|
|
|
// getMemoryUsage returns memory usage for logger.
|
|
|
|
func (c *Context) getMemoryUsage(e *zerolog.Event, level zerolog.Level, message string) {
|
|
|
|
var m runtime.MemStats
|
|
|
|
runtime.ReadMemStats(&m)
|
|
|
|
|
|
|
|
e.Str("memalloc", fmt.Sprintf("%dMB", m.Alloc/1024/1024))
|
|
|
|
e.Str("memsys", fmt.Sprintf("%dMB", m.Sys/1024/1024))
|
|
|
|
e.Str("numgc", fmt.Sprintf("%d", m.NumGC))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Init is an initialization function for core context
|
|
|
|
// Without these parts of the application we can't start at all
|
|
|
|
func (c *Context) Init() {
|
|
|
|
c.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
|
|
|
|
c.Logger = c.Logger.Hook(zerolog.HookFunc(c.getMemoryUsage))
|
|
|
|
|
|
|
|
c.Logger.Info().Msgf("fw_zookeeper_helper v. %s is starting...", VERSION)
|
|
|
|
}
|
|
|
|
|
|
|
|
// InitConfiguration reads configuration from YAML and parses it in
|
|
|
|
// config.Struct.
|
|
|
|
func (c *Context) InitConfiguration() bool {
|
|
|
|
c.Logger.Info().Msg("Loading configuration files...")
|
|
|
|
|
|
|
|
configPath := os.Getenv("BOT_CONFIG")
|
|
|
|
if configPath == "" {
|
|
|
|
configPath = "./example/fw_zookeeper_helper.yaml"
|
|
|
|
}
|
|
|
|
normalizedConfigPath, _ := filepath.Abs(configPath)
|
|
|
|
c.Logger.Debug().Msgf("Configuration file path: %s", normalizedConfigPath)
|
|
|
|
|
|
|
|
// Read configuration file into []byte.
|
|
|
|
fileData, err := ioutil.ReadFile(normalizedConfigPath)
|
|
|
|
if err != nil {
|
2019-03-02 19:26:51 +04:00
|
|
|
c.Logger.Fatal().Err(err).Msg("Failed to read configuration file")
|
2018-12-04 08:32:11 +04:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Config = &config.Struct{}
|
|
|
|
err = yaml.Unmarshal(fileData, c.Config)
|
|
|
|
if err != nil {
|
|
|
|
c.Logger.Error().Err(err).Msg("Failed to parse configuration file")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Logger.Info().Msg("Configuration file parsed successfully")
|
|
|
|
return true
|
|
|
|
}
|