main.go 5.1 KB

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