startup.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "sync"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. "github.com/joho/godotenv"
  13. "github.com/labring/aiproxy/core/common"
  14. "github.com/labring/aiproxy/core/common/balance"
  15. "github.com/labring/aiproxy/core/common/config"
  16. "github.com/labring/aiproxy/core/common/notify"
  17. "github.com/labring/aiproxy/core/common/pprof"
  18. "github.com/labring/aiproxy/core/middleware"
  19. "github.com/labring/aiproxy/core/model"
  20. "github.com/labring/aiproxy/core/router"
  21. log "github.com/sirupsen/logrus"
  22. )
  23. func initializeServices(pprofPort int) error {
  24. initializePprof(pprofPort)
  25. initializeNotifier()
  26. if err := common.InitRedisClient(); err != nil {
  27. return err
  28. }
  29. if err := initializeBalance(); err != nil {
  30. return err
  31. }
  32. if err := model.InitDB(); err != nil {
  33. return err
  34. }
  35. if err := initializeOptionAndCaches(); err != nil {
  36. return err
  37. }
  38. return model.InitLogDB(int(config.GetCleanLogBatchSize()))
  39. }
  40. func initializePprof(pprofPort int) {
  41. go func() {
  42. err := pprof.RunPprofServer(pprofPort)
  43. if err != nil {
  44. log.Errorf("run pprof server error: %v", err)
  45. }
  46. }()
  47. }
  48. func initializeBalance() error {
  49. sealosJwtKey := os.Getenv("SEALOS_JWT_KEY")
  50. if sealosJwtKey == "" {
  51. log.Info("SEALOS_JWT_KEY is not set, balance will not be enabled")
  52. return nil
  53. }
  54. log.Info("SEALOS_JWT_KEY is set, balance will be enabled")
  55. return balance.InitSealos(sealosJwtKey, os.Getenv("SEALOS_ACCOUNT_URL"))
  56. }
  57. func initializeNotifier() {
  58. feishuWh := os.Getenv("NOTIFY_FEISHU_WEBHOOK")
  59. if feishuWh != "" {
  60. notify.SetDefaultNotifier(notify.NewFeishuNotify(feishuWh))
  61. log.Info("NOTIFY_FEISHU_WEBHOOK is set, notifier will be use feishu")
  62. }
  63. }
  64. func initializeOptionAndCaches() error {
  65. log.Info("starting init config and channel")
  66. if err := model.InitOption2DB(); err != nil {
  67. return err
  68. }
  69. return model.InitModelConfigAndChannelCache()
  70. }
  71. func startSyncServices(ctx context.Context, wg *sync.WaitGroup) {
  72. wg.Add(2)
  73. go model.SyncOptions(ctx, wg, time.Second*5)
  74. go model.SyncModelConfigAndChannelCache(ctx, wg, time.Second*10)
  75. }
  76. func setupHTTPServer(listen string) (*http.Server, *gin.Engine) {
  77. server := gin.New()
  78. server.Use(
  79. middleware.GinRecoveryHandler,
  80. middleware.NewLog(log.StandardLogger()),
  81. middleware.RequestIDMiddleware,
  82. middleware.CORS(),
  83. )
  84. router.SetRouter(server)
  85. listenEnv := os.Getenv("LISTEN")
  86. if listenEnv != "" {
  87. listen = listenEnv
  88. }
  89. return &http.Server{
  90. Addr: listen,
  91. ReadHeaderTimeout: 10 * time.Second,
  92. Handler: server,
  93. }, server
  94. }
  95. var loadedEnvFiles []string
  96. func loadEnv() {
  97. envfiles := []string{
  98. ".env",
  99. ".env.local",
  100. }
  101. for _, envfile := range envfiles {
  102. absPath, err := filepath.Abs(envfile)
  103. if err != nil {
  104. panic(
  105. fmt.Sprintf(
  106. "failed to get absolute path of env file: %s, error: %s",
  107. envfile,
  108. err.Error(),
  109. ),
  110. )
  111. }
  112. file, err := os.Stat(absPath)
  113. if err != nil {
  114. continue
  115. }
  116. if file.IsDir() {
  117. continue
  118. }
  119. if err := godotenv.Overload(absPath); err != nil {
  120. panic(fmt.Sprintf("failed to load env file: %s, error: %s", absPath, err.Error()))
  121. }
  122. loadedEnvFiles = append(loadedEnvFiles, absPath)
  123. }
  124. }
  125. func printLoadedEnvFiles() {
  126. for _, envfile := range loadedEnvFiles {
  127. log.Infof("loaded env file: %s", envfile)
  128. }
  129. }
  130. func listenAndServe(srv *http.Server) {
  131. if err := srv.ListenAndServe(); err != nil &&
  132. !errors.Is(err, http.ErrServerClosed) {
  133. log.Fatal("failed to start HTTP server: " + err.Error())
  134. }
  135. }