main.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package main
  4. import (
  5. "context"
  6. "flag"
  7. "fmt"
  8. "log"
  9. "net"
  10. "os"
  11. "os/signal"
  12. "smart-auth/impl/v1/device"
  13. "syscall"
  14. "time"
  15. "smart-auth/impl"
  16. "smart-auth/parser"
  17. "github.com/jaryhe/gopkgs/database"
  18. "github.com/jaryhe/gopkgs/tasker"
  19. "google.golang.org/grpc"
  20. )
  21. var (
  22. configFile = flag.String("config", "conf/common.yaml", "config file location")
  23. version = flag.Bool("version", false, "print the version")
  24. GitCommit = "library-import"
  25. Version = "library-import"
  26. )
  27. func showVersion() {
  28. fmt.Println("Version: ", Version)
  29. fmt.Println("GitCommit:", GitCommit)
  30. }
  31. func prepare(filename string) {
  32. // 加载配置
  33. err := parser.LoadConfig(filename)
  34. if err != nil {
  35. fmt.Printf("get conf failed, err: %+v\n\n", err)
  36. os.Exit(1)
  37. }
  38. // 注册处理函数
  39. // parser.Register(parser.MysqlHandler, parser.RedisHandler, parser.LoggerHandler)
  40. parser.Register(parser.LoggerHandler, parser.MysqlHandler)
  41. // 执行注册的处理函数
  42. parser.Handle()
  43. device.Init()
  44. }
  45. func run() {
  46. // 开始监听
  47. serveAddr := fmt.Sprintf("%s:%d", parser.Conf.Rpc.SmartAuth.ServiceIp, parser.Conf.Rpc.SmartAuth.ServicePort)
  48. log.Printf("Listening and serving TCP on %s\n", serveAddr)
  49. lis, err := net.Listen("tcp", serveAddr)
  50. if err != nil {
  51. os.Exit(1)
  52. }
  53. s := grpc.NewServer()
  54. impl.Register(s)
  55. go func() {
  56. if err := s.Serve(lis); err != nil {
  57. log.Fatalf("HTTP server listen failed. err: %s\n", err.Error())
  58. }
  59. }()
  60. // 优雅关闭服务器
  61. sigChan := make(chan os.Signal, 1)
  62. // 捕获信号
  63. signal.Notify(sigChan, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
  64. sigValue := <-sigChan
  65. log.Printf("Got a signal:%v", sigValue)
  66. // 让tasker安全退出
  67. tasker.SignalNotify(sigValue)
  68. // 不管什么行为,都等待5秒退出
  69. log.Println("Start to shutdown server...")
  70. _, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  71. defer cancel()
  72. s.Stop()
  73. log.Println("Shutdown server finished.")
  74. }
  75. func main() {
  76. defer func() {
  77. database.Close()
  78. }()
  79. flag.Parse()
  80. if *version {
  81. showVersion()
  82. os.Exit(1)
  83. }
  84. prepare(*configFile)
  85. //go utils.Free()
  86. run()
  87. return
  88. }