main.go 6.0 KB

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