migrateDataStore.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. defer legacyDb.Close()
  38. if err != nil {
  39. return migratableServerEntries, err
  40. }
  41. initialization := "pragma journal_mode=WAL;\n"
  42. _, err = legacyDb.Exec(initialization)
  43. if err != nil {
  44. return migratableServerEntries, err
  45. }
  46. iterator, err := newlegacyServerEntryIterator(config)
  47. if err != nil {
  48. return migratableServerEntries, err
  49. }
  50. defer iterator.Close()
  51. for {
  52. serverEntry, err := iterator.Next()
  53. if err != nil {
  54. err = fmt.Errorf("failed to iterate legacy server entries: %s", err)
  55. break
  56. }
  57. if serverEntry == nil {
  58. break
  59. }
  60. migratableServerEntries = append(migratableServerEntries, serverEntry)
  61. }
  62. NoticeInfo("%d server entries prepared for data store migration", len(migratableServerEntries))
  63. }
  64. }
  65. return migratableServerEntries, nil
  66. }
  67. // migrateEntries calls the BoltDB data store method to shuffle
  68. // and store an array of server entries (StoreServerEntries)
  69. // Failing to migrate entries, or delete the legacy file is never fatal
  70. func migrateEntries(serverEntries []*ServerEntry, legacyDataStoreFilename string) {
  71. checkInitDataStore()
  72. err := StoreServerEntries(serverEntries, false)
  73. if err != nil {
  74. NoticeAlert("failed to store migrated server entries: %s", err)
  75. } else {
  76. // Retain server affinity from old datastore by taking the first
  77. // array element (previous top ranked server) and promoting it
  78. // to the top rank before the server selection process begins
  79. err = PromoteServerEntry(serverEntries[0].IpAddress)
  80. if err != nil {
  81. NoticeAlert("failed to promote server entry: %s", err)
  82. }
  83. NoticeAlert("%d server entries successfully migrated to new data store", len(serverEntries))
  84. }
  85. err = os.Remove(legacyDataStoreFilename)
  86. if err != nil {
  87. NoticeAlert("failed to delete legacy data store file '%s': %s", legacyDataStoreFilename, err)
  88. }
  89. return
  90. }
  91. // This code is copied from the dataStore.go code used to operate the legacy
  92. // SQLite datastore. The word "legacy" was added to all of the method names to avoid
  93. // namespace conflicts with the methods used to operate the BoltDB datastore
  94. // legacyServerEntryIterator is used to iterate over
  95. // stored server entries in rank order.
  96. type legacyServerEntryIterator struct {
  97. region string
  98. protocol string
  99. shuffleHeadLength int
  100. transaction *sql.Tx
  101. cursor *sql.Rows
  102. }
  103. // newLegacyServerEntryIterator creates a new legacyServerEntryIterator
  104. func newlegacyServerEntryIterator(config *Config) (iterator *legacyServerEntryIterator, err error) {
  105. iterator = &legacyServerEntryIterator{
  106. region: config.EgressRegion,
  107. protocol: config.TunnelProtocol,
  108. shuffleHeadLength: config.TunnelPoolSize,
  109. }
  110. err = iterator.Reset()
  111. if err != nil {
  112. return nil, err
  113. }
  114. return iterator, nil
  115. }
  116. // Close cleans up resources associated with a legacyServerEntryIterator.
  117. func (iterator *legacyServerEntryIterator) Close() {
  118. if iterator.cursor != nil {
  119. iterator.cursor.Close()
  120. }
  121. iterator.cursor = nil
  122. if iterator.transaction != nil {
  123. iterator.transaction.Rollback()
  124. }
  125. iterator.transaction = nil
  126. }
  127. // Next returns the next server entry, by rank, for a legacyServerEntryIterator.
  128. // Returns nil with no error when there is no next item.
  129. func (iterator *legacyServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  130. defer func() {
  131. if err != nil {
  132. iterator.Close()
  133. }
  134. }()
  135. if !iterator.cursor.Next() {
  136. err = iterator.cursor.Err()
  137. if err != nil {
  138. return nil, ContextError(err)
  139. }
  140. // There is no next item
  141. return nil, nil
  142. }
  143. var data []byte
  144. err = iterator.cursor.Scan(&data)
  145. if err != nil {
  146. return nil, ContextError(err)
  147. }
  148. serverEntry = new(ServerEntry)
  149. err = json.Unmarshal(data, serverEntry)
  150. if err != nil {
  151. return nil, ContextError(err)
  152. }
  153. return MakeCompatibleServerEntry(serverEntry), nil
  154. }
  155. // Reset a NewlegacyServerEntryIterator to the start of its cycle. The next
  156. // call to Next will return the first server entry.
  157. func (iterator *legacyServerEntryIterator) Reset() error {
  158. iterator.Close()
  159. count := countLegacyServerEntries(iterator.region, iterator.protocol)
  160. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  161. transaction, err := legacyDb.Begin()
  162. if err != nil {
  163. return ContextError(err)
  164. }
  165. var cursor *sql.Rows
  166. // This query implements the Psiphon server candidate selection
  167. // algorithm: the first TunnelPoolSize server candidates are in rank
  168. // (priority) order, to favor previously successful servers; then the
  169. // remaining long tail is shuffled to raise up less recent candidates.
  170. whereClause, whereParams := makeServerEntryWhereClause(
  171. iterator.region, iterator.protocol, nil)
  172. headLength := iterator.shuffleHeadLength
  173. queryFormat := `
  174. select data from serverEntry %s
  175. order by case
  176. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  177. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  178. end desc;`
  179. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  180. params := make([]interface{}, 0)
  181. params = append(params, whereParams...)
  182. params = append(params, whereParams...)
  183. params = append(params, headLength)
  184. params = append(params, whereParams...)
  185. params = append(params, headLength)
  186. cursor, err = transaction.Query(query, params...)
  187. if err != nil {
  188. transaction.Rollback()
  189. return ContextError(err)
  190. }
  191. iterator.transaction = transaction
  192. iterator.cursor = cursor
  193. return nil
  194. }
  195. func makeServerEntryWhereClause(
  196. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  197. whereClause = ""
  198. whereParams = make([]interface{}, 0)
  199. if region != "" {
  200. whereClause += " where region = ?"
  201. whereParams = append(whereParams, region)
  202. }
  203. if protocol != "" {
  204. if len(whereClause) > 0 {
  205. whereClause += " and"
  206. } else {
  207. whereClause += " where"
  208. }
  209. whereClause +=
  210. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  211. whereParams = append(whereParams, protocol)
  212. }
  213. if len(excludeIds) > 0 {
  214. if len(whereClause) > 0 {
  215. whereClause += " and"
  216. } else {
  217. whereClause += " where"
  218. }
  219. whereClause += " id in ("
  220. for index, id := range excludeIds {
  221. if index > 0 {
  222. whereClause += ", "
  223. }
  224. whereClause += "?"
  225. whereParams = append(whereParams, id)
  226. }
  227. whereClause += ")"
  228. }
  229. return whereClause, whereParams
  230. }
  231. // countLegacyServerEntries returns a count of stored servers for the specified region and protocol.
  232. func countLegacyServerEntries(region, protocol string) int {
  233. var count int
  234. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  235. query := "select count(*) from serverEntry" + whereClause
  236. err := legacyDb.QueryRow(query, whereParams...).Scan(&count)
  237. if err != nil {
  238. NoticeAlert("countLegacyServerEntries failed: %s", err)
  239. return 0
  240. }
  241. if region == "" {
  242. region = "(any)"
  243. }
  244. if protocol == "" {
  245. protocol = "(any)"
  246. }
  247. NoticeInfo("servers for region %s and protocol %s: %d",
  248. region, protocol, count)
  249. return count
  250. }