main.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. package main
  2. import (
  3. "embed"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "one-api/common"
  8. "one-api/constant"
  9. "one-api/controller"
  10. "one-api/logger"
  11. "one-api/middleware"
  12. "one-api/model"
  13. "one-api/router"
  14. "one-api/service"
  15. "one-api/setting/ratio_setting"
  16. "os"
  17. "strconv"
  18. "github.com/bytedance/gopkg/util/gopool"
  19. "github.com/gin-contrib/sessions"
  20. "github.com/gin-contrib/sessions/cookie"
  21. "github.com/gin-gonic/gin"
  22. "github.com/joho/godotenv"
  23. _ "net/http/pprof"
  24. )
  25. //go:embed web/dist
  26. var buildFS embed.FS
  27. //go:embed web/dist/index.html
  28. var indexPage []byte
  29. func main() {
  30. err := InitResources()
  31. if err != nil {
  32. common.FatalLog("failed to initialize resources: " + err.Error())
  33. return
  34. }
  35. common.SysLog("New API " + common.Version + " started")
  36. if os.Getenv("GIN_MODE") != "debug" {
  37. gin.SetMode(gin.ReleaseMode)
  38. }
  39. if common.DebugEnabled {
  40. common.SysLog("running in debug mode")
  41. }
  42. defer func() {
  43. err := model.CloseDB()
  44. if err != nil {
  45. common.FatalLog("failed to close database: " + err.Error())
  46. }
  47. }()
  48. if common.RedisEnabled {
  49. // for compatibility with old versions
  50. common.MemoryCacheEnabled = true
  51. }
  52. if common.MemoryCacheEnabled {
  53. common.SysLog("memory cache enabled")
  54. common.SysLog(fmt.Sprintf("sync frequency: %d seconds", common.SyncFrequency))
  55. // Add panic recovery and retry for InitChannelCache
  56. func() {
  57. defer func() {
  58. if r := recover(); r != nil {
  59. common.SysLog(fmt.Sprintf("InitChannelCache panic: %v, retrying once", r))
  60. // Retry once
  61. _, _, fixErr := model.FixAbility()
  62. if fixErr != nil {
  63. common.FatalLog(fmt.Sprintf("InitChannelCache failed: %s", fixErr.Error()))
  64. }
  65. }
  66. }()
  67. model.InitChannelCache()
  68. }()
  69. go model.SyncChannelCache(common.SyncFrequency)
  70. }
  71. // 热更新配置
  72. go model.SyncOptions(common.SyncFrequency)
  73. // 数据看板
  74. go model.UpdateQuotaData()
  75. if os.Getenv("CHANNEL_UPDATE_FREQUENCY") != "" {
  76. frequency, err := strconv.Atoi(os.Getenv("CHANNEL_UPDATE_FREQUENCY"))
  77. if err != nil {
  78. common.FatalLog("failed to parse CHANNEL_UPDATE_FREQUENCY: " + err.Error())
  79. }
  80. go controller.AutomaticallyUpdateChannels(frequency)
  81. }
  82. go controller.AutomaticallyTestChannels()
  83. if common.IsMasterNode && constant.UpdateTask {
  84. gopool.Go(func() {
  85. controller.UpdateMidjourneyTaskBulk()
  86. })
  87. gopool.Go(func() {
  88. controller.UpdateTaskBulk()
  89. })
  90. }
  91. if os.Getenv("BATCH_UPDATE_ENABLED") == "true" {
  92. common.BatchUpdateEnabled = true
  93. common.SysLog("batch update enabled with interval " + strconv.Itoa(common.BatchUpdateInterval) + "s")
  94. model.InitBatchUpdater()
  95. }
  96. if os.Getenv("ENABLE_PPROF") == "true" {
  97. gopool.Go(func() {
  98. log.Println(http.ListenAndServe("0.0.0.0:8005", nil))
  99. })
  100. go common.Monitor()
  101. common.SysLog("pprof enabled")
  102. }
  103. // Initialize HTTP server
  104. server := gin.New()
  105. server.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
  106. common.SysLog(fmt.Sprintf("panic detected: %v", err))
  107. c.JSON(http.StatusInternalServerError, gin.H{
  108. "error": gin.H{
  109. "message": fmt.Sprintf("Panic detected, error: %v. Please submit a issue here: https://github.com/Calcium-Ion/new-api", err),
  110. "type": "new_api_panic",
  111. },
  112. })
  113. }))
  114. // This will cause SSE not to work!!!
  115. //server.Use(gzip.Gzip(gzip.DefaultCompression))
  116. server.Use(middleware.RequestId())
  117. middleware.SetUpLogger(server)
  118. // Initialize session store
  119. store := cookie.NewStore([]byte(common.SessionSecret))
  120. store.Options(sessions.Options{
  121. Path: "/",
  122. MaxAge: 2592000, // 30 days
  123. HttpOnly: true,
  124. Secure: false,
  125. SameSite: http.SameSiteStrictMode,
  126. })
  127. server.Use(sessions.Sessions("session", store))
  128. router.SetRouter(server, buildFS, indexPage)
  129. var port = os.Getenv("PORT")
  130. if port == "" {
  131. port = strconv.Itoa(*common.Port)
  132. }
  133. err = server.Run(":" + port)
  134. if err != nil {
  135. common.FatalLog("failed to start HTTP server: " + err.Error())
  136. }
  137. }
  138. func InitResources() error {
  139. // Initialize resources here if needed
  140. // This is a placeholder function for future resource initialization
  141. err := godotenv.Load(".env")
  142. if err != nil {
  143. common.SysLog("未找到 .env 文件,使用默认环境变量,如果需要,请创建 .env 文件并设置相关变量")
  144. common.SysLog("No .env file found, using default environment variables. If needed, please create a .env file and set the relevant variables.")
  145. }
  146. // 加载环境变量
  147. common.InitEnv()
  148. logger.SetupLogger()
  149. // Initialize model settings
  150. ratio_setting.InitRatioSettings()
  151. service.InitHttpClient()
  152. service.InitTokenEncoders()
  153. // Initialize SQL Database
  154. err = model.InitDB()
  155. if err != nil {
  156. common.FatalLog("failed to initialize database: " + err.Error())
  157. return err
  158. }
  159. model.CheckSetup()
  160. // Initialize options, should after model.InitDB()
  161. model.InitOptionMap()
  162. // 初始化模型
  163. model.GetPricing()
  164. // Initialize SQL Database
  165. err = model.InitLogDB()
  166. if err != nil {
  167. return err
  168. }
  169. // Initialize Redis
  170. err = common.InitRedisClient()
  171. if err != nil {
  172. return err
  173. }
  174. return nil
  175. }