You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

database.go 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
  3. // released under the MIT license
  4. package irc
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "log"
  9. "os"
  10. "strings"
  11. "time"
  12. "github.com/oragono/oragono/irc/modes"
  13. "github.com/oragono/oragono/irc/utils"
  14. "github.com/tidwall/buntdb"
  15. )
  16. const (
  17. // 'version' of the database schema
  18. keySchemaVersion = "db.version"
  19. // latest schema of the db
  20. latestDbSchema = "3"
  21. )
  22. type SchemaChanger func(*Config, *buntdb.Tx) error
  23. type SchemaChange struct {
  24. InitialVersion string // the change will take this version
  25. TargetVersion string // and transform it into this version
  26. Changer SchemaChanger
  27. }
  28. // maps an initial version to a schema change capable of upgrading it
  29. var schemaChanges map[string]SchemaChange
  30. type incompatibleSchemaError struct {
  31. currentVersion string
  32. requiredVersion string
  33. }
  34. func IncompatibleSchemaError(currentVersion string) (result *incompatibleSchemaError) {
  35. return &incompatibleSchemaError{
  36. currentVersion: currentVersion,
  37. requiredVersion: latestDbSchema,
  38. }
  39. }
  40. func (err *incompatibleSchemaError) Error() string {
  41. return fmt.Sprintf("Database requires update. Expected schema v%s, got v%s", err.requiredVersion, err.currentVersion)
  42. }
  43. // InitDB creates the database.
  44. func InitDB(path string) {
  45. // prepare kvstore db
  46. //TODO(dan): fail if already exists instead? don't want to overwrite good data
  47. os.Remove(path)
  48. store, err := buntdb.Open(path)
  49. if err != nil {
  50. log.Fatal(fmt.Sprintf("Failed to open datastore: %s", err.Error()))
  51. }
  52. defer store.Close()
  53. err = store.Update(func(tx *buntdb.Tx) error {
  54. // set schema version
  55. tx.Set(keySchemaVersion, latestDbSchema, nil)
  56. return nil
  57. })
  58. if err != nil {
  59. log.Fatal("Could not save datastore:", err.Error())
  60. }
  61. }
  62. // OpenDatabase returns an existing database, performing a schema version check.
  63. func OpenDatabase(config *Config) (*buntdb.DB, error) {
  64. return openDatabaseInternal(config, config.Datastore.AutoUpgrade)
  65. }
  66. // open the database, giving it at most one chance to auto-upgrade the schema
  67. func openDatabaseInternal(config *Config, allowAutoupgrade bool) (db *buntdb.DB, err error) {
  68. db, err = buntdb.Open(config.Datastore.Path)
  69. if err != nil {
  70. return
  71. }
  72. defer func() {
  73. if err != nil && db != nil {
  74. db.Close()
  75. db = nil
  76. }
  77. }()
  78. // read the current version string
  79. var version string
  80. err = db.View(func(tx *buntdb.Tx) error {
  81. version, err = tx.Get(keySchemaVersion)
  82. return err
  83. })
  84. if err != nil {
  85. return
  86. }
  87. if version == latestDbSchema {
  88. // success
  89. return
  90. }
  91. // XXX quiesce the DB so we can be sure it's safe to make a backup copy
  92. db.Close()
  93. db = nil
  94. if allowAutoupgrade {
  95. err = performAutoUpgrade(version, config)
  96. if err != nil {
  97. return
  98. }
  99. // successful autoupgrade, let's try this again:
  100. return openDatabaseInternal(config, false)
  101. } else {
  102. err = IncompatibleSchemaError(version)
  103. return
  104. }
  105. }
  106. func performAutoUpgrade(currentVersion string, config *Config) (err error) {
  107. path := config.Datastore.Path
  108. log.Printf("attempting to auto-upgrade schema from version %s to %s\n", currentVersion, latestDbSchema)
  109. timestamp := time.Now().UTC().Format("2006-01-02-15:04:05.000Z")
  110. backupPath := fmt.Sprintf("%s.v%s.%s.bak", path, currentVersion, timestamp)
  111. log.Printf("making a backup of current database at %s\n", backupPath)
  112. err = utils.CopyFile(path, backupPath)
  113. if err != nil {
  114. return err
  115. }
  116. err = UpgradeDB(config)
  117. if err != nil {
  118. // database upgrade is a single transaction, so we don't need to restore the backup;
  119. // we can just delete it
  120. os.Remove(backupPath)
  121. }
  122. return err
  123. }
  124. // UpgradeDB upgrades the datastore to the latest schema.
  125. func UpgradeDB(config *Config) (err error) {
  126. store, err := buntdb.Open(config.Datastore.Path)
  127. if err != nil {
  128. return err
  129. }
  130. defer store.Close()
  131. var version string
  132. err = store.Update(func(tx *buntdb.Tx) error {
  133. for {
  134. version, _ = tx.Get(keySchemaVersion)
  135. change, schemaNeedsChange := schemaChanges[version]
  136. if !schemaNeedsChange {
  137. if version == latestDbSchema {
  138. // success!
  139. break
  140. }
  141. // unable to upgrade to the desired version, roll back
  142. return IncompatibleSchemaError(version)
  143. }
  144. log.Println("attempting to update schema from version " + version)
  145. err := change.Changer(config, tx)
  146. if err != nil {
  147. return err
  148. }
  149. _, _, err = tx.Set(keySchemaVersion, change.TargetVersion, nil)
  150. if err != nil {
  151. return err
  152. }
  153. log.Println("successfully updated schema to version " + change.TargetVersion)
  154. }
  155. return nil
  156. })
  157. if err != nil {
  158. log.Println("database upgrade failed and was rolled back")
  159. }
  160. return err
  161. }
  162. func schemaChangeV1toV2(config *Config, tx *buntdb.Tx) error {
  163. // == version 1 -> 2 ==
  164. // account key changes and account.verified key bugfix.
  165. var keysToRemove []string
  166. newKeys := make(map[string]string)
  167. tx.AscendKeys("account *", func(key, value string) bool {
  168. keysToRemove = append(keysToRemove, key)
  169. splitkey := strings.Split(key, " ")
  170. // work around bug
  171. if splitkey[2] == "exists" {
  172. // manually create new verified key
  173. newVerifiedKey := fmt.Sprintf("%s.verified %s", splitkey[0], splitkey[1])
  174. newKeys[newVerifiedKey] = "1"
  175. } else if splitkey[1] == "%s" {
  176. return true
  177. }
  178. newKey := fmt.Sprintf("%s.%s %s", splitkey[0], splitkey[2], splitkey[1])
  179. newKeys[newKey] = value
  180. return true
  181. })
  182. for _, key := range keysToRemove {
  183. tx.Delete(key)
  184. }
  185. for key, value := range newKeys {
  186. tx.Set(key, value, nil)
  187. }
  188. return nil
  189. }
  190. // 1. channel founder names should be casefolded
  191. // 2. founder should be explicitly granted the ChannelFounder user mode
  192. // 3. explicitly initialize stored channel modes to the server default values
  193. func schemaChangeV2ToV3(config *Config, tx *buntdb.Tx) error {
  194. var channels []string
  195. prefix := "channel.exists "
  196. tx.AscendGreaterOrEqual("", prefix, func(key, value string) bool {
  197. if !strings.HasPrefix(key, prefix) {
  198. return false
  199. }
  200. chname := strings.TrimPrefix(key, prefix)
  201. channels = append(channels, chname)
  202. return true
  203. })
  204. // founder names should be casefolded
  205. // founder should be explicitly granted the ChannelFounder user mode
  206. for _, channel := range channels {
  207. founderKey := "channel.founder " + channel
  208. founder, _ := tx.Get(founderKey)
  209. if founder != "" {
  210. founder, err := CasefoldName(founder)
  211. if err == nil {
  212. tx.Set(founderKey, founder, nil)
  213. accountToUmode := map[string]modes.Mode{
  214. founder: modes.ChannelFounder,
  215. }
  216. atustr, _ := json.Marshal(accountToUmode)
  217. tx.Set("channel.accounttoumode "+channel, string(atustr), nil)
  218. }
  219. }
  220. }
  221. // explicitly store the channel modes
  222. defaultModes := ParseDefaultChannelModes(config.Channels.RawDefaultModes)
  223. modeStrings := make([]string, len(defaultModes))
  224. for i, mode := range defaultModes {
  225. modeStrings[i] = string(mode)
  226. }
  227. defaultModeString := strings.Join(modeStrings, "")
  228. for _, channel := range channels {
  229. tx.Set("channel.modes "+channel, defaultModeString, nil)
  230. }
  231. return nil
  232. }
  233. func init() {
  234. allChanges := []SchemaChange{
  235. {
  236. InitialVersion: "1",
  237. TargetVersion: "2",
  238. Changer: schemaChangeV1toV2,
  239. },
  240. {
  241. InitialVersion: "2",
  242. TargetVersion: "3",
  243. Changer: schemaChangeV2ToV3,
  244. },
  245. }
  246. // build the index
  247. schemaChanges = make(map[string]SchemaChange)
  248. for _, change := range allChanges {
  249. schemaChanges[change.InitialVersion] = change
  250. }
  251. }