database.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. // Copyright (C) 2018 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //go:generate go run ../../script/protofmt.go database.proto
  7. //go:generate protoc -I ../../../../../ -I ../../vendor/ -I ../../vendor/github.com/gogo/protobuf/protobuf -I . --gogofast_out=. database.proto
  8. package main
  9. import (
  10. "sort"
  11. "time"
  12. "github.com/syndtr/goleveldb/leveldb"
  13. "github.com/syndtr/goleveldb/leveldb/util"
  14. )
  15. type clock interface {
  16. Now() time.Time
  17. }
  18. type defaultClock struct{}
  19. func (defaultClock) Now() time.Time {
  20. return time.Now()
  21. }
  22. type database interface {
  23. put(key string, rec DatabaseRecord) error
  24. merge(key string, addrs []DatabaseAddress, seen int64) error
  25. get(key string) (DatabaseRecord, error)
  26. }
  27. type levelDBStore struct {
  28. db *leveldb.DB
  29. inbox chan func()
  30. stop chan struct{}
  31. clock clock
  32. marshalBuf []byte
  33. }
  34. func newLevelDBStore(dir string) (*levelDBStore, error) {
  35. db, err := leveldb.OpenFile(dir, levelDBOptions)
  36. if err != nil {
  37. return nil, err
  38. }
  39. return &levelDBStore{
  40. db: db,
  41. inbox: make(chan func(), 16),
  42. stop: make(chan struct{}),
  43. clock: defaultClock{},
  44. }, nil
  45. }
  46. func (s *levelDBStore) put(key string, rec DatabaseRecord) error {
  47. t0 := time.Now()
  48. defer func() {
  49. databaseOperationSeconds.WithLabelValues(dbOpPut).Observe(time.Since(t0).Seconds())
  50. }()
  51. rc := make(chan error)
  52. s.inbox <- func() {
  53. size := rec.Size()
  54. if len(s.marshalBuf) < size {
  55. s.marshalBuf = make([]byte, size)
  56. }
  57. n, _ := rec.MarshalTo(s.marshalBuf)
  58. rc <- s.db.Put([]byte(key), s.marshalBuf[:n], nil)
  59. }
  60. err := <-rc
  61. if err != nil {
  62. databaseOperations.WithLabelValues(dbOpPut, dbResError).Inc()
  63. } else {
  64. databaseOperations.WithLabelValues(dbOpPut, dbResSuccess).Inc()
  65. }
  66. return err
  67. }
  68. func (s *levelDBStore) merge(key string, addrs []DatabaseAddress, seen int64) error {
  69. t0 := time.Now()
  70. defer func() {
  71. databaseOperationSeconds.WithLabelValues(dbOpMerge).Observe(time.Since(t0).Seconds())
  72. }()
  73. rc := make(chan error)
  74. newRec := DatabaseRecord{
  75. Addresses: addrs,
  76. Seen: seen,
  77. }
  78. s.inbox <- func() {
  79. // grab the existing record
  80. oldRec, err := s.get(key)
  81. if err != nil {
  82. // "not found" is not an error from get, so this is serious
  83. // stuff only
  84. rc <- err
  85. return
  86. }
  87. newRec = merge(newRec, oldRec)
  88. // We replicate s.put() functionality here ourselves instead of
  89. // calling it because we want to serialize our get above together
  90. // with the put in the same function.
  91. size := newRec.Size()
  92. if len(s.marshalBuf) < size {
  93. s.marshalBuf = make([]byte, size)
  94. }
  95. n, _ := newRec.MarshalTo(s.marshalBuf)
  96. rc <- s.db.Put([]byte(key), s.marshalBuf[:n], nil)
  97. }
  98. err := <-rc
  99. if err != nil {
  100. databaseOperations.WithLabelValues(dbOpMerge, dbResError).Inc()
  101. } else {
  102. databaseOperations.WithLabelValues(dbOpMerge, dbResSuccess).Inc()
  103. }
  104. return err
  105. }
  106. func (s *levelDBStore) get(key string) (DatabaseRecord, error) {
  107. t0 := time.Now()
  108. defer func() {
  109. databaseOperationSeconds.WithLabelValues(dbOpGet).Observe(time.Since(t0).Seconds())
  110. }()
  111. keyBs := []byte(key)
  112. val, err := s.db.Get(keyBs, nil)
  113. if err == leveldb.ErrNotFound {
  114. databaseOperations.WithLabelValues(dbOpGet, dbResNotFound).Inc()
  115. return DatabaseRecord{}, nil
  116. }
  117. if err != nil {
  118. databaseOperations.WithLabelValues(dbOpGet, dbResError).Inc()
  119. return DatabaseRecord{}, err
  120. }
  121. var rec DatabaseRecord
  122. if err := rec.Unmarshal(val); err != nil {
  123. databaseOperations.WithLabelValues(dbOpGet, dbResUnmarshalError).Inc()
  124. return DatabaseRecord{}, nil
  125. }
  126. rec.Addresses = expire(rec.Addresses, s.clock.Now().UnixNano())
  127. databaseOperations.WithLabelValues(dbOpGet, dbResSuccess).Inc()
  128. return rec, nil
  129. }
  130. func (s *levelDBStore) Serve() {
  131. t := time.NewTimer(0)
  132. defer t.Stop()
  133. defer s.db.Close()
  134. // Start the statistics serve routine. It will exit with us when
  135. // statisticsTrigger is closed.
  136. statisticsTrigger := make(chan struct{})
  137. defer close(statisticsTrigger)
  138. statisticsDone := make(chan struct{})
  139. go s.statisticsServe(statisticsTrigger, statisticsDone)
  140. for {
  141. select {
  142. case fn := <-s.inbox:
  143. // Run function in serialized order.
  144. fn()
  145. case <-t.C:
  146. // Trigger the statistics routine to do its thing in the
  147. // background.
  148. statisticsTrigger <- struct{}{}
  149. case <-statisticsDone:
  150. // The statistics routine is done with one iteratation, schedule
  151. // the next.
  152. t.Reset(databaseStatisticsInterval)
  153. case <-s.stop:
  154. // We're done.
  155. return
  156. }
  157. }
  158. }
  159. func (s *levelDBStore) statisticsServe(trigger <-chan struct{}, done chan<- struct{}) {
  160. for range trigger {
  161. t0 := time.Now()
  162. nowNanos := t0.UnixNano()
  163. cutoff24h := t0.Add(-24 * time.Hour).UnixNano()
  164. cutoff1w := t0.Add(-7 * 24 * time.Hour).UnixNano()
  165. current, last24h, last1w, inactive, errors := 0, 0, 0, 0, 0
  166. iter := s.db.NewIterator(&util.Range{}, nil)
  167. for iter.Next() {
  168. // Attempt to unmarshal the record and count the
  169. // failure if there's something wrong with it.
  170. var rec DatabaseRecord
  171. if err := rec.Unmarshal(iter.Value()); err != nil {
  172. errors++
  173. continue
  174. }
  175. // If there are addresses that have not expired it's a current
  176. // record, otherwise account it based on when it was last seen
  177. // (last 24 hours or last week) or finally as inactice.
  178. switch {
  179. case len(expire(rec.Addresses, nowNanos)) > 0:
  180. current++
  181. case rec.Seen > cutoff24h:
  182. last24h++
  183. case rec.Seen > cutoff1w:
  184. last1w++
  185. default:
  186. inactive++
  187. }
  188. }
  189. iter.Release()
  190. databaseKeys.WithLabelValues("current").Set(float64(current))
  191. databaseKeys.WithLabelValues("last24h").Set(float64(last24h))
  192. databaseKeys.WithLabelValues("last1w").Set(float64(last1w))
  193. databaseKeys.WithLabelValues("inactive").Set(float64(inactive))
  194. databaseKeys.WithLabelValues("error").Set(float64(errors))
  195. databaseStatisticsSeconds.Set(time.Since(t0).Seconds())
  196. // Signal that we are done and can be scheduled again.
  197. done <- struct{}{}
  198. }
  199. }
  200. func (s *levelDBStore) Stop() {
  201. close(s.stop)
  202. }
  203. // merge returns the merged result of the two database records a and b. The
  204. // result is the union of the two address sets, with the newer expiry time
  205. // chosen for any duplicates.
  206. func merge(a, b DatabaseRecord) DatabaseRecord {
  207. // Both lists must be sorted for this to work.
  208. sort.Slice(a.Addresses, func(i, j int) bool {
  209. return a.Addresses[i].Address < a.Addresses[j].Address
  210. })
  211. sort.Slice(b.Addresses, func(i, j int) bool {
  212. return b.Addresses[i].Address < b.Addresses[j].Address
  213. })
  214. res := DatabaseRecord{
  215. Addresses: make([]DatabaseAddress, 0, len(a.Addresses)+len(b.Addresses)),
  216. Seen: a.Seen,
  217. }
  218. if b.Seen > a.Seen {
  219. res.Seen = b.Seen
  220. }
  221. aIdx := 0
  222. bIdx := 0
  223. aAddrs := a.Addresses
  224. bAddrs := b.Addresses
  225. loop:
  226. for {
  227. switch {
  228. case aIdx == len(aAddrs) && bIdx == len(bAddrs):
  229. // both lists are exhausted, we are done
  230. break loop
  231. case aIdx == len(aAddrs):
  232. // a is exhausted, pick from b and continue
  233. res.Addresses = append(res.Addresses, bAddrs[bIdx])
  234. bIdx++
  235. continue
  236. case bIdx == len(bAddrs):
  237. // b is exhausted, pick from a and continue
  238. res.Addresses = append(res.Addresses, aAddrs[aIdx])
  239. aIdx++
  240. continue
  241. }
  242. // We have values left on both sides.
  243. aVal := aAddrs[aIdx]
  244. bVal := bAddrs[bIdx]
  245. switch {
  246. case aVal.Address == bVal.Address:
  247. // update for same address, pick newer
  248. if aVal.Expires > bVal.Expires {
  249. res.Addresses = append(res.Addresses, aVal)
  250. } else {
  251. res.Addresses = append(res.Addresses, bVal)
  252. }
  253. aIdx++
  254. bIdx++
  255. case aVal.Address < bVal.Address:
  256. // a is smallest, pick it and continue
  257. res.Addresses = append(res.Addresses, aVal)
  258. aIdx++
  259. default:
  260. // b is smallest, pick it and continue
  261. res.Addresses = append(res.Addresses, bVal)
  262. bIdx++
  263. }
  264. }
  265. return res
  266. }
  267. // expire returns the list of addresses after removing expired entries.
  268. // Expiration happen in place, so the slice given as the parameter is
  269. // destroyed. Internal order is not preserved.
  270. func expire(addrs []DatabaseAddress, now int64) []DatabaseAddress {
  271. i := 0
  272. for i < len(addrs) {
  273. if addrs[i].Expires < now {
  274. // This item is expired. Replace it with the last in the list
  275. // (noop if we are at the last item).
  276. addrs[i] = addrs[len(addrs)-1]
  277. // Wipe the last item of the list to release references to
  278. // strings and stuff.
  279. addrs[len(addrs)-1] = DatabaseAddress{}
  280. // Shorten the slice.
  281. addrs = addrs[:len(addrs)-1]
  282. continue
  283. }
  284. i++
  285. }
  286. return addrs
  287. }