server.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. package alert
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "time"
  10. "github.com/gin-contrib/pprof"
  11. "github.com/gin-gonic/gin"
  12. "github.com/go-admin-team/go-admin-core/config/source/file"
  13. "github.com/go-admin-team/go-admin-core/sdk"
  14. "github.com/go-admin-team/go-admin-core/sdk/api"
  15. "github.com/go-admin-team/go-admin-core/sdk/config"
  16. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  17. "github.com/spf13/cobra"
  18. "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
  19. "go-admin/app/alert/router"
  20. "go-admin/common/database"
  21. common "go-admin/common/middleware"
  22. mhandler "go-admin/common/middleware/handler"
  23. extConfig "go-admin/config"
  24. "go-admin/handler"
  25. )
  26. var (
  27. configYml string
  28. apiCheck bool
  29. StartCmd = &cobra.Command{
  30. Use: "alert",
  31. Short: "Start Alert server",
  32. Example: "go-admin alert -c config/settings.yml",
  33. SilenceUsage: true,
  34. PreRun: func(cmd *cobra.Command, args []string) {
  35. setup()
  36. },
  37. RunE: func(cmd *cobra.Command, args []string) error {
  38. return run()
  39. },
  40. }
  41. )
  42. var AppRouters = make([]func(), 0)
  43. func init() {
  44. StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
  45. AppRouters = append(AppRouters, router.InitRouter)
  46. }
  47. func setup() {
  48. config.ExtendConfig = &extConfig.ExtConfig
  49. //1. 读取配置
  50. config.Setup(
  51. file.NewSource(file.WithPath(configYml)),
  52. database.Setup,
  53. // storage.Setup,
  54. // olap.Setup,
  55. )
  56. usageStr := `starting alert server...`
  57. log.Println(usageStr)
  58. }
  59. func run() error {
  60. handler.SetAlertManager()
  61. if config.ApplicationConfig.Mode == pkg.ModeProd.String() {
  62. // gin.SetMode(gin.ReleaseMode)
  63. }
  64. initRouter()
  65. //暴露metric数据接口
  66. for _, f := range AppRouters {
  67. f()
  68. }
  69. srv := &http.Server{
  70. Addr: fmt.Sprintf("%s:%d", config.ApplicationConfig.Host, config.ApplicationConfig.Port),
  71. Handler: sdk.Runtime.GetEngine(),
  72. }
  73. go func() {
  74. // 服务连接
  75. if config.SslConfig.Enable {
  76. if err := srv.ListenAndServeTLS(config.SslConfig.Pem, config.SslConfig.KeyStr); err != nil && err != http.ErrServerClosed {
  77. log.Fatal("listen: ", err)
  78. }
  79. } else {
  80. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  81. log.Fatal("listen: ", err)
  82. }
  83. }
  84. }()
  85. fmt.Println(pkg.Green("Server run at:"))
  86. fmt.Printf("- Local: http://localhost:%d/ \r\n", config.ApplicationConfig.Port)
  87. fmt.Printf("- Network: http://%s:%d/ \r\n", pkg.GetLocaHonst(), config.ApplicationConfig.Port)
  88. //TODO:10s一次的检测,设定可配置
  89. // productor
  90. ticker := time.Tick(time.Duration(handler.GetAlertManager().Interval) * time.Second)
  91. go func() {
  92. handler.GetAlertManager().PolicyProducter()
  93. for {
  94. select {
  95. case <-ticker:
  96. fmt.Println("alert policy producting....")
  97. handler.GetAlertManager().PolicyProducter()
  98. }
  99. }
  100. }()
  101. go func() {
  102. handler.GetAlertManager().PolicyConsumer()
  103. }()
  104. defer handler.CloseAlertManager()
  105. fmt.Println(pkg.Red("Start alert Service"))
  106. quit := make(chan os.Signal, 1)
  107. signal.Notify(quit, os.Interrupt)
  108. <-quit
  109. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  110. defer cancel()
  111. fmt.Printf("%s Shutdown Server ... \r\n", pkg.GetCurrentTimeStr())
  112. fmt.Printf("%s Shutdown alert server ... \r\n", pkg.GetCurrentTimeStr())
  113. log.Println("Alert server exiting")
  114. if err := srv.Shutdown(ctx); err != nil {
  115. log.Fatal("Server Shutdown:", err)
  116. }
  117. log.Println("Server exiting")
  118. return nil
  119. }
  120. func initRouter() {
  121. var r *gin.Engine
  122. h := sdk.Runtime.GetEngine()
  123. if h == nil {
  124. h = gin.New()
  125. sdk.Runtime.SetEngine(h)
  126. }
  127. switch h := h.(type) {
  128. case *gin.Engine:
  129. r = h
  130. default:
  131. log.Fatal("not support other engine")
  132. os.Exit(-1)
  133. }
  134. if config.ApplicationConfig.Mode == "dev" {
  135. pprof.Register(r)
  136. }
  137. if config.SslConfig.Enable {
  138. r.Use(mhandler.TlsHandler())
  139. }
  140. r.Use(otelgin.Middleware("observe-server"))
  141. // r.Use(middleware.Metrics())
  142. r.Use(common.Sentinel()).
  143. Use(common.RequestId(pkg.TrafficKey)).
  144. Use(api.SetRequestLogger)
  145. common.InitMiddleware(r)
  146. }