migrateDataStore_windows.go 8.6 KB

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