index_stats.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (c) 2014 Couchbase, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package bleve
  15. import (
  16. "encoding/json"
  17. "sync"
  18. "sync/atomic"
  19. )
  20. type IndexStat struct {
  21. searches uint64
  22. searchTime uint64
  23. i *indexImpl
  24. }
  25. func (is *IndexStat) statsMap() map[string]interface{} {
  26. m := map[string]interface{}{}
  27. m["index"] = is.i.i.StatsMap()
  28. m["searches"] = atomic.LoadUint64(&is.searches)
  29. m["search_time"] = atomic.LoadUint64(&is.searchTime)
  30. return m
  31. }
  32. func (is *IndexStat) MarshalJSON() ([]byte, error) {
  33. m := is.statsMap()
  34. return json.Marshal(m)
  35. }
  36. type IndexStats struct {
  37. indexes map[string]*IndexStat
  38. mutex sync.RWMutex
  39. }
  40. func NewIndexStats() *IndexStats {
  41. return &IndexStats{
  42. indexes: make(map[string]*IndexStat),
  43. }
  44. }
  45. func (i *IndexStats) Register(index Index) {
  46. i.mutex.Lock()
  47. defer i.mutex.Unlock()
  48. i.indexes[index.Name()] = index.Stats()
  49. }
  50. func (i *IndexStats) UnRegister(index Index) {
  51. i.mutex.Lock()
  52. defer i.mutex.Unlock()
  53. delete(i.indexes, index.Name())
  54. }
  55. func (i *IndexStats) String() string {
  56. i.mutex.RLock()
  57. defer i.mutex.RUnlock()
  58. bytes, err := json.Marshal(i.indexes)
  59. if err != nil {
  60. return "error marshaling stats"
  61. }
  62. return string(bytes)
  63. }
  64. var indexStats *IndexStats