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
15package bleve
16
17import (
18	"encoding/json"
19	"sync"
20	"sync/atomic"
21)
22
23type IndexStat struct {
24	searches   uint64
25	searchTime uint64
26	i          *indexImpl
27}
28
29func (is *IndexStat) statsMap() map[string]interface{} {
30	m := map[string]interface{}{}
31	m["index"] = is.i.i.StatsMap()
32	m["searches"] = atomic.LoadUint64(&is.searches)
33	m["search_time"] = atomic.LoadUint64(&is.searchTime)
34	return m
35}
36
37func (is *IndexStat) MarshalJSON() ([]byte, error) {
38	m := is.statsMap()
39	return json.Marshal(m)
40}
41
42type IndexStats struct {
43	indexes map[string]*IndexStat
44	mutex   sync.RWMutex
45}
46
47func NewIndexStats() *IndexStats {
48	return &IndexStats{
49		indexes: make(map[string]*IndexStat),
50	}
51}
52
53func (i *IndexStats) Register(index Index) {
54	i.mutex.Lock()
55	defer i.mutex.Unlock()
56	i.indexes[index.Name()] = index.Stats()
57}
58
59func (i *IndexStats) UnRegister(index Index) {
60	i.mutex.Lock()
61	defer i.mutex.Unlock()
62	delete(i.indexes, index.Name())
63}
64
65func (i *IndexStats) String() string {
66	i.mutex.RLock()
67	defer i.mutex.RUnlock()
68	bytes, err := json.Marshal(i.indexes)
69	if err != nil {
70		return "error marshaling stats"
71	}
72	return string(bytes)
73}
74
75var indexStats *IndexStats
76