summaryrefslogtreecommitdiffstats
path: root/adapter/statsclient/statseg_v2.go
blob: 0780248a3c3aa6e965d03899ac50e90fbb9bd09c (plain)
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//  Copyright (c) 2020 Cisco and/or its affiliates.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at:
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

package statsclient

import (
	"bytes"
	"encoding/binary"
	"sync/atomic"
	"unsafe"

	"git.fd.io/govpp.git/adapter"
)

type statSegmentV2 struct {
	sharedHeader []byte
	memorySize   int64
}

type sharedHeaderV2 struct {
	version     uint64
	base        unsafe.Pointer
	epoch       int64
	inProgress  int64
	dirVector   unsafe.Pointer
	errorVector unsafe.Pointer
}

type statSegDirectoryEntryV2 struct {
	directoryType dirType
	// unionData can represent:
	// - symlink indexes
	// - index
	// - value
	// - pointer to data
	unionData uint64
	name      [128]byte
}

func newStatSegmentV2(data []byte, size int64) *statSegmentV2 {
	return &statSegmentV2{
		sharedHeader: data,
		memorySize:   size,
	}
}

func (ss *statSegmentV2) loadSharedHeader(b []byte) (header sharedHeaderV2) {
	h := (*sharedHeaderV2)(unsafe.Pointer(&b[0]))
	return sharedHeaderV2{
		version:     atomic.LoadUint64(&h.version),
		base:        atomic.LoadPointer(&h.base),
		epoch:       atomic.LoadInt64(&h.epoch),
		inProgress:  atomic.LoadInt64(&h.inProgress),
		dirVector:   atomic.LoadPointer(&h.dirVector),
		errorVector: atomic.LoadPointer(&h.errorVector),
	}
}

func (ss *statSegmentV2) GetDirectoryVector() dirVector {
	header := ss.loadSharedHeader(ss.sharedHeader)
	return ss.adjust(dirVector(&header.dirVector))
}

func (ss *statSegmentV2) GetStatDirOnIndex(v dirVector, index uint32) (dirSegment, dirName, dirType) {
	statSegDir := dirSegment(uintptr(v) + uintptr(index)*unsafe.Sizeof(statSegDirectoryEntryV2{}))
	dir := (*statSegDirectoryEntryV2)(statSegDir)
	var name []byte
	for n := 0; n < len(dir.name); n++ {
		if dir.name[n] == 0 {
			name = dir.name[:n]
			break
		}
	}
	return statSegDir, name, dir.directoryType
}

func (ss *statSegmentV2) GetEpoch() (int64, bool) {
	sh := ss.loadSharedHeader(ss.sharedHeader)
	return sh.epoch, sh.inProgress != 0
}

func (ss *statSegmentV2) CopyEntryData(segment dirSegment, index uint32) adapter.Stat {
	dirEntry := (*statSegDirectoryEntryV2)(segment)
	typ := adapter.StatType(dirEntry.directoryType)
	// skip zero pointer value
	if typ != statDirScalarIndex && typ != statDirEmpty && dirEntry.unionData == 0 {
		debugf("data pointer not defined for %s", dirEntry.name)
		return nil
	}

	switch typ {
	case statDirScalarIndex:
		return adapter.ScalarStat(dirEntry.unionData)

	case statDirErrorIndex:
		dirVector := ss.getErrorVector()
		if dirVector == nil {
			debugf("error vector pointer is out of range for %s", dirEntry.name)
			return nil
		}
		vecLen := *(*uint32)(vectorLen(dirVector))
		var errData []adapter.Counter
		for i := uint32(0); i < vecLen; i++ {
			cb := statSegPointer(dirVector, uintptr(i+1)*unsafe.Sizeof(uint64(0)))
			cbVal := ss.adjust(vectorLen(cb))
			if cbVal == nil {
				debugf("error counter pointer out of range")
				continue
			}
			offset := uintptr(dirEntry.unionData) * unsafe.Sizeof(adapter.Counter(0))
			val := *(*adapter.Counter)(statSegPointer(cbVal, offset))
			errData = append(errData, val)
		}
		return adapter.ErrorStat(errData)

	case statDirCounterVectorSimple:
		dirVector := ss.adjust(dirVector(&dirEntry.unionData))
		if dirVector == nil {
			debugf("data vector pointer is out of range for %s", dirEntry.name)
			return nil
		}
		vecLen := *(*uint32)(vectorLen(dirVector))
		data := make([][]adapter.Counter, vecLen)
		for i := uint32(0); i < vecLen; i++ {
			counterVectorOffset := statSegPointer(dirVector, uintptr(i+1)*unsafe.Sizeof(uint64(0)))
			counterVector := ss.adjust(vectorLen(counterVectorOffset))
			if counterVector == nil {
				debugf("counter (vector simple) pointer out of range")
				continue
			}
			counterVectorLength := *(*uint32)(vectorLen(counterVector))
			if index == ^uint32(0) {
				data[i] = make([]adapter.Counter, counterVectorLength)
				for j := uint32(0); j < counterVectorLength; j++ {
					offset := uintptr(j) * unsafe.Sizeof(adapter.Counter(0))
					data[i][j] = *(*adapter.Counter)(statSegPointer(counterVector, offset))
				}
			} else {
				data[i] = make([]adapter.Counter, 1) // expect single value
				for j := uint32(0); j < counterVectorLength; j++ {
					offset := uintptr(j) * unsafe.Sizeof(adapter.Counter(0))
					if index == j {
						data[i][0] = *(*adapter.Counter)(statSegPointer(counterVector, offset))
						break
					}
				}
			}
		}
		return adapter.SimpleCounterStat(data)

	case statDirCounterVectorCombined:
		dirVector := ss.adjust(dirVector(&dirEntry.unionData))
		if dirVector == nil {
			debugf("data vector pointer is out of range for %s", dirEntry.name)
			return nil
		}
		vecLen := *(*uint32)(vectorLen(dirVector))
		data := make([][]adapter.CombinedCounter, vecLen)
		for i := uint32(0); i < vecLen; i++ {
			counterVectorOffset := statSegPointer(dirVector, uintptr(i+1)*unsafe.Sizeof(uint64(0)))
			counterVector := ss.adjust(vectorLen(counterVectorOffset))
			if counterVector == nil {
				debugf("counter (vector combined) pointer out of range")
				continue
			}
			counterVectorLength := *(*uint32)(vectorLen(counterVector))
			if index == ^uint32(0) {
				data[i] = make([]adapter.CombinedCounter, counterVectorLength)
				for j := uint32(0); j < counterVectorLength; j++ {
					offset := uintptr(j) * unsafe.Sizeof(adapter.CombinedCounter{})
					data[i][j] = *(*adapter.CombinedCounter)(statSegPointer(counterVector, offset))
				}
			} else {
				data[i] = make([]adapter.CombinedCounter, 1) // expect single value pair
				for j := uint32(0); j < counterVectorLength; j++ {
					offset := uintptr(j) * unsafe.Sizeof(adapter.CombinedCounter{})
					if index == j {
						data[i][0] = *(*adapter.CombinedCounter)(statSegPointer(counterVector, offset))
						break
					}
				}
			}
		}
		return adapter.CombinedCounterStat(data)

	case statDirNameVector:
		dirVector := ss.adjust(dirVector(&dirEntry.unionData))
		if dirVector == nil {
			debugf("data vector pointer is out of range for %s", dirEntry.name)
			return nil
		}
		vecLen := *(*uint32)(vectorLen(dirVector))
		data := make([]adapter.Name, vecLen)
		for i := uint32(0); i < vecLen; i++ {
			nameVectorOffset := statSegPointer(dirVector, uintptr(i+1)*unsafe.Sizeof(uint64(0)))
			if uintptr(nameVectorOffset) == 0 {
				debugf("name vector out of range for %s (%v)", dirEntry.name, i)
				continue
			}
			nameVector := ss.adjust(vectorLen(nameVectorOffset))
			if nameVector == nil {
				debugf("name data pointer out of range")
				continue
			}
			nameVectorLen := *(*uint32)(vectorLen(nameVector))
			name := make([]byte, 0, nameVectorLen)
			for j := uint32(0); j < nameVectorLen; j++ {
				offset := uintptr(j) * unsafe.Sizeof(byte(0))
				value := *(*byte)(statSegPointer(nameVector, offset))
				if value > 0 {
					name = append(name, value)
				}
			}
			data[i] = name
		}
		return adapter.NameStat(data)

	case statDirEmpty:
		return adapter.EmptyStat("<none>")
		// no-op

	case statDirSymlink:
		// prevent recursion loops
		if index != ^uint32(0) {
			debugf("received symlink with defined item index")
			return nil
		}
		i1, i2 := ss.getSymlinkIndexes(dirEntry)
		// use first index to get the stats directory the symlink points to
		header := ss.loadSharedHeader(ss.sharedHeader)
		dirVector := ss.adjust(dirVector(&header.dirVector))
		statSegDir2 := dirSegment(uintptr(dirVector) + uintptr(i1)*unsafe.Sizeof(statSegDirectoryEntryV2{}))

		// retry with actual stats segment and use second index to get
		// stats for the required item
		return ss.CopyEntryData(statSegDir2, i2)

	default:
		// TODO: monitor occurrences with metrics
		debugf("Unknown type %d for stat entry: %q", dirEntry.directoryType, dirEntry.name)
	}
	return nil
}

func (ss *statSegmentV2) UpdateEntryData(segment dirSegment, stat *adapter.Stat) error {
	dirEntry := (*statSegDirectoryEntryV2)(segment)
	switch (*stat).(type) {
	case adapter.ScalarStat:
		*stat = adapter.ScalarStat(dirEntry.unionData)

	case adapter.ErrorStat:
		dirVector := ss.getErrorVector()
		if dirVector == nil {
			debugf("error vector pointer is out of range for %s", dirEntry.name)
			return nil
		}
		vecLen := *(*uint32)(vectorLen(dirVector))
		var errData []adapter.Counter
		for i := uint32(0); i < vecLen; i++ {
			cb := statSegPointer(dirVector, uintptr(i+1)*unsafe.Sizeof(uint64(0)))
			cbVal := ss.adjust(vectorLen(cb))
			if cbVal == nil {
				debugf("error counter pointer out of range")
				continue
			}
			offset := uintptr(dirEntry.unionData) * unsafe.Sizeof(adapter.Counter(0))
			val := *(*adapter.Counter)(statSegPointer(cbVal, offset))
			errData = append(errData, val)
		}
		*stat = adapter.ErrorStat(errData)

	case adapter.SimpleCounterStat:
		dirVector := ss.adjust(dirVector(&dirEntry.unionData))
		if dirVector == nil {
			debugf("data vector pointer is out of range for %s", dirEntry.name)
			return nil
		}
		vecLen := *(*uint32)(vectorLen(dirVector))
		data := (*stat).(adapter.SimpleCounterStat)
		if uint32(len(data)) != vecLen {
			return ErrStatDataLenIncorrect
		}
		for i := uint32(0); i < vecLen; i++ {
			counterVectorOffset := statSegPointer(dirVector, uintptr(i+1)*unsafe.Sizeof(uint64(0)))
			counterVector := ss.adjust(vectorLen(counterVectorOffset))
			if counterVector == nil {
				debugf("counter (vector simple) pointer out of range")
				continue
			}
			counterVectorLength := *(*uint32)(vectorLen(counterVector))
			data[i] = make([]adapter.Counter, counterVectorLength)
			for j := uint32(0); j < counterVectorLength; j++ {
				offset := uintptr(j) * unsafe.Sizeof(adapter.Counter(0))
				val := *(*adapter.Counter)(statSegPointer(counterVector, offset))
				data[i][j] = val
			}
		}

	case adapter.CombinedCounterStat:
		dirVector := ss.adjust(dirVector(&dirEntry.unionData))
		if dirVector == nil {
			debugf("data vector pointer is out of range for %s", dirEntry.name)
			return nil
		}
		vecLen := *(*uint32)(vectorLen(dirVector))
		data := (*stat).(adapter.CombinedCounterStat)
		for i := uint32(0); i < vecLen; i++ {
			counterVectorOffset := statSegPointer(dirVector, uintptr(i+1)*unsafe.Sizeof(uint64(0)))
			counterVector := ss.adjust(vectorLen(counterVectorOffset))
			if counterVector == nil {
				debugf("counter (vector combined) pointer out of range")
				continue
			}
			counterVectorLength := *(*uint32)(vectorLen(counterVector))
			data[i] = make([]adapter.CombinedCounter, counterVectorLength)
			for j := uint32(0); j < counterVectorLength; j++ {
				offset := uintptr(j) * unsafe.Sizeof(adapter.CombinedCounter{})
				val := *(*adapter.CombinedCounter)(statSegPointer(counterVector, offset))
				data[i][j] = val
			}
		}

	case adapter.NameStat:
		dirVector := ss.adjust(dirVector(&dirEntry.unionData))
		if dirVector == nil {
			debugf("data vector pointer is out of range for %s", dirEntry.name)
			return nil
		}
		vecLen := *(*uint32)(vectorLen(dirVector))
		data := (*stat).(adapter.NameStat)
		for i := uint32(0); i < vecLen; i++ {
			nameVectorOffset := statSegPointer(dirVector, uintptr(i+1)*unsafe.Sizeof(uint64(0)))
			if uintptr(nameVectorOffset) == 0 {
				debugf("name vector out of range for %s (%v)", dirEntry.name, i)
				continue
			}
			nameVector := ss.adjust(vectorLen(nameVectorOffset))
			if nameVector == nil {
				debugf("name data pointer out of range")
				continue
			}
			nameVectorLen := *(*uint32)(vectorLen(nameVector))
			nameData := data[i]
			if uint32(len(nameData))+1 != nameVectorLen {
				return ErrStatDataLenIncorrect
			}
			for j := uint32(0); j < nameVectorLen; j++ {
				offset := uintptr(j) * unsafe.Sizeof(byte(0))
				value := *(*byte)(statSegPointer(nameVector, offset))
				if value == 0 {
					break
				}
				nameData[j] = value
			}
		}

	default:
		if Debug {
			Log.Debugf("Unrecognized stat type %T for stat entry: %v", stat, dirEntry.name)
		}
	}
	return nil
}

// Adjust data pointer using shared header and base and return
// the pointer to a data segment
func (ss *statSegmentV2) adjust(data dirVector) dirVector {
	header := ss.loadSharedHeader(ss.sharedHeader)
	adjusted := dirVector(uintptr(unsafe.Pointer(&ss.sharedHeader[0])) +
		uintptr(*(*uint64)(data)) - uintptr(*(*uint64)(unsafe.Pointer(&header.base))))
	if uintptr(unsafe.Pointer(&ss.sharedHeader[len(ss.sharedHeader)-1])) <= uintptr(adjusted) ||
		uintptr(unsafe.Pointer(&ss.sharedHeader[0])) >= uintptr(adjusted) {
		return nil
	}
	return adjusted
}

func (ss *statSegmentV2) getErrorVector() dirVector {
	header := ss.loadSharedHeader(ss.sharedHeader)
	return ss.adjust(dirVector(&header.errorVector))
}

func (ss *statSegmentV2) getSymlinkIndexes(dirEntry *statSegDirectoryEntryV2) (index1, index2 uint32) {
	var b bytes.Buffer
	if err := binary.Write(&b, binary.LittleEndian, dirEntry.unionData); err != nil {
		debugf("error getting symlink indexes for %s: %v", dirEntry.name, err)
		return
	}
	if len(b.Bytes()) != 8 {
		debugf("incorrect symlink union data length for %s: expected 8, got %d", dirEntry.name, len(b.Bytes()))
		return
	}
	for i := range b.Bytes()[:4] {
		index1 += uint32(b.Bytes()[i]) << (uint32(i) * 8)
	}
	for i := range b.Bytes()[4:] {
		index2 += uint32(b.Bytes()[i+4]) << (uint32(i) * 8)
	}
	return
}