main.go 5.0 KB

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