dataStore.go 20 KB

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