migrateDataStore.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // TODO: Windows only build flag + runtime.GOOS check in datastore.go?
  2. /*
  3. * Copyright (c) 2015, Psiphon Inc.
  4. * All rights reserved.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package psiphon
  21. import (
  22. "database/sql"
  23. "encoding/json"
  24. "fmt"
  25. "os"
  26. "path/filepath"
  27. _ "github.com/Psiphon-Inc/go-sqlite3"
  28. )
  29. var legacyDb *sql.DB
  30. var migratableServerEntries []*ServerEntry
  31. func prepareMigrationEntries(config *Config) ([]*ServerEntry, error) {
  32. // If DATA_STORE_FILENAME does not exist on disk
  33. if _, err := os.Stat(filepath.Join(config.DataStoreDirectory, DATA_STORE_FILENAME)); os.IsNotExist(err) {
  34. // If LEGACY_DATA_STORE_FILENAME exists on disk
  35. if _, err := os.Stat(filepath.Join(config.DataStoreDirectory, LEGACY_DATA_STORE_FILENAME)); err == nil {
  36. legacyDb, err = sql.Open("sqlite3", fmt.Sprintf("file:%s?cache=private&mode=rwc", filepath.Join(config.DataStoreDirectory, LEGACY_DATA_STORE_FILENAME)))
  37. if err != nil {
  38. return migratableServerEntries, err
  39. }
  40. initialization := "pragma journal_mode=WAL;\n"
  41. _, err = legacyDb.Exec(initialization)
  42. if err != nil {
  43. return migratableServerEntries, err
  44. }
  45. iterator, err := newlegacyServerEntryIterator(config)
  46. if err != nil {
  47. return migratableServerEntries, err
  48. }
  49. defer iterator.Close()
  50. for {
  51. serverEntry, err := iterator.Next()
  52. if err != nil {
  53. err = fmt.Errorf("failed to iterate legacy server entries: %s", err)
  54. break
  55. }
  56. if serverEntry == nil {
  57. break
  58. }
  59. migratableServerEntries = append(migratableServerEntries, serverEntry)
  60. }
  61. NoticeInfo("%d server entries prepared for data store migration", len(migratableServerEntries))
  62. }
  63. }
  64. return migratableServerEntries, nil
  65. }
  66. func migrateEntries(serverEntries []*ServerEntry, legacyDataStoreFilename string) error {
  67. checkInitDataStore()
  68. err := StoreServerEntries(serverEntries, false)
  69. if err != nil {
  70. return err
  71. }
  72. NoticeInfo("%d server entries successfully migrated to new data store", len(serverEntries))
  73. err = os.Remove(legacyDataStoreFilename)
  74. if err != nil {
  75. NoticeInfo("failed to delete legacy data store file '%s': %s", legacyDataStoreFilename, err)
  76. }
  77. return nil
  78. }
  79. // This code is copied from the dataStore.go code used to operate the legacy
  80. // SQLite datastore. The word "legacy" was added to all of the method names to avoid
  81. // namespace conflicts with the methods used to operate the BoltDB datastore
  82. // legacyServerEntryIterator is used to iterate over
  83. // stored server entries in rank order.
  84. type legacyServerEntryIterator struct {
  85. region string
  86. protocol string
  87. shuffleHeadLength int
  88. transaction *sql.Tx
  89. cursor *sql.Rows
  90. }
  91. // newLegacyServerEntryIterator creates a new legacyServerEntryIterator
  92. func newlegacyServerEntryIterator(config *Config) (iterator *legacyServerEntryIterator, err error) {
  93. iterator = &legacyServerEntryIterator{
  94. region: config.EgressRegion,
  95. protocol: config.TunnelProtocol,
  96. shuffleHeadLength: config.TunnelPoolSize,
  97. }
  98. err = iterator.Reset()
  99. if err != nil {
  100. return nil, err
  101. }
  102. return iterator, nil
  103. }
  104. // Close cleans up resources associated with a legacyServerEntryIterator.
  105. func (iterator *legacyServerEntryIterator) Close() {
  106. if iterator.cursor != nil {
  107. iterator.cursor.Close()
  108. }
  109. iterator.cursor = nil
  110. if iterator.transaction != nil {
  111. iterator.transaction.Rollback()
  112. }
  113. iterator.transaction = nil
  114. }
  115. // Next returns the next server entry, by rank, for a legacyServerEntryIterator.
  116. // Returns nil with no error when there is no next item.
  117. func (iterator *legacyServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  118. defer func() {
  119. if err != nil {
  120. iterator.Close()
  121. }
  122. }()
  123. if !iterator.cursor.Next() {
  124. err = iterator.cursor.Err()
  125. if err != nil {
  126. return nil, ContextError(err)
  127. }
  128. // There is no next item
  129. return nil, nil
  130. }
  131. var data []byte
  132. err = iterator.cursor.Scan(&data)
  133. if err != nil {
  134. return nil, ContextError(err)
  135. }
  136. serverEntry = new(ServerEntry)
  137. err = json.Unmarshal(data, serverEntry)
  138. if err != nil {
  139. return nil, ContextError(err)
  140. }
  141. return MakeCompatibleServerEntry(serverEntry), nil
  142. }
  143. // Reset a NewlegacyServerEntryIterator to the start of its cycle. The next
  144. // call to Next will return the first server entry.
  145. func (iterator *legacyServerEntryIterator) Reset() error {
  146. iterator.Close()
  147. count := countLegacyServerEntries(iterator.region, iterator.protocol)
  148. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  149. transaction, err := legacyDb.Begin()
  150. if err != nil {
  151. return ContextError(err)
  152. }
  153. var cursor *sql.Rows
  154. // This query implements the Psiphon server candidate selection
  155. // algorithm: the first TunnelPoolSize server candidates are in rank
  156. // (priority) order, to favor previously successful servers; then the
  157. // remaining long tail is shuffled to raise up less recent candidates.
  158. whereClause, whereParams := makeServerEntryWhereClause(
  159. iterator.region, iterator.protocol, nil)
  160. headLength := iterator.shuffleHeadLength
  161. queryFormat := `
  162. select data from serverEntry %s
  163. order by case
  164. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  165. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  166. end desc;`
  167. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  168. params := make([]interface{}, 0)
  169. params = append(params, whereParams...)
  170. params = append(params, whereParams...)
  171. params = append(params, headLength)
  172. params = append(params, whereParams...)
  173. params = append(params, headLength)
  174. cursor, err = transaction.Query(query, params...)
  175. if err != nil {
  176. transaction.Rollback()
  177. return ContextError(err)
  178. }
  179. iterator.transaction = transaction
  180. iterator.cursor = cursor
  181. return nil
  182. }
  183. func makeServerEntryWhereClause(
  184. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  185. whereClause = ""
  186. whereParams = make([]interface{}, 0)
  187. if region != "" {
  188. whereClause += " where region = ?"
  189. whereParams = append(whereParams, region)
  190. }
  191. if protocol != "" {
  192. if len(whereClause) > 0 {
  193. whereClause += " and"
  194. } else {
  195. whereClause += " where"
  196. }
  197. whereClause +=
  198. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  199. whereParams = append(whereParams, protocol)
  200. }
  201. if len(excludeIds) > 0 {
  202. if len(whereClause) > 0 {
  203. whereClause += " and"
  204. } else {
  205. whereClause += " where"
  206. }
  207. whereClause += " id in ("
  208. for index, id := range excludeIds {
  209. if index > 0 {
  210. whereClause += ", "
  211. }
  212. whereClause += "?"
  213. whereParams = append(whereParams, id)
  214. }
  215. whereClause += ")"
  216. }
  217. return whereClause, whereParams
  218. }
  219. // countLegacyServerEntries returns a count of stored servers for the specified region and protocol.
  220. func countLegacyServerEntries(region, protocol string) int {
  221. var count int
  222. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  223. query := "select count(*) from serverEntry" + whereClause
  224. err := legacyDb.QueryRow(query, whereParams...).Scan(&count)
  225. if err != nil {
  226. NoticeAlert("countLegacyServerEntries failed: %s", err)
  227. return 0
  228. }
  229. if region == "" {
  230. region = "(any)"
  231. }
  232. if protocol == "" {
  233. protocol = "(any)"
  234. }
  235. NoticeInfo("servers for region %s and protocol %s: %d",
  236. region, protocol, count)
  237. return count
  238. }