main.go 6.1 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(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. appname := conf.Rpc.Vehicle.Name
  63. // 指定mysql数据库,若无则使用默认数据库
  64. mysqldb := conf.Rpc.Vehicle.MysqlDB
  65. if mysqldb == "" {
  66. mysqldb = conf.Mysql.DefaultDB
  67. }
  68. mysqldb = ""
  69. // 指定redis数据库,若无则使用默认数据库
  70. redisdb := conf.Rpc.Vehicle.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. // 初始化mongodb数据库
  85. //clinit.InitMongo(conf.Mongo.Addr, conf.Mongo.User, conf.Mongo.Password)
  86. // 连接redis服务器
  87. cache.InitRedis(&cache.RedisConfig{
  88. Addrs: strings.Split(conf.Redis.Addrs, ","),
  89. Password: conf.Redis.Password,
  90. DB: redisdb,
  91. PoolSize: conf.Redis.PoolSize,
  92. MinIdleConns: conf.Redis.MinIdleConns,
  93. MaxRetries: conf.Redis.MaxRetries,
  94. IsCluster: conf.Redis.IsCluster,
  95. })
  96. //rpc_apis.Init(etcdAddrs, conf)
  97. // clinit.InitUniqueID()
  98. // clinit.InitElastic(conf.Elastic.Addr, conf.Elastic.Sniff == "true")
  99. // 初始化logger
  100. ms, _ := conf.Rpc.Vehicle.Log.MaxSize.Int64()
  101. mb, _ := conf.Rpc.Vehicle.Log.MaxBackups.Int64()
  102. ma, _ := conf.Rpc.Vehicle.Log.MaxAge.Int64()
  103. maxSize := int(ms)
  104. maxBackups := int(mb)
  105. maxAge := int(ma)
  106. disableStacktrace := (conf.Rpc.Vehicle.Log.DisableStacktrace == "true")
  107. // 通用logger
  108. commonLogger := logger.InitLogger(runmode, fmt.Sprintf("%s/%s.log", logDir, appname), appname, conf.Rpc.Vehicle.Log.Level,
  109. maxSize, maxBackups, maxAge, disableStacktrace)
  110. // 单独设置
  111. accessLogger := logger.NewInfoLogger(runmode, fmt.Sprintf("%s/%s-access.log", logDir, appname), appname, conf.Rpc.Vehicle.Log.Level,
  112. maxSize, maxBackups, maxAge)
  113. thirdpartyLogger := logger.NewInfoLogger(runmode, fmt.Sprintf("%s/%s-thirdparty.log", logDir, appname), appname, conf.Rpc.Vehicle.Log.Level,
  114. maxSize, maxBackups, maxAge)
  115. // 设置需要使用logger的地方
  116. // common日志
  117. impl.SetLogger(commonLogger)
  118. dutils.SetLogger(commonLogger)
  119. // access日志
  120. task.SetLogger(accessLogger)
  121. // 第三方日志
  122. thirdparty.SetLogger(thirdpartyLogger)
  123. impl.RegisterOrmModel()
  124. dutils.ProviderApiHystrixLoad()
  125. // 打开第三方包调试开关
  126. if runmode != "prod" {
  127. orm.Debug = true
  128. //redis.Debug = true
  129. }
  130. }
  131. func start(conf *config.Configure, serveAddr string, etcdAddrs []string) {
  132. s := server.NewServer()
  133. r := &serverplugin.EtcdRegisterPlugin{
  134. ServiceAddress: fmt.Sprintf("tcp@%s", serveAddr),
  135. EtcdServers: etcdAddrs,
  136. BasePath: conf.Rpc.BasePath,
  137. Metrics: metrics.NewRegistry(),
  138. UpdateInterval: time.Minute,
  139. }
  140. if err := r.Start(); err != nil {
  141. fmt.Printf("start failed. error:%s\n\n", err)
  142. os.Exit(1)
  143. }
  144. s.Plugins.Add(r)
  145. s.RegisterName(conf.Rpc.Vehicle.Name, new(impl.Rcvr), "")
  146. go func() {
  147. if err := s.Serve("tcp", serveAddr); err != nil {
  148. log.Fatalf("HTTP server listen failed. err: %s\n", err.Error())
  149. }
  150. }()
  151. // 捕获信号
  152. sigChan := make(chan os.Signal, 1)
  153. signal.Notify(sigChan, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
  154. sigValue := <-sigChan
  155. log.Printf("Got a signal:%v", sigValue)
  156. r.Stop()
  157. time.Sleep(5 * time.Second)
  158. log.Println("Shutdown server finished.")
  159. }
  160. func startPeerToPeer(conf *config.Configure, serveAddr string) {
  161. s := server.NewServer()
  162. s.RegisterName(conf.Rpc.Vehicle.Name, new(impl.Rcvr), "")
  163. s.Serve("tcp", serveAddr)
  164. }
  165. func main() {
  166. flag.Parse()
  167. if *version {
  168. showVersion()
  169. }
  170. cfg, err := ini.Load(*configFile)
  171. if err != nil {
  172. fmt.Printf("Fail to read file: %v\n\n", err)
  173. os.Exit(1)
  174. }
  175. //appname := cfg.Section("").Key("appname").String()
  176. runmode := cfg.Section("").Key("runmode").String()
  177. logDir := cfg.Section("").Key("log_dir").String()
  178. //serveAddr := cfg.Section("").Key("serve_addr").String()
  179. etcdAddrs := strings.Split(cfg.Section("").Key("etcd_addrs").String(), ",")
  180. encryptKey := cfg.Section("").Key("encrypt_key").String()
  181. discoveryType := cfg.Section("").Key("discovery_type").String()
  182. projectName := cfg.Section("").Key("project_name").String()
  183. utils.SetRunmode(runmode)
  184. prepare(projectName, runmode, encryptKey, logDir, etcdAddrs, discoveryType)
  185. go utils.Free()
  186. serveAddr := fmt.Sprintf("%s:%s", gconfig.Conf.Rpc.Vehicle.ServiceName, gconfig.Conf.Rpc.Vehicle.ServicePort.String())
  187. if discoveryType == "etcd" {
  188. start(gconfig.Conf, serveAddr, etcdAddrs)
  189. } else {
  190. startPeerToPeer(gconfig.Conf, serveAddr)
  191. }
  192. return
  193. }