database.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. cutoff2Mon := t0.Add(-60 * 24 * time.Hour).UnixNano()
  166. current, last24h, last1w, inactive, errors := 0, 0, 0, 0, 0
  167. iter := s.db.NewIterator(&util.Range{}, nil)
  168. for iter.Next() {
  169. // Attempt to unmarshal the record and count the
  170. // failure if there's something wrong with it.
  171. var rec DatabaseRecord
  172. if err := rec.Unmarshal(iter.Value()); err != nil {
  173. errors++
  174. continue
  175. }
  176. // If there are addresses that have not expired it's a current
  177. // record, otherwise account it based on when it was last seen
  178. // (last 24 hours or last week) or finally as inactice.
  179. switch {
  180. case len(expire(rec.Addresses, nowNanos)) > 0:
  181. current++
  182. case rec.Seen > cutoff24h:
  183. last24h++
  184. case rec.Seen > cutoff1w:
  185. last1w++
  186. case rec.Seen > cutoff2Mon:
  187. inactive++
  188. case rec.Missed < cutoff2Mon:
  189. // It hasn't been seen lately and we haven't recorded
  190. // someone asking for this device in a long time either;
  191. // delete the record.
  192. if err := s.db.Delete(iter.Key(), nil); err != nil {
  193. databaseOperations.WithLabelValues(dbOpDelete, dbResError).Inc()
  194. } else {
  195. databaseOperations.WithLabelValues(dbOpDelete, dbResSuccess).Inc()
  196. }
  197. default:
  198. inactive++
  199. }
  200. }
  201. iter.Release()
  202. databaseKeys.WithLabelValues("current").Set(float64(current))
  203. databaseKeys.WithLabelValues("last24h").Set(float64(last24h))
  204. databaseKeys.WithLabelValues("last1w").Set(float64(last1w))
  205. databaseKeys.WithLabelValues("inactive").Set(float64(inactive))
  206. databaseKeys.WithLabelValues("error").Set(float64(errors))
  207. databaseStatisticsSeconds.Set(time.Since(t0).Seconds())
  208. // Signal that we are done and can be scheduled again.
  209. done <- struct{}{}
  210. }
  211. }
  212. func (s *levelDBStore) Stop() {
  213. close(s.stop)
  214. }
  215. // merge returns the merged result of the two database records a and b. The
  216. // result is the union of the two address sets, with the newer expiry time
  217. // chosen for any duplicates.
  218. func merge(a, b DatabaseRecord) DatabaseRecord {
  219. // Both lists must be sorted for this to work.
  220. sort.Slice(a.Addresses, func(i, j int) bool {
  221. return a.Addresses[i].Address < a.Addresses[j].Address
  222. })
  223. sort.Slice(b.Addresses, func(i, j int) bool {
  224. return b.Addresses[i].Address < b.Addresses[j].Address
  225. })
  226. res := DatabaseRecord{
  227. Addresses: make([]DatabaseAddress, 0, len(a.Addresses)+len(b.Addresses)),
  228. Seen: a.Seen,
  229. }
  230. if b.Seen > a.Seen {
  231. res.Seen = b.Seen
  232. }
  233. aIdx := 0
  234. bIdx := 0
  235. aAddrs := a.Addresses
  236. bAddrs := b.Addresses
  237. loop:
  238. for {
  239. switch {
  240. case aIdx == len(aAddrs) && bIdx == len(bAddrs):
  241. // both lists are exhausted, we are done
  242. break loop
  243. case aIdx == len(aAddrs):
  244. // a is exhausted, pick from b and continue
  245. res.Addresses = append(res.Addresses, bAddrs[bIdx])
  246. bIdx++
  247. continue
  248. case bIdx == len(bAddrs):
  249. // b is exhausted, pick from a and continue
  250. res.Addresses = append(res.Addresses, aAddrs[aIdx])
  251. aIdx++
  252. continue
  253. }
  254. // We have values left on both sides.
  255. aVal := aAddrs[aIdx]
  256. bVal := bAddrs[bIdx]
  257. switch {
  258. case aVal.Address == bVal.Address:
  259. // update for same address, pick newer
  260. if aVal.Expires > bVal.Expires {
  261. res.Addresses = append(res.Addresses, aVal)
  262. } else {
  263. res.Addresses = append(res.Addresses, bVal)
  264. }
  265. aIdx++
  266. bIdx++
  267. case aVal.Address < bVal.Address:
  268. // a is smallest, pick it and continue
  269. res.Addresses = append(res.Addresses, aVal)
  270. aIdx++
  271. default:
  272. // b is smallest, pick it and continue
  273. res.Addresses = append(res.Addresses, bVal)
  274. bIdx++
  275. }
  276. }
  277. return res
  278. }
  279. // expire returns the list of addresses after removing expired entries.
  280. // Expiration happen in place, so the slice given as the parameter is
  281. // destroyed. Internal order is not preserved.
  282. func expire(addrs []DatabaseAddress, now int64) []DatabaseAddress {
  283. i := 0
  284. for i < len(addrs) {
  285. if addrs[i].Expires < now {
  286. // This item is expired. Replace it with the last in the list
  287. // (noop if we are at the last item).
  288. addrs[i] = addrs[len(addrs)-1]
  289. // Wipe the last item of the list to release references to
  290. // strings and stuff.
  291. addrs[len(addrs)-1] = DatabaseAddress{}
  292. // Shorten the slice.
  293. addrs = addrs[:len(addrs)-1]
  294. continue
  295. }
  296. i++
  297. }
  298. return addrs
  299. }