migrateDataStore_windows.go 8.6 KB

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