main.go 8.1 KB

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