game_sync/gamesrv/slotspkg/internal/generic/global/global.go

319 lines
7.8 KiB
Go

package global
import (
"fmt"
logger2 "github.com/breezedup/goserver/core/logger"
"github.com/go-redis/redis"
"github.com/gofrs/uuid"
"github.com/gogo/protobuf/codec"
"github.com/sirupsen/logrus"
"github.com/tomas-qstarrs/boost/config"
"github.com/tomas-qstarrs/boost/dogfish"
"github.com/tomas-qstarrs/boost/httpx"
"github.com/tomas-qstarrs/boost/logger"
"github.com/tomas-qstarrs/boost/regexp"
"github.com/tomas-qstarrs/boost/timex"
"os"
"os/exec"
"path/filepath"
"qstar_server/internal/exported/resource"
"qstar_server/internal/generic/ddb"
"sort"
"strings"
"sync/atomic"
"time"
)
var (
// Project is the name of project
Project string
// Game is the name of game
Game string
// Process is the name of type name of process
Process string
// ProcessID is the id of process
ProcessID string
// ProcessTime is the time of process
ProcessTime int64
// ProcessSeqID is the seq id of process
ProcessSeqID atomic.Int64
// Runtime is the value of Runtime
Runtime string
// Cluster is the cluster of project
Cluster string
// Instance is the instance of project
Instance string
// ExecutableDirectory is the path of Executable
ExecutableDirectory string
// WorkingDirectory is the path of CWD
WorkingDirectory string
// ProjectDirectory is the path of project `qstar_server`
ProjectDirectory string
// ConfigDirectory is the path of config
ConfigDirectory string
// LogDirectory is the path of log
LogDirectory string
// Config is the config of project
Configs *config.Config
// Timex is the timex of project
Timex *timex.Timex
// Logger is the logger of project
//Logger *logger.Logger
// TALogger is the ta logger of project
TALogger *logger.Logger
// Codec is the codec of project
Codec codec.Codec
// PlainCodec is the plain codec
PlainCodec codec.Codec
// Mock is the mock mode
Mock bool
// HTTP is the http client
HTTPClient *httpx.Client
// RedisClient is the redis client
RedisClient *redis.Client
Regexp *regexp.Regexp
)
func init() {
InitGeneric()
Project = getProject()
Game = getGame()
Process = getProcess()
ProcessID = getProcessID()
Runtime = getRuntime()
Cluster = getCluster()
Instance = getInstance()
ExecutableDirectory = getExecutableDirectory()
WorkingDirectory = getWorkingDirectory()
ProjectDirectory = getProjectDirectory()
ConfigDirectory = getConfigDirectory()
Configs = getConfig()
Timex = getTimex()
//Logger = getLogger()
ProcessTime = getProcessTime()
Mock = getMock()
HTTPClient = getHTTPClient()
RedisClient = getRedisClient()
ddb.Init()
}
func getProject() string {
return "qstar_server"
}
func getGame() string {
return "SLOTS"
}
func getProcess() string {
args := os.Args
if len(args) < 2 {
return ""
}
return args[1]
}
func getProcessID() string {
return uuid.Must(uuid.NewV4()).String()
}
func getProcessTime() int64 {
return timex.Now().Unix()
}
func getRuntime() string {
s := os.Getenv("QSTAR_SERVER_RUNTIME")
logger2.Logger.Infof("QSTAR_SERVER_RUNTIME--------- [%v]", s)
if s == "" {
logger2.Logger.Info("Please set environment variable QSTAR_SERVER_RUNTIME, " +
"now temporarily use QSTAR_SERVER_RUNTIME=Default.")
s = config.GetString("runtime")
} else {
logger2.Logger.Infof("Use QSTAR_SERVER_RUNTIME=%s", s)
}
return strings.ToLower(s)
}
func getCluster() string {
return os.Getenv("qstar_server_CLUSTER")
}
func getInstance() string {
return os.Getenv("qstar_server_INSTANCE")
}
func getExecutableDirectory() string {
if _, err := os.Stat(os.Args[0]); err == nil {
return filepath.Dir(os.Args[0])
}
path, err := exec.LookPath(os.Args[0])
if err != nil {
panic(err)
}
return filepath.Dir(path)
}
func getWorkingDirectory() string {
dir, err := os.Getwd()
if err != nil {
panic(err)
}
return dir
}
func getProjectDirectory() string {
// MatchParentDir returns target's directory's full path,
// returning error if `dir`'s parent dir names don't match `target`
matchParentDir := func(dir string, target string) (string, error) {
var currentDir string
var file string
for {
currentDir = filepath.Dir(dir)
file = filepath.Base(dir)
// Match target directory
if file == target {
return dir, nil
}
// Reach the top of directory
if currentDir == dir {
return "", fmt.Errorf(
"diretory `%s` doesn't match `%s`", dir, target)
}
dir = currentDir
}
}
dir, err := matchParentDir(WorkingDirectory, Project)
if err != nil {
dir, err = os.Getwd()
if err != nil {
panic(err)
}
}
return dir
}
func getConfigDirectory() string {
return filepath.Join(ProjectDirectory, "resource/config")
}
func InitGeneric() {
config.ReadBinary(func() []string {
var assetNames = make([]string, 0)
for _, assetName := range resource.AssetNames() {
if strings.HasPrefix(assetName, "resource/config/generic") {
assetNames = append(assetNames, assetName)
}
}
sort.Strings(assetNames)
return assetNames
}, resource.Asset)
}
func getConfig() *config.Config {
config.SetRuntimeEnv(Runtime).ReadBinary(func() []string {
var assetNames = make([]string, 0)
for _, assetName := range resource.AssetNames() {
/*if strings.HasPrefix(assetName, "resource/config/generic") {
assetNames = append(assetNames, assetName)
} else*/if strings.HasPrefix(assetName, "resource/config/runtime/"+Runtime) {
assetNames = append(assetNames, assetName)
}
}
sort.Strings(assetNames)
return assetNames
}, resource.Asset)
config.Default().AutomaticEnv()
config.Default().SetEnvPrefix("qstar_server")
config.Default().SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
config.Default().AutoParse(1)
return config.Default()
}
func getTimex() *timex.Timex {
tm := timex.Init(config.JSON("timex"))
dogfish.LocateAt(timex.TimeLocation())
return tm
}
func getLogger() *logrus.Logger {
logger, err := logger.New(config.Parse(config.JSON("logger.default")))
if err != nil {
panic(err)
}
//log.Use(logger)
return logger
}
func getMock() bool {
s := os.Getenv("qstar_server_MOCK")
logger2.Logger.Infof("qstar_server_MOCK--------- [%v]", s)
if s != "" {
if s == "true" {
return true
} else {
return false
}
}
return config.GetBool("mock")
}
func getHTTPClient() *httpx.Client {
c := httpx.NewClient(httpx.ClientConfig{
Retry: config.GetInt64("http.retry"),
Timeout: config.GetDuration("http.timeout") * time.Second,
Proxy: config.GetString("http.proxy"),
DialerTimeout: config.GetDuration("http.dialerTimeout") * time.Second,
DialerKeepAlive: config.GetDuration("http.dialerKeepAlive") * time.Second,
ForceAttemptHTTP2: config.GetBool("http.forceAttemptHTTP2"),
MaxIdleConns: config.GetInt("http.maxIdleConns"),
MaxIdleConnsPerHost: config.GetInt("http.maxIdleConnsPerHost"),
MaxConnsPerHost: config.GetInt("http.maxConnsPerHost"),
IdleConnTimeout: config.GetDuration("http.idleConnTimeout") * time.Second,
TLSHandshakeTimeout: config.GetDuration("http.tlsHandshakeTimeout") * time.Second,
ResponseHeaderTimeout: config.GetDuration("http.responseHeaderTimeout") * time.Second,
ExpectContinueTimeout: config.GetDuration("http.expectContinueTimeout") * time.Second,
})
return c
}
func getRedisClient() *redis.Client {
c := redis.NewClient(&redis.Options{
Addr: config.GetString("redis.player.addr"),
Password: config.GetString("redis.player.password"),
DB: config.GetInt("redis.player.db"),
PoolSize: config.GetInt("redis.player.poolSize"),
MinIdleConns: config.GetInt("redis.player.minIdleConns"),
MaxConnAge: config.GetDuration("redis.player.maxConnAge") * time.Second,
PoolTimeout: config.GetDuration("redis.player.poolTimeout") * time.Second,
IdleTimeout: config.GetDuration("redis.player.idleTimeout") * time.Second,
IdleCheckFrequency: config.GetDuration("redis.player.idleCheckFrequency") * time.Second,
})
return c
}