main.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. package main
  2. import (
  3. "embed"
  4. "fmt"
  5. "github.com/bytedance/gopkg/util/gopool"
  6. "github.com/gin-contrib/sessions"
  7. "github.com/gin-contrib/sessions/cookie"
  8. "github.com/gin-gonic/gin"
  9. "log"
  10. "net/http"
  11. "one-api/common"
  12. "one-api/constant"
  13. "one-api/controller"
  14. "one-api/middleware"
  15. "one-api/model"
  16. "one-api/router"
  17. "one-api/service"
  18. "os"
  19. "strconv"
  20. _ "net/http/pprof"
  21. )
  22. //go:embed web/dist
  23. var buildFS embed.FS
  24. //go:embed web/dist/index.html
  25. var indexPage []byte
  26. func main() {
  27. common.SetupLogger()
  28. common.SysLog("New API " + common.Version + " started")
  29. if os.Getenv("GIN_MODE") != "debug" {
  30. gin.SetMode(gin.ReleaseMode)
  31. }
  32. if common.DebugEnabled {
  33. common.SysLog("running in debug mode")
  34. }
  35. // Initialize SQL Database
  36. err := model.InitDB()
  37. if err != nil {
  38. common.FatalLog("failed to initialize database: " + err.Error())
  39. }
  40. // Initialize SQL Database
  41. err = model.InitLogDB()
  42. if err != nil {
  43. common.FatalLog("failed to initialize database: " + err.Error())
  44. }
  45. defer func() {
  46. err := model.CloseDB()
  47. if err != nil {
  48. common.FatalLog("failed to close database: " + err.Error())
  49. }
  50. }()
  51. // Initialize Redis
  52. err = common.InitRedisClient()
  53. if err != nil {
  54. common.FatalLog("failed to initialize Redis: " + err.Error())
  55. }
  56. // Initialize constants
  57. constant.InitEnv()
  58. // Initialize options
  59. model.InitOptionMap()
  60. if common.RedisEnabled {
  61. // for compatibility with old versions
  62. common.MemoryCacheEnabled = true
  63. }
  64. if common.MemoryCacheEnabled {
  65. common.SysLog("memory cache enabled")
  66. common.SysError(fmt.Sprintf("sync frequency: %d seconds", common.SyncFrequency))
  67. model.InitChannelCache()
  68. }
  69. if common.RedisEnabled {
  70. go model.SyncTokenCache(common.SyncFrequency)
  71. }
  72. if common.MemoryCacheEnabled {
  73. go model.SyncOptions(common.SyncFrequency)
  74. go model.SyncChannelCache(common.SyncFrequency)
  75. }
  76. // 数据看板
  77. go model.UpdateQuotaData()
  78. if os.Getenv("CHANNEL_UPDATE_FREQUENCY") != "" {
  79. frequency, err := strconv.Atoi(os.Getenv("CHANNEL_UPDATE_FREQUENCY"))
  80. if err != nil {
  81. common.FatalLog("failed to parse CHANNEL_UPDATE_FREQUENCY: " + err.Error())
  82. }
  83. go controller.AutomaticallyUpdateChannels(frequency)
  84. }
  85. if os.Getenv("CHANNEL_TEST_FREQUENCY") != "" {
  86. frequency, err := strconv.Atoi(os.Getenv("CHANNEL_TEST_FREQUENCY"))
  87. if err != nil {
  88. common.FatalLog("failed to parse CHANNEL_TEST_FREQUENCY: " + err.Error())
  89. }
  90. go controller.AutomaticallyTestChannels(frequency)
  91. }
  92. if common.IsMasterNode && constant.UpdateTask {
  93. gopool.Go(func() {
  94. controller.UpdateMidjourneyTaskBulk()
  95. })
  96. gopool.Go(func() {
  97. controller.UpdateTaskBulk()
  98. })
  99. }
  100. if os.Getenv("BATCH_UPDATE_ENABLED") == "true" {
  101. common.BatchUpdateEnabled = true
  102. common.SysLog("batch update enabled with interval " + strconv.Itoa(common.BatchUpdateInterval) + "s")
  103. model.InitBatchUpdater()
  104. }
  105. if os.Getenv("ENABLE_PPROF") == "true" {
  106. go func() {
  107. log.Println(http.ListenAndServe("0.0.0.0:8005", nil))
  108. }()
  109. go common.Monitor()
  110. common.SysLog("pprof enabled")
  111. }
  112. service.InitTokenEncoders()
  113. // Initialize HTTP server
  114. server := gin.New()
  115. server.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
  116. common.SysError(fmt.Sprintf("panic detected: %v", err))
  117. c.JSON(http.StatusInternalServerError, gin.H{
  118. "error": gin.H{
  119. "message": fmt.Sprintf("Panic detected, error: %v. Please submit a issue here: https://github.com/Calcium-Ion/new-api", err),
  120. "type": "new_api_panic",
  121. },
  122. })
  123. }))
  124. // This will cause SSE not to work!!!
  125. //server.Use(gzip.Gzip(gzip.DefaultCompression))
  126. server.Use(middleware.RequestId())
  127. middleware.SetUpLogger(server)
  128. // Initialize session store
  129. store := cookie.NewStore([]byte(common.SessionSecret))
  130. server.Use(sessions.Sessions("session", store))
  131. router.SetRouter(server, buildFS, indexPage)
  132. var port = os.Getenv("PORT")
  133. if port == "" {
  134. port = strconv.Itoa(*common.Port)
  135. }
  136. err = server.Run(":" + port)
  137. if err != nil {
  138. common.FatalLog("failed to start HTTP server: " + err.Error())
  139. }
  140. }