main.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright 2019 utimes.cc. All rights reserved.
  2. // Use of this source code is governed by utimes.cc.
  3. package main
  4. import (
  5. "gd_auth_check/limit"
  6. "flag"
  7. "fmt"
  8. "log"
  9. "os"
  10. "os/signal"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "gd_auth_check/impl"
  15. "gd_auth_check/impl/data_api_check"
  16. "gd_auth_check/common.in/cache"
  17. "gd_auth_check/common.in/clinit"
  18. "gd_auth_check/common.in/config"
  19. "gd_auth_check/common.in/logger"
  20. "gd_auth_check/common.in/task"
  21. "gd_auth_check/common.in/utils"
  22. "github.com/astaxie/beego/orm"
  23. _ "github.com/go-sql-driver/mysql"
  24. //"github.com/gomodule/redigo/redis"
  25. "github.com/smallnest/rpcx/server"
  26. "github.com/smallnest/rpcx/serverplugin"
  27. gconfig "gd_auth_check/common.in/config"
  28. "gd_auth_check/rpc_apis"
  29. "github.com/rcrowley/go-metrics"
  30. "gopkg.in/ini.v1"
  31. )
  32. var (
  33. // 这里可以改默认值
  34. configFile = flag.String("config", "/etc/gd_auth_check/app.conf", "config file location")
  35. version = flag.Bool("version", false, "config file location")
  36. GitCommit = "library-import"
  37. Version = "library-import"
  38. )
  39. func showVersion() {
  40. fmt.Println("Version: ", Version)
  41. fmt.Println("GitCommit:", GitCommit)
  42. }
  43. func prepare(projectName, runmode, key, logDir string, etcdAddrs []string, discoveryType string) {
  44. var conf *config.Configure
  45. if discoveryType == "k8s" {
  46. conf = config.GetConfigForK8s()
  47. if conf == nil {
  48. fmt.Printf("get conf failed\n\n")
  49. os.Exit(1)
  50. }
  51. rpc_apis.InitForK8s(conf)
  52. } else {
  53. // 先行于读配置
  54. clinit.InitEtcd(etcdAddrs)
  55. utils.SetEtcdKeyApi(clinit.GetEtcdClient())
  56. conf = config.GetConfig(projectName+"/"+runmode, key, clinit.GetEtcdClient())
  57. if conf == nil {
  58. fmt.Printf("get conf failed\n\n")
  59. os.Exit(1)
  60. }
  61. rpc_apis.Init(etcdAddrs, conf)
  62. }
  63. appname := conf.Rpc.AuthCheck.Name
  64. // 指定mysql数据库,若无则使用默认数据库
  65. mysqldb := conf.Rpc.AuthCheck.MysqlDB
  66. if mysqldb == "" {
  67. mysqldb = conf.Mysql.DefaultDB
  68. }
  69. // 指定redis数据库,若无则使用默认数据库
  70. redisdb := conf.Rpc.AuthCheck.RedisDB
  71. if redisdb == "" {
  72. redisdb = conf.Redis.DefaultDB
  73. }
  74. // 连接数据库服务器
  75. clinit.InitMySQL(&clinit.MysqlConfig{
  76. User: conf.Mysql.User,
  77. Password: conf.Mysql.Password,
  78. Addr: conf.Mysql.Addr,
  79. DB: mysqldb,
  80. Charset: conf.Mysql.Charset,
  81. MaxIdle: conf.Mysql.MaxIdle,
  82. MaxConn: conf.Mysql.MaxConn,
  83. })
  84. // 连接redis服务器
  85. cache.InitRedis(&cache.RedisConfig{
  86. Addrs: strings.Split(conf.Redis.Addrs, ","),
  87. Password: conf.Redis.Password,
  88. DB: redisdb,
  89. PoolSize: conf.Redis.PoolSize,
  90. MinIdleConns: conf.Redis.MinIdleConns,
  91. MaxRetries: conf.Redis.MaxRetries,
  92. IsCluster: conf.Redis.IsCluster,
  93. })
  94. //初始化logger
  95. ms, _ := conf.Rpc.AuthCheck.Log.MaxSize.Int64()
  96. mb, _ := conf.Rpc.AuthCheck.Log.MaxBackups.Int64()
  97. ma, _ := conf.Rpc.AuthCheck.Log.MaxAge.Int64()
  98. maxSize := int(ms)
  99. maxBackups := int(mb)
  100. maxAge := int(ma)
  101. disableStacktrace := (conf.Rpc.AuthCheck.Log.DisableStacktrace == "true")
  102. //通用logger
  103. commonLogger := logger.InitLogger(runmode, fmt.Sprintf("%s/%s.log", logDir, appname),
  104. maxSize, maxBackups, maxAge, disableStacktrace)
  105. // 单独设置
  106. accessLogger := logger.NewInfoLogger(runmode, fmt.Sprintf("%s/%s-access.log", logDir, appname),
  107. maxSize, maxBackups, maxAge)
  108. //thirdpartyLogger := logger.NewInfoLogger(runmode, fmt.Sprintf("%s/%s-thirdparty.log", logDir, appname),
  109. // maxSize, maxBackups, maxAge)
  110. // 设置需要使用logger的地方
  111. // common日志
  112. data_api_check.SetLogger(commonLogger)
  113. task.SetLogger(accessLogger)
  114. if runmode != "prod" {
  115. orm.Debug = true
  116. //redis.Debug = true
  117. }
  118. impl.RegisterModel()
  119. limit.InitLimiter()
  120. }
  121. func start(conf *config.Configure, serveAddr string, etcdAddrs []string) {
  122. s := server.NewServer()
  123. fmt.Printf("base path:%v\n", conf.Rpc.BasePath)
  124. r := &serverplugin.EtcdRegisterPlugin{
  125. ServiceAddress: fmt.Sprintf("tcp@%s", serveAddr),
  126. EtcdServers: etcdAddrs,
  127. BasePath: conf.Rpc.BasePath,
  128. Metrics: metrics.NewRegistry(),
  129. UpdateInterval: time.Minute,
  130. }
  131. if err := r.Start(); err != nil {
  132. fmt.Printf("start failed. error:%s\n\n", err)
  133. os.Exit(1)
  134. }
  135. s.Plugins.Add(r)
  136. s.RegisterName(conf.Rpc.AuthCheck.Name, new(impl.Rcvr), "")
  137. go func() {
  138. if err := s.Serve("tcp", serveAddr); err != nil {
  139. log.Fatalf("HTTP server listen failed. err: %s\n", err.Error())
  140. }
  141. }()
  142. // 捕获信号
  143. sigChan := make(chan os.Signal, 1)
  144. signal.Notify(sigChan, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
  145. sigValue := <-sigChan
  146. log.Printf("Got a signal:%v", sigValue)
  147. r.Stop()
  148. time.Sleep(5 * time.Second)
  149. log.Println("Shutdown server finished.")
  150. }
  151. func startPeerToPeer(conf *config.Configure, serveAddr string) {
  152. s := server.NewServer()
  153. s.RegisterName(conf.Rpc.AuthCheck.Name, new(impl.Rcvr), "")
  154. s.Serve("tcp", serveAddr)
  155. }
  156. func main() {
  157. flag.Parse()
  158. if *version {
  159. showVersion()
  160. }
  161. cfg, err := ini.Load(*configFile)
  162. if err != nil {
  163. fmt.Printf("Fail to read file: %v\n\n", err)
  164. os.Exit(1)
  165. }
  166. //appname := cfg.Section("").Key("appname").String()
  167. logDir := cfg.Section("").Key("log_dir").String()
  168. runmode := cfg.Section("").Key("runmode").String()
  169. //serveAddr := cfg.Section("").Key("serve_addr").String()
  170. etcdAddrs := strings.Split(cfg.Section("").Key("etcd_addrs").String(), ",")
  171. encryptKey := cfg.Section("").Key("encrypt_key").String()
  172. discoveryType := cfg.Section("").Key("discovery_type").String()
  173. projectName := cfg.Section("").Key("project_name").String()
  174. utils.SetRunmode(runmode)
  175. prepare(projectName, runmode, encryptKey, logDir, etcdAddrs, discoveryType)
  176. data_api_check.Watch()
  177. data_api_check.LoadRedis()
  178. go utils.Free()
  179. go data_api_check.CleanLocalCache()
  180. data_api_check.GetFilterRule()
  181. serveAddr := fmt.Sprintf("%s:%s",gconfig.Conf.Rpc.AuthCheck.ServiceName,gconfig.Conf.Rpc.AuthCheck.ServicePort.String())
  182. if discoveryType == "etcd" {
  183. start(gconfig.Conf, serveAddr, etcdAddrs)
  184. } else {
  185. startPeerToPeer(gconfig.Conf, serveAddr)
  186. }
  187. return
  188. }