main.go 5.1 KB

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