main.go 6.3 KB

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