dataStore.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c) 2014, 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. "errors"
  24. "fmt"
  25. sqlite3 "github.com/mattn/go-sqlite3"
  26. "log"
  27. "sync"
  28. "time"
  29. )
  30. type dataStore struct {
  31. init sync.Once
  32. db *sql.DB
  33. }
  34. var singleton dataStore
  35. // initDataStore initializes the singleton instance of dataStore. This
  36. // function uses a sync.Once and is safe for use by concurrent goroutines.
  37. // The underlying sql.DB connection pool is also safe.
  38. func initDataStore() {
  39. singleton.init.Do(func() {
  40. const schema = `
  41. create table if not exists serverEntry
  42. (id text not null primary key,
  43. rank integer not null unique,
  44. region text not null,
  45. data blob not null);
  46. create table if not exists keyValue
  47. (key text not null,
  48. value text not null);
  49. pragma journal_mode=WAL;
  50. `
  51. db, err := sql.Open(
  52. "sqlite3",
  53. fmt.Sprintf("file:%s?cache=private&mode=rwc", DATA_STORE_FILENAME))
  54. if err != nil {
  55. log.Fatal("initDataStore failed to open database: %s", err)
  56. }
  57. _, err = db.Exec(schema)
  58. if err != nil {
  59. log.Fatal("initDataStore failed to initialize schema: %s", err)
  60. }
  61. singleton.db = db
  62. })
  63. }
  64. func canRetry(err error) bool {
  65. sqlError, ok := err.(sqlite3.Error)
  66. return ok && (sqlError.Code == sqlite3.ErrBusy ||
  67. sqlError.Code == sqlite3.ErrLocked ||
  68. sqlError.ExtendedCode == sqlite3.ErrLockedSharedCache ||
  69. sqlError.ExtendedCode == sqlite3.ErrBusySnapshot)
  70. }
  71. // transactionWithRetry will retry a write transaction if sqlite3
  72. // reports a table is locked by another writer.
  73. func transactionWithRetry(updater func(*sql.Tx) error) error {
  74. initDataStore()
  75. for i := 0; i < 10; i++ {
  76. if i > 0 {
  77. // Delay on retry
  78. time.Sleep(100)
  79. }
  80. transaction, err := singleton.db.Begin()
  81. if err != nil {
  82. return ContextError(err)
  83. }
  84. err = updater(transaction)
  85. if err != nil {
  86. transaction.Rollback()
  87. if canRetry(err) {
  88. continue
  89. }
  90. return ContextError(err)
  91. }
  92. err = transaction.Commit()
  93. if err != nil {
  94. transaction.Rollback()
  95. if canRetry(err) {
  96. continue
  97. }
  98. return ContextError(err)
  99. }
  100. return nil
  101. }
  102. return ContextError(errors.New("retries exhausted"))
  103. }
  104. // serverEntryExists returns true if a serverEntry with the
  105. // given ipAddress id already exists.
  106. func serverEntryExists(transaction *sql.Tx, ipAddress string) bool {
  107. query := "select count(*) from serverEntry where id = ?;"
  108. var count int
  109. err := singleton.db.QueryRow(query, ipAddress).Scan(&count)
  110. return err == nil && count > 0
  111. }
  112. // StoreServerEntry adds the server entry to the data store. A newly
  113. // stored (or re-stored) server entry is assigned the next-to-top rank
  114. // for cycle order (the previous top ranked entry is promoted). The
  115. // purpose of this is to keep the last selected server as the top
  116. // ranked server.
  117. // When replaceIfExists is true, an existing server entry record is
  118. // overwritten; otherwise, the existing record is unchanged.
  119. func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error {
  120. return transactionWithRetry(func(transaction *sql.Tx) error {
  121. serverEntryExists := serverEntryExists(transaction, serverEntry.IpAddress)
  122. if serverEntryExists && !replaceIfExists {
  123. return nil
  124. }
  125. // TODO: also skip updates if replaceIfExists but 'data' has not changed
  126. _, err := transaction.Exec(`
  127. update serverEntry set rank = rank + 1
  128. where id = (select id from serverEntry order by rank desc limit 1);
  129. `)
  130. if err != nil {
  131. // Note: ContextError() would break canRetry()
  132. return err
  133. }
  134. data, err := json.Marshal(serverEntry)
  135. if err != nil {
  136. return ContextError(err)
  137. }
  138. _, err = transaction.Exec(`
  139. insert or replace into serverEntry (id, rank, region, data)
  140. values (?, (select coalesce(max(rank)-1, 0) from serverEntry), ?, ?);
  141. `, serverEntry.IpAddress, serverEntry.Region, data)
  142. if err != nil {
  143. return err
  144. }
  145. // TODO: log after commit
  146. if !serverEntryExists {
  147. log.Printf("stored server %s", serverEntry.IpAddress)
  148. }
  149. return nil
  150. })
  151. }
  152. // PromoteServerEntry assigns the top cycle rank to the specified
  153. // server entry. This server entry will be the first candidate in
  154. // a subsequent tunnel establishment.
  155. func PromoteServerEntry(ipAddress string) error {
  156. return transactionWithRetry(func(transaction *sql.Tx) error {
  157. _, err := transaction.Exec(`
  158. update serverEntry
  159. set rank = (select MAX(rank)+1 from serverEntry)
  160. where id = ?;
  161. `, ipAddress)
  162. if err != nil {
  163. // Note: ContextError() would break canRetry()
  164. return err
  165. }
  166. return nil
  167. })
  168. }
  169. // ServerEntryCycler is used to continuously iterate over
  170. // stored server entries in rank order.
  171. type ServerEntryCycler struct {
  172. region string
  173. transaction *sql.Tx
  174. cursor *sql.Rows
  175. isReset bool
  176. }
  177. // NewServerEntryCycler creates a new ServerEntryCycler
  178. func NewServerEntryCycler(region string) (cycler *ServerEntryCycler, err error) {
  179. initDataStore()
  180. cycler = &ServerEntryCycler{region: region}
  181. err = cycler.Reset()
  182. if err != nil {
  183. return nil, err
  184. }
  185. return cycler, nil
  186. }
  187. // Reset a ServerEntryCycler to the start of its cycle. The next
  188. // call to Next will return the first server entry.
  189. func (cycler *ServerEntryCycler) Reset() error {
  190. cycler.Close()
  191. transaction, err := singleton.db.Begin()
  192. if err != nil {
  193. return ContextError(err)
  194. }
  195. var cursor *sql.Rows
  196. if cycler.region == "" {
  197. cursor, err = transaction.Query(
  198. "select data from serverEntry order by rank desc;")
  199. } else {
  200. cursor, err = transaction.Query(
  201. "select data from serverEntry where region = ? order by rank desc;",
  202. cycler.region)
  203. }
  204. if err != nil {
  205. transaction.Rollback()
  206. return ContextError(err)
  207. }
  208. cycler.isReset = true
  209. cycler.transaction = transaction
  210. cycler.cursor = cursor
  211. return nil
  212. }
  213. // Close cleans up resources associated with a ServerEntryCycler.
  214. func (cycler *ServerEntryCycler) Close() {
  215. if cycler.cursor != nil {
  216. cycler.cursor.Close()
  217. }
  218. cycler.cursor = nil
  219. if cycler.transaction != nil {
  220. cycler.transaction.Rollback()
  221. }
  222. cycler.transaction = nil
  223. }
  224. // Next returns the next server entry, by rank, for a ServerEntryCycler. When
  225. // the ServerEntryCycler has worked through all known server entries, Next will
  226. // call Reset and start over and return the first server entry again.
  227. func (cycler *ServerEntryCycler) Next() (serverEntry *ServerEntry, err error) {
  228. defer func() {
  229. if err != nil {
  230. cycler.Close()
  231. }
  232. }()
  233. for !cycler.cursor.Next() {
  234. err = cycler.cursor.Err()
  235. if err != nil {
  236. return nil, ContextError(err)
  237. }
  238. if cycler.isReset {
  239. return nil, ContextError(errors.New("no server entries"))
  240. }
  241. err = cycler.Reset()
  242. if err != nil {
  243. return nil, ContextError(err)
  244. }
  245. }
  246. cycler.isReset = false
  247. var data []byte
  248. err = cycler.cursor.Scan(&data)
  249. if err != nil {
  250. return nil, ContextError(err)
  251. }
  252. serverEntry = new(ServerEntry)
  253. err = json.Unmarshal(data, serverEntry)
  254. if err != nil {
  255. return nil, ContextError(err)
  256. }
  257. return serverEntry, nil
  258. }
  259. // HasServerEntries returns true if the data store contains at
  260. // least one server entry (for the specified region, in not blank).
  261. func HasServerEntries(region string) bool {
  262. initDataStore()
  263. var err error
  264. var count int
  265. if region == "" {
  266. err = singleton.db.QueryRow("select count(*) from serverEntry;").Scan(&count)
  267. if err == nil {
  268. log.Printf("servers: %d", count)
  269. }
  270. } else {
  271. err = singleton.db.QueryRow(
  272. "select count(*) from serverEntry where region = ?;", region).Scan(&count)
  273. if err == nil {
  274. log.Printf("servers for region %s: %d", region, count)
  275. }
  276. }
  277. return err == nil && count > 0
  278. }
  279. // GetServerEntryIpAddresses returns an array containing
  280. // all stored server IP addresses.
  281. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  282. initDataStore()
  283. ipAddresses = make([]string, 0)
  284. rows, err := singleton.db.Query("select id from serverEntry;")
  285. if err != nil {
  286. return nil, ContextError(err)
  287. }
  288. defer rows.Close()
  289. for rows.Next() {
  290. var ipAddress string
  291. err = rows.Scan(&ipAddress)
  292. if err != nil {
  293. return nil, ContextError(err)
  294. }
  295. ipAddresses = append(ipAddresses, ipAddress)
  296. }
  297. if err = rows.Err(); err != nil {
  298. return nil, ContextError(err)
  299. }
  300. return ipAddresses, nil
  301. }
  302. // SetKeyValue stores a key/value pair.
  303. func SetKeyValue(key, value string) error {
  304. return transactionWithRetry(func(transaction *sql.Tx) error {
  305. _, err := transaction.Exec(`
  306. insert or replace into keyValue (key, value)
  307. values (?, ?);
  308. `, key, value)
  309. if err != nil {
  310. // Note: ContextError() would break canRetry()
  311. return err
  312. }
  313. return nil
  314. })
  315. }
  316. // GetLastConnected retrieves a key/value pair. If not found,
  317. // it returns an empty string value.
  318. func GetKeyValue(key string) (value string, err error) {
  319. initDataStore()
  320. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  321. err = rows.Scan(&value)
  322. if err == sql.ErrNoRows {
  323. return "", nil
  324. }
  325. if err != nil {
  326. return "", ContextError(err)
  327. }
  328. return value, nil
  329. }