main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. // dropIndexIfExists drops a MySQL index only if it exists to avoid noisy 1091 errors
  60. func dropIndexIfExists(tableName string, indexName string) {
  61. if !common.UsingMySQL {
  62. return
  63. }
  64. var count int64
  65. // Check index existence via information_schema
  66. err := DB.Raw(
  67. "SELECT COUNT(1) FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?",
  68. tableName, indexName,
  69. ).Scan(&count).Error
  70. if err == nil && count > 0 {
  71. _ = DB.Exec("ALTER TABLE " + tableName + " DROP INDEX " + indexName + ";").Error
  72. }
  73. }
  74. func createRootAccountIfNeed() error {
  75. var user User
  76. //if user.Status != common.UserStatusEnabled {
  77. if err := DB.First(&user).Error; err != nil {
  78. common.SysLog("no user exists, create a root user for you: username is root, password is 123456")
  79. hashedPassword, err := common.Password2Hash("123456")
  80. if err != nil {
  81. return err
  82. }
  83. rootUser := User{
  84. Username: "root",
  85. Password: hashedPassword,
  86. Role: common.RoleRootUser,
  87. Status: common.UserStatusEnabled,
  88. DisplayName: "Root User",
  89. AccessToken: nil,
  90. Quota: 100000000,
  91. }
  92. DB.Create(&rootUser)
  93. }
  94. return nil
  95. }
  96. func CheckSetup() {
  97. setup := GetSetup()
  98. if setup == nil {
  99. // No setup record exists, check if we have a root user
  100. if RootUserExists() {
  101. common.SysLog("system is not initialized, but root user exists")
  102. // Create setup record
  103. newSetup := Setup{
  104. Version: common.Version,
  105. InitializedAt: time.Now().Unix(),
  106. }
  107. err := DB.Create(&newSetup).Error
  108. if err != nil {
  109. common.SysLog("failed to create setup record: " + err.Error())
  110. }
  111. constant.Setup = true
  112. } else {
  113. common.SysLog("system is not initialized and no root user exists")
  114. constant.Setup = false
  115. }
  116. } else {
  117. // Setup record exists, system is initialized
  118. common.SysLog("system is already initialized at: " + time.Unix(setup.InitializedAt, 0).String())
  119. constant.Setup = true
  120. }
  121. }
  122. func chooseDB(envName string, isLog bool) (*gorm.DB, error) {
  123. defer func() {
  124. initCol()
  125. }()
  126. dsn := os.Getenv(envName)
  127. if dsn != "" {
  128. if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
  129. // Use PostgreSQL
  130. common.SysLog("using PostgreSQL as database")
  131. if !isLog {
  132. common.UsingPostgreSQL = true
  133. } else {
  134. common.LogSqlType = common.DatabaseTypePostgreSQL
  135. }
  136. return gorm.Open(postgres.New(postgres.Config{
  137. DSN: dsn,
  138. PreferSimpleProtocol: true, // disables implicit prepared statement usage
  139. }), &gorm.Config{
  140. PrepareStmt: true, // precompile SQL
  141. })
  142. }
  143. if strings.HasPrefix(dsn, "local") {
  144. common.SysLog("SQL_DSN not set, using SQLite as database")
  145. if !isLog {
  146. common.UsingSQLite = true
  147. } else {
  148. common.LogSqlType = common.DatabaseTypeSQLite
  149. }
  150. return gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
  151. PrepareStmt: true, // precompile SQL
  152. })
  153. }
  154. // Use MySQL
  155. common.SysLog("using MySQL as database")
  156. // check parseTime
  157. if !strings.Contains(dsn, "parseTime") {
  158. if strings.Contains(dsn, "?") {
  159. dsn += "&parseTime=true"
  160. } else {
  161. dsn += "?parseTime=true"
  162. }
  163. }
  164. if !isLog {
  165. common.UsingMySQL = true
  166. } else {
  167. common.LogSqlType = common.DatabaseTypeMySQL
  168. }
  169. return gorm.Open(mysql.Open(dsn), &gorm.Config{
  170. PrepareStmt: true, // precompile SQL
  171. })
  172. }
  173. // Use SQLite
  174. common.SysLog("SQL_DSN not set, using SQLite as database")
  175. common.UsingSQLite = true
  176. return gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
  177. PrepareStmt: true, // precompile SQL
  178. })
  179. }
  180. func InitDB() (err error) {
  181. db, err := chooseDB("SQL_DSN", false)
  182. if err == nil {
  183. if common.DebugEnabled {
  184. db = db.Debug()
  185. }
  186. DB = db
  187. // MySQL charset/collation startup check: ensure Chinese-capable charset
  188. if common.UsingMySQL {
  189. if err := checkMySQLChineseSupport(DB); err != nil {
  190. panic(err)
  191. }
  192. }
  193. sqlDB, err := DB.DB()
  194. if err != nil {
  195. return err
  196. }
  197. sqlDB.SetMaxIdleConns(common.GetEnvOrDefault("SQL_MAX_IDLE_CONNS", 100))
  198. sqlDB.SetMaxOpenConns(common.GetEnvOrDefault("SQL_MAX_OPEN_CONNS", 1000))
  199. sqlDB.SetConnMaxLifetime(time.Second * time.Duration(common.GetEnvOrDefault("SQL_MAX_LIFETIME", 60)))
  200. if !common.IsMasterNode {
  201. return nil
  202. }
  203. if common.UsingMySQL {
  204. //_, _ = sqlDB.Exec("ALTER TABLE channels MODIFY model_mapping TEXT;") // TODO: delete this line when most users have upgraded
  205. }
  206. common.SysLog("database migration started")
  207. err = migrateDB()
  208. return err
  209. } else {
  210. common.FatalLog(err)
  211. }
  212. return err
  213. }
  214. func InitLogDB() (err error) {
  215. if os.Getenv("LOG_SQL_DSN") == "" {
  216. LOG_DB = DB
  217. return
  218. }
  219. db, err := chooseDB("LOG_SQL_DSN", true)
  220. if err == nil {
  221. if common.DebugEnabled {
  222. db = db.Debug()
  223. }
  224. LOG_DB = db
  225. // If log DB is MySQL, also ensure Chinese-capable charset
  226. if common.LogSqlType == common.DatabaseTypeMySQL {
  227. if err := checkMySQLChineseSupport(LOG_DB); err != nil {
  228. panic(err)
  229. }
  230. }
  231. sqlDB, err := LOG_DB.DB()
  232. if err != nil {
  233. return err
  234. }
  235. sqlDB.SetMaxIdleConns(common.GetEnvOrDefault("SQL_MAX_IDLE_CONNS", 100))
  236. sqlDB.SetMaxOpenConns(common.GetEnvOrDefault("SQL_MAX_OPEN_CONNS", 1000))
  237. sqlDB.SetConnMaxLifetime(time.Second * time.Duration(common.GetEnvOrDefault("SQL_MAX_LIFETIME", 60)))
  238. if !common.IsMasterNode {
  239. return nil
  240. }
  241. common.SysLog("database migration started")
  242. err = migrateLOGDB()
  243. return err
  244. } else {
  245. common.FatalLog(err)
  246. }
  247. return err
  248. }
  249. func migrateDB() error {
  250. // 修复旧版本留下的唯一索引,允许软删除后重新插入同名记录
  251. // 删除单列唯一索引(列级 UNIQUE)及早期命名方式,防止与新复合唯一索引 (model_name, deleted_at) 冲突
  252. dropIndexIfExists("models", "uk_model_name") // 新版复合索引名称(若已存在)
  253. dropIndexIfExists("models", "model_name") // 旧版列级唯一索引名称
  254. dropIndexIfExists("vendors", "uk_vendor_name") // 新版复合索引名称(若已存在)
  255. dropIndexIfExists("vendors", "name") // 旧版列级唯一索引名称
  256. //if !common.UsingPostgreSQL {
  257. // return migrateDBFast()
  258. //}
  259. err := DB.AutoMigrate(
  260. &Channel{},
  261. &Token{},
  262. &User{},
  263. &Option{},
  264. &Redemption{},
  265. &Ability{},
  266. &Log{},
  267. &Midjourney{},
  268. &TopUp{},
  269. &QuotaData{},
  270. &Task{},
  271. &Model{},
  272. &Vendor{},
  273. &PrefillGroup{},
  274. &Setup{},
  275. &TwoFA{},
  276. &TwoFABackupCode{},
  277. )
  278. if err != nil {
  279. return err
  280. }
  281. return nil
  282. }
  283. func migrateDBFast() error {
  284. // 修复旧版本留下的唯一索引,允许软删除后重新插入同名记录
  285. // 删除单列唯一索引(列级 UNIQUE)及早期命名方式,防止与新复合唯一索引冲突
  286. dropIndexIfExists("models", "uk_model_name")
  287. dropIndexIfExists("models", "model_name")
  288. dropIndexIfExists("vendors", "uk_vendor_name")
  289. dropIndexIfExists("vendors", "name")
  290. var wg sync.WaitGroup
  291. migrations := []struct {
  292. model interface{}
  293. name string
  294. }{
  295. {&Channel{}, "Channel"},
  296. {&Token{}, "Token"},
  297. {&User{}, "User"},
  298. {&Option{}, "Option"},
  299. {&Redemption{}, "Redemption"},
  300. {&Ability{}, "Ability"},
  301. {&Log{}, "Log"},
  302. {&Midjourney{}, "Midjourney"},
  303. {&TopUp{}, "TopUp"},
  304. {&QuotaData{}, "QuotaData"},
  305. {&Task{}, "Task"},
  306. {&Model{}, "Model"},
  307. {&Vendor{}, "Vendor"},
  308. {&PrefillGroup{}, "PrefillGroup"},
  309. {&Setup{}, "Setup"},
  310. {&TwoFA{}, "TwoFA"},
  311. {&TwoFABackupCode{}, "TwoFABackupCode"},
  312. }
  313. // 动态计算migration数量,确保errChan缓冲区足够大
  314. errChan := make(chan error, len(migrations))
  315. for _, m := range migrations {
  316. wg.Add(1)
  317. go func(model interface{}, name string) {
  318. defer wg.Done()
  319. if err := DB.AutoMigrate(model); err != nil {
  320. errChan <- fmt.Errorf("failed to migrate %s: %v", name, err)
  321. }
  322. }(m.model, m.name)
  323. }
  324. // Wait for all migrations to complete
  325. wg.Wait()
  326. close(errChan)
  327. // Check for any errors
  328. for err := range errChan {
  329. if err != nil {
  330. return err
  331. }
  332. }
  333. common.SysLog("database migrated")
  334. return nil
  335. }
  336. func migrateLOGDB() error {
  337. var err error
  338. if err = LOG_DB.AutoMigrate(&Log{}); err != nil {
  339. return err
  340. }
  341. return nil
  342. }
  343. func closeDB(db *gorm.DB) error {
  344. sqlDB, err := db.DB()
  345. if err != nil {
  346. return err
  347. }
  348. err = sqlDB.Close()
  349. return err
  350. }
  351. func CloseDB() error {
  352. if LOG_DB != DB {
  353. err := closeDB(LOG_DB)
  354. if err != nil {
  355. return err
  356. }
  357. }
  358. return closeDB(DB)
  359. }
  360. // checkMySQLChineseSupport ensures the MySQL connection and current schema
  361. // default charset/collation can store Chinese characters. It allows common
  362. // Chinese-capable charsets (utf8mb4, utf8, gbk, big5, gb18030) and panics otherwise.
  363. func checkMySQLChineseSupport(db *gorm.DB) error {
  364. // 仅检测:当前库默认字符集/排序规则 + 各表的排序规则(隐含字符集)
  365. // Read current schema defaults
  366. var schemaCharset, schemaCollation string
  367. err := db.Raw("SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = DATABASE()").Row().Scan(&schemaCharset, &schemaCollation)
  368. if err != nil {
  369. return fmt.Errorf("读取当前库默认字符集/排序规则失败 / Failed to read schema default charset/collation: %v", err)
  370. }
  371. toLower := func(s string) string { return strings.ToLower(s) }
  372. // Allowed charsets that can store Chinese text
  373. allowedCharsets := map[string]string{
  374. "utf8mb4": "utf8mb4_",
  375. "utf8": "utf8_",
  376. "gbk": "gbk_",
  377. "big5": "big5_",
  378. "gb18030": "gb18030_",
  379. }
  380. isChineseCapable := func(cs, cl string) bool {
  381. csLower := toLower(cs)
  382. clLower := toLower(cl)
  383. if prefix, ok := allowedCharsets[csLower]; ok {
  384. if clLower == "" {
  385. return true
  386. }
  387. return strings.HasPrefix(clLower, prefix)
  388. }
  389. // 如果仅提供了排序规则,尝试按排序规则前缀判断
  390. for _, prefix := range allowedCharsets {
  391. if strings.HasPrefix(clLower, prefix) {
  392. return true
  393. }
  394. }
  395. return false
  396. }
  397. // 1) 当前库默认值必须支持中文
  398. if !isChineseCapable(schemaCharset, schemaCollation) {
  399. return fmt.Errorf("当前库默认字符集/排序规则不支持中文:schema(%s/%s)。请将库设置为 utf8mb4/utf8/gbk/big5/gb18030 / Schema default charset/collation is not Chinese-capable: schema(%s/%s). Please set to utf8mb4/utf8/gbk/big5/gb18030",
  400. schemaCharset, schemaCollation, schemaCharset, schemaCollation)
  401. }
  402. // 2) 所有物理表的排序规则(隐含字符集)必须支持中文
  403. type tableInfo struct {
  404. Name string
  405. Collation *string
  406. }
  407. var tables []tableInfo
  408. if err := db.Raw("SELECT TABLE_NAME, TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'").Scan(&tables).Error; err != nil {
  409. return fmt.Errorf("读取表排序规则失败 / Failed to read table collations: %v", err)
  410. }
  411. var badTables []string
  412. for _, t := range tables {
  413. // NULL 或空表示继承库默认设置,已在上面校验库默认,视为通过
  414. if t.Collation == nil || *t.Collation == "" {
  415. continue
  416. }
  417. cl := *t.Collation
  418. // 仅凭排序规则判断是否中文可用
  419. ok := false
  420. lower := strings.ToLower(cl)
  421. for _, prefix := range allowedCharsets {
  422. if strings.HasPrefix(lower, prefix) {
  423. ok = true
  424. break
  425. }
  426. }
  427. if !ok {
  428. badTables = append(badTables, fmt.Sprintf("%s(%s)", t.Name, cl))
  429. }
  430. }
  431. if len(badTables) > 0 {
  432. // 限制输出数量以避免日志过长
  433. maxShow := 20
  434. shown := badTables
  435. if len(shown) > maxShow {
  436. shown = shown[:maxShow]
  437. }
  438. return fmt.Errorf(
  439. "存在不支持中文的表,请修复其排序规则/字符集。示例(最多展示 %d 项):%v / Found tables not Chinese-capable. Please fix their collation/charset. Examples (showing up to %d): %v",
  440. maxShow, shown, maxShow, shown,
  441. )
  442. }
  443. return nil
  444. }
  445. var (
  446. lastPingTime time.Time
  447. pingMutex sync.Mutex
  448. )
  449. func PingDB() error {
  450. pingMutex.Lock()
  451. defer pingMutex.Unlock()
  452. if time.Since(lastPingTime) < time.Second*10 {
  453. return nil
  454. }
  455. sqlDB, err := DB.DB()
  456. if err != nil {
  457. log.Printf("Error getting sql.DB from GORM: %v", err)
  458. return err
  459. }
  460. err = sqlDB.Ping()
  461. if err != nil {
  462. log.Printf("Error pinging DB: %v", err)
  463. return err
  464. }
  465. lastPingTime = time.Now()
  466. common.SysLog("Database pinged successfully")
  467. return nil
  468. }