File: types.go

package info (click to toggle)
golang-collectd 0.3.0%2Bgit20181025.f80706d-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 312 kB
  • sloc: makefile: 3
file content (265 lines) | stat: -rw-r--r-- 6,229 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Package api defines data types representing core collectd data types.
package api // import "collectd.org/api"

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"reflect"
	"strconv"
	"strings"
	"time"
)

var (
	// ErrNoDataset is returned when the data set cannot be found.
	ErrNoDataset = errors.New("no such dataset")
)

var (
	dsTypeCounter = reflect.TypeOf(Counter(0))
	dsTypeDerive  = reflect.TypeOf(Derive(0))
	dsTypeGauge   = reflect.TypeOf(Gauge(0))
)

// TypesDB holds the type definitions of one or more types.db(5) files.
type TypesDB struct {
	rows map[string]*DataSet
}

// NewTypesDB parses collectd's types.db file and returns an initialized
// TypesDB object that can be queried.
func NewTypesDB(r io.Reader) (*TypesDB, error) {
	db := &TypesDB{
		rows: make(map[string]*DataSet),
	}

	s := bufio.NewScanner(r)
	for s.Scan() {
		line := s.Text()
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		ds, err := parseSet(s.Text())
		if err != nil {
			continue
		}

		db.rows[ds.Name] = ds
	}

	if err := s.Err(); err != nil {
		return nil, err
	}

	return db, nil
}

// Merge adds all entries in other to db, possibly overwriting entries in db
// with the same name.
func (db *TypesDB) Merge(other *TypesDB) {
	for k, v := range other.rows {
		db.rows[k] = v
	}
}

// DataSet returns the DataSet "typ".
// This is similar to collectd's plugin_get_ds() function.
func (db *TypesDB) DataSet(typ string) (*DataSet, bool) {
	s, ok := db.rows[typ]
	return s, ok
}

// ValueList initializes and returns a new ValueList. The number of values
// arguments must match the number of DataSources in the vl.Type DataSet and
// are converted to []Value using DataSet.Values().
func (db *TypesDB) ValueList(id Identifier, t time.Time, interval time.Duration, values ...interface{}) (*ValueList, error) {
	ds, ok := db.DataSet(id.Type)
	if !ok {
		return nil, ErrNoDataset
	}

	v, err := ds.Values(values...)
	if err != nil {
		return nil, err
	}

	return &ValueList{
		Identifier: id,
		Time:       t,
		Interval:   interval,
		DSNames:    ds.Names(),
		Values:     v,
	}, nil
}

// DataSet defines the metrics of a given "Type", i.e. the name, kind (Derive,
// Gauge, …) and minimum and maximum values.
type DataSet struct {
	Name    string
	Sources []DataSource
}

func parseSet(line string) (*DataSet, error) {
	ds := &DataSet{}

	s := bufio.NewScanner(strings.NewReader(line))
	s.Split(bufio.ScanWords)

	for s.Scan() {
		if ds.Name == "" {
			ds.Name = s.Text()
			continue
		}

		dsrc, err := parseSource(s.Text())
		if err != nil {
			return nil, err
		}

		ds.Sources = append(ds.Sources, *dsrc)
	}

	if err := s.Err(); err != nil {
		return nil, err
	}

	return ds, nil
}

// Names returns a slice of the data source names. This can be used to populate ValueList.DSNames.
func (ds *DataSet) Names() []string {
	var ret []string
	for _, dsrc := range ds.Sources {
		ret = append(ret, dsrc.Name)
	}

	return ret
}

// Values converts the arguments to the Value interface type and returns them
// as a slice. It expects the same number of arguments as it has Sources and
// will return an error if there is a mismatch. Each argument is converted to a
// Counter, Derive or Gauge according to the corresponding DataSource.Type.
func (ds *DataSet) Values(args ...interface{}) ([]Value, error) {
	if len(args) != len(ds.Sources) {
		return nil, fmt.Errorf("len(args) = %d, want %d", len(args), len(ds.Sources))
	}

	var ret []Value
	for i, arg := range args {
		v, err := ds.Sources[i].Value(arg)
		if err != nil {
			return nil, err
		}

		ret = append(ret, v)
	}

	return ret, nil
}

// Check does sanity checking of vl and returns an error if it finds a problem.
// Sanity checking includes checking the concrete types in the Values slice
// against the DataSet's Sources.
func (ds *DataSet) Check(vl *ValueList) error {
	if ds.Name != vl.Type {
		return fmt.Errorf("vl.Type = %q, want %q", vl.Type, ds.Name)
	}

	if len(ds.Sources) != len(vl.Values) {
		return fmt.Errorf("len(vl.Values) = %d, want %d", len(vl.Values), len(ds.Sources))
	}

	if len(ds.Sources) != len(vl.DSNames) {
		return fmt.Errorf("len(vl.DSNames) = %d, want %d", len(vl.DSNames), len(ds.Sources))
	}

	for i, dsrc := range ds.Sources {
		if dsrc.Name != vl.DSNames[i] {
			return fmt.Errorf("vl.DSNames[%d] = %q, want %q", i, vl.DSNames[i], dsrc.Name)
		}

		if reflect.TypeOf(vl.Values[i]) != dsrc.Type {
			return fmt.Errorf("vl.Values[%d] is a %T, want %s", i, vl.Values[i], dsrc.Type.Name())
		}
	}

	return nil
}

// DataSource defines one metric within a "Type" / DataSet. Type is one of
// Counter, Derive and Gauge. Min and Max apply to the rates of Counter and
// Derive types, not the raw incremental value.
type DataSource struct {
	Name     string
	Type     reflect.Type
	Min, Max float64
}

func parseSource(line string) (*DataSource, error) {
	line = strings.TrimSuffix(line, ",")

	f := strings.Split(line, ":")
	if len(f) != 4 {
		return nil, fmt.Errorf("unexpected field count: %d", len(f))
	}

	dsrc := &DataSource{
		Name: f[0],
		Min:  math.NaN(),
		Max:  math.NaN(),
	}

	switch f[1] {
	case "COUNTER":
		dsrc.Type = dsTypeCounter
	case "DERIVE":
		dsrc.Type = dsTypeDerive
	case "GAUGE":
		dsrc.Type = dsTypeGauge
	default:
		return nil, fmt.Errorf("invalid data source type %q", f[1])
	}

	if f[2] != "U" {
		v, err := strconv.ParseFloat(f[2], 64)
		if err != nil {
			return nil, err
		}
		dsrc.Min = v
	}

	if f[3] != "U" {
		v, err := strconv.ParseFloat(f[3], 64)
		if err != nil {
			return nil, err
		}
		dsrc.Max = v
	}

	return dsrc, nil
}

// Value converts arg to a Counter, Derive or Gauge and returns it as the Value
// interface type. Returns an error if arg cannot be converted.
func (dsrc DataSource) Value(arg interface{}) (Value, error) {
	if !reflect.TypeOf(arg).ConvertibleTo(dsrc.Type) {
		return nil, fmt.Errorf("cannot convert %T to %s", arg, dsrc.Type.Name())
	}

	v := reflect.ValueOf(arg).Convert(dsrc.Type)
	switch dsrc.Type {
	case dsTypeCounter:
		return v.Interface().(Counter), nil
	case dsTypeDerive:
		return v.Interface().(Derive), nil
	case dsTypeGauge:
		return v.Interface().(Gauge), nil
	}

	return nil, fmt.Errorf("unexpected data sourc type %s", dsrc.Type.Name())
}