dataStore.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. // +build windows
  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. "errors"
  25. "fmt"
  26. "math/rand"
  27. "path/filepath"
  28. "strings"
  29. "sync"
  30. "time"
  31. sqlite3 "github.com/Psiphon-Inc/go-sqlite3"
  32. )
  33. type dataStore struct {
  34. init sync.Once
  35. db *sql.DB
  36. }
  37. var singleton dataStore
  38. // InitDataStore initializes the singleton instance of dataStore. This
  39. // function uses a sync.Once and is safe for use by concurrent goroutines.
  40. // The underlying sql.DB connection pool is also safe.
  41. //
  42. // Note: the sync.Once was more useful when initDataStore was private and
  43. // called on-demand by the public functions below. Now we require an explicit
  44. // InitDataStore() call with the filename passed in. The on-demand calls
  45. // have been replaced by checkInitDataStore() to assert that Init was called.
  46. func InitDataStore(config *Config) (err error) {
  47. singleton.init.Do(func() {
  48. filename := filepath.Join(config.DataStoreDirectory, DATA_STORE_FILENAME)
  49. var db *sql.DB
  50. db, err = sql.Open(
  51. "sqlite3",
  52. fmt.Sprintf("file:%s?cache=private&mode=rwc", filename))
  53. if err != nil {
  54. // Note: intending to set the err return value for InitDataStore
  55. err = fmt.Errorf("initDataStore failed to open database: %s", err)
  56. return
  57. }
  58. initialization := "pragma journal_mode=WAL;\n"
  59. if config.DataStoreTempDirectory != "" {
  60. // On some platforms (e.g., Android), the standard temporary directories expected
  61. // by sqlite (see unixGetTempname in aggregate sqlite3.c) may not be present.
  62. // In that case, sqlite tries to use the current working directory; but this may
  63. // be "/" (again, on Android) which is not writable.
  64. // Instead of setting the process current working directory from this library,
  65. // use the deprecated temp_store_directory pragma to force use of a specified
  66. // temporary directory: https://www.sqlite.org/pragma.html#pragma_temp_store_directory.
  67. // TODO: is there another way to restrict writing of temporary files? E.g. temp_store=3?
  68. initialization += fmt.Sprintf(
  69. "pragma temp_store_directory=\"%s\";\n", config.DataStoreTempDirectory)
  70. }
  71. initialization += `
  72. create table if not exists serverEntry
  73. (id text not null primary key,
  74. rank integer not null unique,
  75. region text not null,
  76. data blob not null);
  77. create index if not exists idx_serverEntry_region on serverEntry(region);
  78. create table if not exists serverEntryProtocol
  79. (serverEntryId text not null,
  80. protocol text not null,
  81. primary key (serverEntryId, protocol));
  82. create table if not exists splitTunnelRoutes
  83. (region text not null primary key,
  84. etag text not null,
  85. data blob not null);
  86. create table if not exists urlETags
  87. (url text not null primary key,
  88. etag text not null);
  89. create table if not exists keyValue
  90. (key text not null primary key,
  91. value text not null);
  92. `
  93. _, err = db.Exec(initialization)
  94. if err != nil {
  95. err = fmt.Errorf("initDataStore failed to initialize: %s", err)
  96. return
  97. }
  98. singleton.db = db
  99. })
  100. return err
  101. }
  102. func checkInitDataStore() {
  103. if singleton.db == nil {
  104. panic("checkInitDataStore: datastore not initialized")
  105. }
  106. }
  107. func canRetry(err error) bool {
  108. sqlError, ok := err.(sqlite3.Error)
  109. return ok && (sqlError.Code == sqlite3.ErrBusy ||
  110. sqlError.Code == sqlite3.ErrLocked ||
  111. sqlError.ExtendedCode == sqlite3.ErrLockedSharedCache ||
  112. sqlError.ExtendedCode == sqlite3.ErrBusySnapshot)
  113. }
  114. // transactionWithRetry will retry a write transaction if sqlite3
  115. // reports a table is locked by another writer.
  116. func transactionWithRetry(updater func(*sql.Tx) error) error {
  117. checkInitDataStore()
  118. for i := 0; i < 10; i++ {
  119. if i > 0 {
  120. // Delay on retry
  121. time.Sleep(100)
  122. }
  123. transaction, err := singleton.db.Begin()
  124. if err != nil {
  125. return ContextError(err)
  126. }
  127. err = updater(transaction)
  128. if err != nil {
  129. transaction.Rollback()
  130. if canRetry(err) {
  131. continue
  132. }
  133. return ContextError(err)
  134. }
  135. err = transaction.Commit()
  136. if err != nil {
  137. transaction.Rollback()
  138. if canRetry(err) {
  139. continue
  140. }
  141. return ContextError(err)
  142. }
  143. return nil
  144. }
  145. return ContextError(errors.New("retries exhausted"))
  146. }
  147. // serverEntryExists returns true if a serverEntry with the
  148. // given ipAddress id already exists.
  149. func serverEntryExists(transaction *sql.Tx, ipAddress string) (bool, error) {
  150. query := "select count(*) from serverEntry where id = ?;"
  151. var count int
  152. err := singleton.db.QueryRow(query, ipAddress).Scan(&count)
  153. if err != nil {
  154. return false, ContextError(err)
  155. }
  156. return count > 0, nil
  157. }
  158. // StoreServerEntry adds the server entry to the data store.
  159. // A newly stored (or re-stored) server entry is assigned the next-to-top
  160. // rank for iteration order (the previous top ranked entry is promoted). The
  161. // purpose of inserting at next-to-top is to keep the last selected server
  162. // as the top ranked server. Note, server candidates are iterated in decending
  163. // rank order, so the largest rank is top rank.
  164. // When replaceIfExists is true, an existing server entry record is
  165. // overwritten; otherwise, the existing record is unchanged.
  166. // If the server entry data is malformed, an alert notice is issued and
  167. // the entry is skipped; no error is returned.
  168. func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error {
  169. // Server entries should already be validated before this point,
  170. // so instead of skipping we fail with an error.
  171. err := ValidateServerEntry(serverEntry)
  172. if err != nil {
  173. return ContextError(errors.New("invalid server entry"))
  174. }
  175. return transactionWithRetry(func(transaction *sql.Tx) error {
  176. serverEntryExists, err := serverEntryExists(transaction, serverEntry.IpAddress)
  177. if err != nil {
  178. return ContextError(err)
  179. }
  180. if serverEntryExists && !replaceIfExists {
  181. // Disabling this notice, for now, as it generates too much noise
  182. // in diagnostics with clients that always submit embedded servers
  183. // to the core on each run.
  184. // NoticeInfo("ignored update for server %s", serverEntry.IpAddress)
  185. return nil
  186. }
  187. _, err = transaction.Exec(`
  188. update serverEntry set rank = rank + 1
  189. where id = (select id from serverEntry order by rank desc limit 1);
  190. `)
  191. if err != nil {
  192. // Note: ContextError() would break canRetry()
  193. return err
  194. }
  195. data, err := json.Marshal(serverEntry)
  196. if err != nil {
  197. return ContextError(err)
  198. }
  199. _, err = transaction.Exec(`
  200. insert or replace into serverEntry (id, rank, region, data)
  201. values (?, (select coalesce(max(rank)-1, 0) from serverEntry), ?, ?);
  202. `, serverEntry.IpAddress, serverEntry.Region, data)
  203. if err != nil {
  204. return err
  205. }
  206. _, err = transaction.Exec(`
  207. delete from serverEntryProtocol where serverEntryId = ?;
  208. `, serverEntry.IpAddress)
  209. if err != nil {
  210. return err
  211. }
  212. for _, protocol := range SupportedTunnelProtocols {
  213. // Note: for meek, the capabilities are FRONTED-MEEK and UNFRONTED-MEEK
  214. // and the additonal OSSH service is assumed to be available internally.
  215. requiredCapability := strings.TrimSuffix(protocol, "-OSSH")
  216. if Contains(serverEntry.Capabilities, requiredCapability) {
  217. _, err = transaction.Exec(`
  218. insert into serverEntryProtocol (serverEntryId, protocol)
  219. values (?, ?);
  220. `, serverEntry.IpAddress, protocol)
  221. if err != nil {
  222. return err
  223. }
  224. }
  225. }
  226. // TODO: post notice after commit
  227. if !serverEntryExists {
  228. NoticeInfo("updated server %s", serverEntry.IpAddress)
  229. }
  230. return nil
  231. })
  232. }
  233. // StoreServerEntries shuffles and stores a list of server entries.
  234. // Shuffling is performed on imported server entrues as part of client-side
  235. // load balancing.
  236. // There is an independent transaction for each entry insert/update.
  237. func StoreServerEntries(serverEntries []*ServerEntry, replaceIfExists bool) error {
  238. for index := len(serverEntries) - 1; index > 0; index-- {
  239. swapIndex := rand.Intn(index + 1)
  240. serverEntries[index], serverEntries[swapIndex] = serverEntries[swapIndex], serverEntries[index]
  241. }
  242. for _, serverEntry := range serverEntries {
  243. err := StoreServerEntry(serverEntry, replaceIfExists)
  244. if err != nil {
  245. return ContextError(err)
  246. }
  247. }
  248. // Since there has possibly been a significant change in the server entries,
  249. // take this opportunity to update the available egress regions.
  250. ReportAvailableRegions()
  251. return nil
  252. }
  253. // PromoteServerEntry assigns the top rank (one more than current
  254. // max rank) to the specified server entry. Server candidates are
  255. // iterated in decending rank order, so this server entry will be
  256. // the first candidate in a subsequent tunnel establishment.
  257. func PromoteServerEntry(ipAddress string) error {
  258. return transactionWithRetry(func(transaction *sql.Tx) error {
  259. _, err := transaction.Exec(`
  260. update serverEntry
  261. set rank = (select MAX(rank)+1 from serverEntry)
  262. where id = ?;
  263. `, ipAddress)
  264. if err != nil {
  265. // Note: ContextError() would break canRetry()
  266. return err
  267. }
  268. return nil
  269. })
  270. }
  271. // ServerEntryIterator is used to iterate over
  272. // stored server entries in rank order.
  273. type ServerEntryIterator struct {
  274. region string
  275. protocol string
  276. shuffleHeadLength int
  277. transaction *sql.Tx
  278. cursor *sql.Rows
  279. isTargetServerEntryIterator bool
  280. hasNextTargetServerEntry bool
  281. targetServerEntry *ServerEntry
  282. }
  283. // NewServerEntryIterator creates a new NewServerEntryIterator
  284. func NewServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  285. // When configured, this target server entry is the only candidate
  286. if config.TargetServerEntry != "" {
  287. return newTargetServerEntryIterator(config)
  288. }
  289. checkInitDataStore()
  290. iterator = &ServerEntryIterator{
  291. region: config.EgressRegion,
  292. protocol: config.TunnelProtocol,
  293. shuffleHeadLength: config.TunnelPoolSize,
  294. isTargetServerEntryIterator: false,
  295. }
  296. err = iterator.Reset()
  297. if err != nil {
  298. return nil, err
  299. }
  300. return iterator, nil
  301. }
  302. // newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
  303. func newTargetServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  304. serverEntry, err := DecodeServerEntry(config.TargetServerEntry)
  305. if err != nil {
  306. return nil, err
  307. }
  308. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  309. return nil, errors.New("TargetServerEntry does not support EgressRegion")
  310. }
  311. if config.TunnelProtocol != "" {
  312. // Note: same capability/protocol mapping as in StoreServerEntry
  313. requiredCapability := strings.TrimSuffix(config.TunnelProtocol, "-OSSH")
  314. if !Contains(serverEntry.Capabilities, requiredCapability) {
  315. return nil, errors.New("TargetServerEntry does not support TunnelProtocol")
  316. }
  317. }
  318. iterator = &ServerEntryIterator{
  319. isTargetServerEntryIterator: true,
  320. hasNextTargetServerEntry: true,
  321. targetServerEntry: serverEntry,
  322. }
  323. NoticeInfo("using TargetServerEntry: %s", serverEntry.IpAddress)
  324. return iterator, nil
  325. }
  326. // Reset a NewServerEntryIterator to the start of its cycle. The next
  327. // call to Next will return the first server entry.
  328. func (iterator *ServerEntryIterator) Reset() error {
  329. iterator.Close()
  330. if iterator.isTargetServerEntryIterator {
  331. iterator.hasNextTargetServerEntry = true
  332. return nil
  333. }
  334. count := CountServerEntries(iterator.region, iterator.protocol)
  335. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  336. transaction, err := singleton.db.Begin()
  337. if err != nil {
  338. return ContextError(err)
  339. }
  340. var cursor *sql.Rows
  341. // This query implements the Psiphon server candidate selection
  342. // algorithm: the first TunnelPoolSize server candidates are in rank
  343. // (priority) order, to favor previously successful servers; then the
  344. // remaining long tail is shuffled to raise up less recent candidates.
  345. whereClause, whereParams := makeServerEntryWhereClause(
  346. iterator.region, iterator.protocol, nil)
  347. headLength := iterator.shuffleHeadLength
  348. queryFormat := `
  349. select data from serverEntry %s
  350. order by case
  351. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  352. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  353. end desc;`
  354. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  355. params := make([]interface{}, 0)
  356. params = append(params, whereParams...)
  357. params = append(params, whereParams...)
  358. params = append(params, headLength)
  359. params = append(params, whereParams...)
  360. params = append(params, headLength)
  361. cursor, err = transaction.Query(query, params...)
  362. if err != nil {
  363. transaction.Rollback()
  364. return ContextError(err)
  365. }
  366. iterator.transaction = transaction
  367. iterator.cursor = cursor
  368. return nil
  369. }
  370. // Close cleans up resources associated with a ServerEntryIterator.
  371. func (iterator *ServerEntryIterator) Close() {
  372. if iterator.cursor != nil {
  373. iterator.cursor.Close()
  374. }
  375. iterator.cursor = nil
  376. if iterator.transaction != nil {
  377. iterator.transaction.Rollback()
  378. }
  379. iterator.transaction = nil
  380. }
  381. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  382. // Returns nil with no error when there is no next item.
  383. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  384. defer func() {
  385. if err != nil {
  386. iterator.Close()
  387. }
  388. }()
  389. if iterator.isTargetServerEntryIterator {
  390. if iterator.hasNextTargetServerEntry {
  391. iterator.hasNextTargetServerEntry = false
  392. return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
  393. }
  394. return nil, nil
  395. }
  396. if !iterator.cursor.Next() {
  397. err = iterator.cursor.Err()
  398. if err != nil {
  399. return nil, ContextError(err)
  400. }
  401. // There is no next item
  402. return nil, nil
  403. }
  404. var data []byte
  405. err = iterator.cursor.Scan(&data)
  406. if err != nil {
  407. return nil, ContextError(err)
  408. }
  409. serverEntry = new(ServerEntry)
  410. err = json.Unmarshal(data, serverEntry)
  411. if err != nil {
  412. return nil, ContextError(err)
  413. }
  414. return MakeCompatibleServerEntry(serverEntry), nil
  415. }
  416. // MakeCompatibleServerEntry provides backwards compatibility with old server entries
  417. // which have a single meekFrontingDomain and not a meekFrontingAddresses array.
  418. // By copying this one meekFrontingDomain into meekFrontingAddresses, this client effectively
  419. // uses that single value as legacy clients do.
  420. func MakeCompatibleServerEntry(serverEntry *ServerEntry) *ServerEntry {
  421. if len(serverEntry.MeekFrontingAddresses) == 0 && serverEntry.MeekFrontingDomain != "" {
  422. serverEntry.MeekFrontingAddresses =
  423. append(serverEntry.MeekFrontingAddresses, serverEntry.MeekFrontingDomain)
  424. }
  425. return serverEntry
  426. }
  427. func makeServerEntryWhereClause(
  428. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  429. whereClause = ""
  430. whereParams = make([]interface{}, 0)
  431. if region != "" {
  432. whereClause += " where region = ?"
  433. whereParams = append(whereParams, region)
  434. }
  435. if protocol != "" {
  436. if len(whereClause) > 0 {
  437. whereClause += " and"
  438. } else {
  439. whereClause += " where"
  440. }
  441. whereClause +=
  442. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  443. whereParams = append(whereParams, protocol)
  444. }
  445. if len(excludeIds) > 0 {
  446. if len(whereClause) > 0 {
  447. whereClause += " and"
  448. } else {
  449. whereClause += " where"
  450. }
  451. whereClause += " id in ("
  452. for index, id := range excludeIds {
  453. if index > 0 {
  454. whereClause += ", "
  455. }
  456. whereClause += "?"
  457. whereParams = append(whereParams, id)
  458. }
  459. whereClause += ")"
  460. }
  461. return whereClause, whereParams
  462. }
  463. // CountServerEntries returns a count of stored servers for the
  464. // specified region and protocol.
  465. func CountServerEntries(region, protocol string) int {
  466. checkInitDataStore()
  467. var count int
  468. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  469. query := "select count(*) from serverEntry" + whereClause
  470. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  471. if err != nil {
  472. NoticeAlert("CountServerEntries failed: %s", err)
  473. return 0
  474. }
  475. if region == "" {
  476. region = "(any)"
  477. }
  478. if protocol == "" {
  479. protocol = "(any)"
  480. }
  481. NoticeInfo("servers for region %s and protocol %s: %d",
  482. region, protocol, count)
  483. return count
  484. }
  485. // ReportAvailableRegions prints a notice with the available egress regions.
  486. func ReportAvailableRegions() {
  487. checkInitDataStore()
  488. // TODO: For consistency, regions-per-protocol should be used
  489. rows, err := singleton.db.Query("select distinct(region) from serverEntry;")
  490. if err != nil {
  491. NoticeAlert("failed to query data store for available regions: %s", ContextError(err))
  492. return
  493. }
  494. defer rows.Close()
  495. var regions []string
  496. for rows.Next() {
  497. var region string
  498. err = rows.Scan(&region)
  499. if err != nil {
  500. NoticeAlert("failed to retrieve available regions from data store: %s", ContextError(err))
  501. return
  502. }
  503. // Some server entries do not have a region, but it makes no sense to return
  504. // an empty string as an "available region".
  505. if region != "" {
  506. regions = append(regions, region)
  507. }
  508. }
  509. NoticeAvailableEgressRegions(regions)
  510. }
  511. // GetServerEntryIpAddresses returns an array containing
  512. // all stored server IP addresses.
  513. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  514. checkInitDataStore()
  515. ipAddresses = make([]string, 0)
  516. rows, err := singleton.db.Query("select id from serverEntry;")
  517. if err != nil {
  518. return nil, ContextError(err)
  519. }
  520. defer rows.Close()
  521. for rows.Next() {
  522. var ipAddress string
  523. err = rows.Scan(&ipAddress)
  524. if err != nil {
  525. return nil, ContextError(err)
  526. }
  527. ipAddresses = append(ipAddresses, ipAddress)
  528. }
  529. if err = rows.Err(); err != nil {
  530. return nil, ContextError(err)
  531. }
  532. return ipAddresses, nil
  533. }
  534. // SetSplitTunnelRoutes updates the cached routes data for
  535. // the given region. The associated etag is also stored and
  536. // used to make efficient web requests for updates to the data.
  537. func SetSplitTunnelRoutes(region, etag string, data []byte) error {
  538. return transactionWithRetry(func(transaction *sql.Tx) error {
  539. _, err := transaction.Exec(`
  540. insert or replace into splitTunnelRoutes (region, etag, data)
  541. values (?, ?, ?);
  542. `, region, etag, data)
  543. if err != nil {
  544. // Note: ContextError() would break canRetry()
  545. return err
  546. }
  547. return nil
  548. })
  549. }
  550. // GetSplitTunnelRoutesETag retrieves the etag for cached routes
  551. // data for the specified region. If not found, it returns an empty string value.
  552. func GetSplitTunnelRoutesETag(region string) (etag string, err error) {
  553. checkInitDataStore()
  554. rows := singleton.db.QueryRow("select etag from splitTunnelRoutes where region = ?;", region)
  555. err = rows.Scan(&etag)
  556. if err == sql.ErrNoRows {
  557. return "", nil
  558. }
  559. if err != nil {
  560. return "", ContextError(err)
  561. }
  562. return etag, nil
  563. }
  564. // GetSplitTunnelRoutesData retrieves the cached routes data
  565. // for the specified region. If not found, it returns a nil value.
  566. func GetSplitTunnelRoutesData(region string) (data []byte, err error) {
  567. checkInitDataStore()
  568. rows := singleton.db.QueryRow("select data from splitTunnelRoutes where region = ?;", region)
  569. err = rows.Scan(&data)
  570. if err == sql.ErrNoRows {
  571. return nil, nil
  572. }
  573. if err != nil {
  574. return nil, ContextError(err)
  575. }
  576. return data, nil
  577. }
  578. // SetUrlETag stores an ETag for the specfied URL.
  579. // Note: input URL is treated as a string, and is not
  580. // encoded or decoded or otherwise canonicalized.
  581. func SetUrlETag(url, etag string) error {
  582. return transactionWithRetry(func(transaction *sql.Tx) error {
  583. _, err := transaction.Exec(`
  584. insert or replace into urlETags (url, etag)
  585. values (?, ?);
  586. `, url, etag)
  587. if err != nil {
  588. // Note: ContextError() would break canRetry()
  589. return err
  590. }
  591. return nil
  592. })
  593. }
  594. // GetUrlETag retrieves a previously stored an ETag for the
  595. // specfied URL. If not found, it returns an empty string value.
  596. func GetUrlETag(url string) (etag string, err error) {
  597. checkInitDataStore()
  598. rows := singleton.db.QueryRow("select etag from urlETags where url = ?;", url)
  599. err = rows.Scan(&etag)
  600. if err == sql.ErrNoRows {
  601. return "", nil
  602. }
  603. if err != nil {
  604. return "", ContextError(err)
  605. }
  606. return etag, nil
  607. }
  608. // SetKeyValue stores a key/value pair.
  609. func SetKeyValue(key, value string) error {
  610. return transactionWithRetry(func(transaction *sql.Tx) error {
  611. _, err := transaction.Exec(`
  612. insert or replace into keyValue (key, value)
  613. values (?, ?);
  614. `, key, value)
  615. if err != nil {
  616. // Note: ContextError() would break canRetry()
  617. return err
  618. }
  619. return nil
  620. })
  621. }
  622. // GetKeyValue retrieves the value for a given key. If not found,
  623. // it returns an empty string value.
  624. func GetKeyValue(key string) (value string, err error) {
  625. checkInitDataStore()
  626. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  627. err = rows.Scan(&value)
  628. if err == sql.ErrNoRows {
  629. return "", nil
  630. }
  631. if err != nil {
  632. return "", ContextError(err)
  633. }
  634. return value, nil
  635. }