dataStore.go 20 KB

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