main.go 13 KB

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