main.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package model
  2. import (
  3. "fmt"
  4. "log"
  5. "one-api/common"
  6. "one-api/constant"
  7. "os"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/glebarez/sqlite"
  12. "gorm.io/driver/mysql"
  13. "gorm.io/driver/postgres"
  14. "gorm.io/gorm"
  15. )
  16. var commonGroupCol string
  17. var commonKeyCol string
  18. var commonTrueVal string
  19. var commonFalseVal string
  20. var logKeyCol string
  21. var logGroupCol string
  22. func initCol() {
  23. // init common column names
  24. if common.UsingPostgreSQL {
  25. commonGroupCol = `"group"`
  26. commonKeyCol = `"key"`
  27. commonTrueVal = "true"
  28. commonFalseVal = "false"
  29. } else {
  30. commonGroupCol = "`group`"
  31. commonKeyCol = "`key`"
  32. commonTrueVal = "1"
  33. commonFalseVal = "0"
  34. }
  35. if os.Getenv("LOG_SQL_DSN") != "" {
  36. switch common.LogSqlType {
  37. case common.DatabaseTypePostgreSQL:
  38. logGroupCol = `"group"`
  39. logKeyCol = `"key"`
  40. default:
  41. logGroupCol = commonGroupCol
  42. logKeyCol = commonKeyCol
  43. }
  44. } else {
  45. // LOG_SQL_DSN 为空时,日志数据库与主数据库相同
  46. if common.UsingPostgreSQL {
  47. logGroupCol = `"group"`
  48. logKeyCol = `"key"`
  49. } else {
  50. logGroupCol = commonGroupCol
  51. logKeyCol = commonKeyCol
  52. }
  53. }
  54. // log sql type and database type
  55. //common.SysLog("Using Log SQL Type: " + common.LogSqlType)
  56. }
  57. var DB *gorm.DB
  58. var LOG_DB *gorm.DB
  59. func createRootAccountIfNeed() error {
  60. var user User
  61. //if user.Status != common.UserStatusEnabled {
  62. if err := DB.First(&user).Error; err != nil {
  63. common.SysLog("no user exists, create a root user for you: username is root, password is 123456")
  64. hashedPassword, err := common.Password2Hash("123456")
  65. if err != nil {
  66. return err
  67. }
  68. rootUser := User{
  69. Username: "root",
  70. Password: hashedPassword,
  71. Role: common.RoleRootUser,
  72. Status: common.UserStatusEnabled,
  73. DisplayName: "Root User",
  74. AccessToken: nil,
  75. Quota: 100000000,
  76. }
  77. DB.Create(&rootUser)
  78. }
  79. return nil
  80. }
  81. func CheckSetup() {
  82. setup := GetSetup()
  83. if setup == nil {
  84. // No setup record exists, check if we have a root user
  85. if RootUserExists() {
  86. common.SysLog("system is not initialized, but root user exists")
  87. // Create setup record
  88. newSetup := Setup{
  89. Version: common.Version,
  90. InitializedAt: time.Now().Unix(),
  91. }
  92. err := DB.Create(&newSetup).Error
  93. if err != nil {
  94. common.SysLog("failed to create setup record: " + err.Error())
  95. }
  96. constant.Setup = true
  97. } else {
  98. common.SysLog("system is not initialized and no root user exists")
  99. constant.Setup = false
  100. }
  101. } else {
  102. // Setup record exists, system is initialized
  103. common.SysLog("system is already initialized at: " + time.Unix(setup.InitializedAt, 0).String())
  104. constant.Setup = true
  105. }
  106. }
  107. func chooseDB(envName string, isLog bool) (*gorm.DB, error) {
  108. defer func() {
  109. initCol()
  110. }()
  111. dsn := os.Getenv(envName)
  112. if dsn != "" {
  113. if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
  114. // Use PostgreSQL
  115. common.SysLog("using PostgreSQL as database")
  116. if !isLog {
  117. common.UsingPostgreSQL = true
  118. } else {
  119. common.LogSqlType = common.DatabaseTypePostgreSQL
  120. }
  121. return gorm.Open(postgres.New(postgres.Config{
  122. DSN: dsn,
  123. PreferSimpleProtocol: true, // disables implicit prepared statement usage
  124. }), &gorm.Config{
  125. PrepareStmt: true, // precompile SQL
  126. })
  127. }
  128. if strings.HasPrefix(dsn, "local") {
  129. common.SysLog("SQL_DSN not set, using SQLite as database")
  130. if !isLog {
  131. common.UsingSQLite = true
  132. } else {
  133. common.LogSqlType = common.DatabaseTypeSQLite
  134. }
  135. return gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
  136. PrepareStmt: true, // precompile SQL
  137. })
  138. }
  139. // Use MySQL
  140. common.SysLog("using MySQL as database")
  141. // check parseTime
  142. if !strings.Contains(dsn, "parseTime") {
  143. if strings.Contains(dsn, "?") {
  144. dsn += "&parseTime=true"
  145. } else {
  146. dsn += "?parseTime=true"
  147. }
  148. }
  149. if !isLog {
  150. common.UsingMySQL = true
  151. } else {
  152. common.LogSqlType = common.DatabaseTypeMySQL
  153. }
  154. return gorm.Open(mysql.Open(dsn), &gorm.Config{
  155. PrepareStmt: true, // precompile SQL
  156. })
  157. }
  158. // Use SQLite
  159. common.SysLog("SQL_DSN not set, using SQLite as database")
  160. common.UsingSQLite = true
  161. return gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
  162. PrepareStmt: true, // precompile SQL
  163. })
  164. }
  165. func InitDB() (err error) {
  166. db, err := chooseDB("SQL_DSN", false)
  167. if err == nil {
  168. if common.DebugEnabled {
  169. db = db.Debug()
  170. }
  171. DB = db
  172. sqlDB, err := DB.DB()
  173. if err != nil {
  174. return err
  175. }
  176. sqlDB.SetMaxIdleConns(common.GetEnvOrDefault("SQL_MAX_IDLE_CONNS", 100))
  177. sqlDB.SetMaxOpenConns(common.GetEnvOrDefault("SQL_MAX_OPEN_CONNS", 1000))
  178. sqlDB.SetConnMaxLifetime(time.Second * time.Duration(common.GetEnvOrDefault("SQL_MAX_LIFETIME", 60)))
  179. if !common.IsMasterNode {
  180. return nil
  181. }
  182. if common.UsingMySQL {
  183. //_, _ = sqlDB.Exec("ALTER TABLE channels MODIFY model_mapping TEXT;") // TODO: delete this line when most users have upgraded
  184. }
  185. common.SysLog("database migration started")
  186. err = migrateDB()
  187. return err
  188. } else {
  189. common.FatalLog(err)
  190. }
  191. return err
  192. }
  193. func InitLogDB() (err error) {
  194. if os.Getenv("LOG_SQL_DSN") == "" {
  195. LOG_DB = DB
  196. return
  197. }
  198. db, err := chooseDB("LOG_SQL_DSN", true)
  199. if err == nil {
  200. if common.DebugEnabled {
  201. db = db.Debug()
  202. }
  203. LOG_DB = db
  204. sqlDB, err := LOG_DB.DB()
  205. if err != nil {
  206. return err
  207. }
  208. sqlDB.SetMaxIdleConns(common.GetEnvOrDefault("SQL_MAX_IDLE_CONNS", 100))
  209. sqlDB.SetMaxOpenConns(common.GetEnvOrDefault("SQL_MAX_OPEN_CONNS", 1000))
  210. sqlDB.SetConnMaxLifetime(time.Second * time.Duration(common.GetEnvOrDefault("SQL_MAX_LIFETIME", 60)))
  211. if !common.IsMasterNode {
  212. return nil
  213. }
  214. common.SysLog("database migration started")
  215. err = migrateLOGDB()
  216. return err
  217. } else {
  218. common.FatalLog(err)
  219. }
  220. return err
  221. }
  222. func migrateDB() error {
  223. if !common.UsingPostgreSQL {
  224. return migrateDBFast()
  225. }
  226. err := DB.AutoMigrate(
  227. &Channel{},
  228. &Token{},
  229. &User{},
  230. &Option{},
  231. &Redemption{},
  232. &Ability{},
  233. &Log{},
  234. &Midjourney{},
  235. &TopUp{},
  236. &QuotaData{},
  237. &Task{},
  238. &Setup{},
  239. &UsageStatistics{},
  240. &TokenUsageLog{},
  241. )
  242. if err != nil {
  243. return err
  244. }
  245. return nil
  246. }
  247. func migrateDBFast() error {
  248. var wg sync.WaitGroup
  249. migrations := []struct {
  250. model interface{}
  251. name string
  252. }{
  253. {&Channel{}, "Channel"},
  254. {&Token{}, "Token"},
  255. {&User{}, "User"},
  256. {&Option{}, "Option"},
  257. {&Redemption{}, "Redemption"},
  258. {&Ability{}, "Ability"},
  259. {&Log{}, "Log"},
  260. {&Midjourney{}, "Midjourney"},
  261. {&TopUp{}, "TopUp"},
  262. {&QuotaData{}, "QuotaData"},
  263. {&Task{}, "Task"},
  264. {&Setup{}, "Setup"},
  265. {&UsageStatistics{}, "UsageStatistics"},
  266. {&TokenUsageLog{}, "TokenUsageLog"},
  267. }
  268. // 动态计算migration数量,确保errChan缓冲区足够大
  269. errChan := make(chan error, len(migrations))
  270. for _, m := range migrations {
  271. wg.Add(1)
  272. go func(model interface{}, name string) {
  273. defer wg.Done()
  274. if err := DB.AutoMigrate(model); err != nil {
  275. errChan <- fmt.Errorf("failed to migrate %s: %v", name, err)
  276. }
  277. }(m.model, m.name)
  278. }
  279. // Wait for all migrations to complete
  280. wg.Wait()
  281. close(errChan)
  282. // Check for any errors
  283. for err := range errChan {
  284. if err != nil {
  285. return err
  286. }
  287. }
  288. common.SysLog("database migrated")
  289. return nil
  290. }
  291. func migrateLOGDB() error {
  292. var err error
  293. if err = LOG_DB.AutoMigrate(&Log{}); err != nil {
  294. return err
  295. }
  296. return nil
  297. }
  298. func closeDB(db *gorm.DB) error {
  299. sqlDB, err := db.DB()
  300. if err != nil {
  301. return err
  302. }
  303. err = sqlDB.Close()
  304. return err
  305. }
  306. func CloseDB() error {
  307. if LOG_DB != DB {
  308. err := closeDB(LOG_DB)
  309. if err != nil {
  310. return err
  311. }
  312. }
  313. return closeDB(DB)
  314. }
  315. var (
  316. lastPingTime time.Time
  317. pingMutex sync.Mutex
  318. )
  319. func PingDB() error {
  320. pingMutex.Lock()
  321. defer pingMutex.Unlock()
  322. if time.Since(lastPingTime) < time.Second*10 {
  323. return nil
  324. }
  325. sqlDB, err := DB.DB()
  326. if err != nil {
  327. log.Printf("Error getting sql.DB from GORM: %v", err)
  328. return err
  329. }
  330. err = sqlDB.Ping()
  331. if err != nil {
  332. log.Printf("Error pinging DB: %v", err)
  333. return err
  334. }
  335. lastPingTime = time.Now()
  336. common.SysLog("Database pinged successfully")
  337. return nil
  338. }