File: standardbackend.go

package info (click to toggle)
golang-github-tideland-golib 4.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,144 kB
  • sloc: makefile: 4
file content (561 lines) | stat: -rw-r--r-- 15,042 bytes parent folder | download | duplicates (2)
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// Tideland Go Library - Monitoring - Standard Backend
//
// Copyright (C) 2009-2017 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.

package monitoring

//--------------------
// IMPORTS
//--------------------

import (
	"fmt"
	"sort"
	"time"

	"github.com/tideland/golib/errors"
	"github.com/tideland/golib/logger"
	"github.com/tideland/golib/loop"
)

//--------------------
// CONSTANTS
//--------------------

const (
	cmdReset = iota
	cmdMeasuringPointRead
	cmdMeasuringPointsReadAll
	cmdStaySetVariableRead
	cmdStaySetVariablesReadAll
	cmdDynamicStatusRetrieverRead
	cmdDynamicStatusRetrieversReadAll
)

//--------------------
// COMMAND
//--------------------

// command encapsulated the data for any command.
type command struct {
	opCode   int
	args     interface{}
	respChan chan interface{}
}

// respond allow to simply respond to a command.
func (c *command) respond(v interface{}) {
	c.respChan <- v
}

// ok is a simple positive response.
func (c *command) ok() {
	c.respond(true)
}

// close closes the response channel.
func (c *command) close() {
	close(c.respChan)
}

//--------------------
// MEASURING
//--------------------

// stdMeasuring implements the Measuring interface.
type stdMeasuring struct {
	backend   *stdBackend
	id        string
	startTime time.Time
	duration  time.Duration
}

// EndMEasuring implements the Measuring interface.
func (m *stdMeasuring) EndMeasuring() time.Duration {
	if m.backend == nil {
		return 0
	}
	m.duration = time.Since(m.startTime)
	m.backend.measuringC <- m
	return m.duration
}

//--------------------
// MEASURING POINT
//--------------------

// stdMeasuringPoint implements the MeasuringPoint interface.
type stdMeasuringPoint struct {
	id          string
	count       int64
	minDuration time.Duration
	maxDuration time.Duration
	avgDuration time.Duration
}

// newStdMeasuringPoint creates a new measuring point out of a measuring.
func newStdMeasuringPoint(m *stdMeasuring) *stdMeasuringPoint {
	return &stdMeasuringPoint{
		id:          m.id,
		count:       1,
		minDuration: m.duration,
		maxDuration: m.duration,
		avgDuration: m.duration,
	}
}

// ID implements the MeasuringPoint interface.
func (mp *stdMeasuringPoint) ID() string { return mp.id }

// Count implements the MeasuringPoint interface.
func (mp *stdMeasuringPoint) Count() int64 { return mp.count }

// MinDuration implements the MeasuringPoint interface.
func (mp *stdMeasuringPoint) MinDuration() time.Duration { return mp.minDuration }

// MaxDuration implements the MeasuringPoint interface.
func (mp *stdMeasuringPoint) MaxDuration() time.Duration { return mp.maxDuration }

// AvgDuration implements the MeasuringPoint interface.
func (mp *stdMeasuringPoint) AvgDuration() time.Duration { return mp.avgDuration }

// Uupdate a measuring point with a measuring.
func (mp *stdMeasuringPoint) update(m *stdMeasuring) {
	average := mp.avgDuration.Nanoseconds()
	mp.count++
	if mp.minDuration > m.duration {
		mp.minDuration = m.duration
	}
	if mp.maxDuration < m.duration {
		mp.maxDuration = m.duration
	}
	mp.avgDuration = time.Duration((average + m.duration.Nanoseconds()) / 2)
}

// String implements the Stringer interface.
func (mp *stdMeasuringPoint) String() string {
	return fmt.Sprintf("Measuring Point %q (%dx / min %s / max %s / avg %s)", mp.id, mp.count, mp.minDuration, mp.maxDuration, mp.avgDuration)
}

//--------------------
// STAY-SET VARIABLE
//--------------------

// stdSSVChange represents the change of a stay-set variable.
type stdSSVChange struct {
	id       string
	absolute bool
	variable int64
}

// stdStaySetVariable implements the StaySetVariable interface.
type stdStaySetVariable struct {
	id       string
	count    int64
	actValue int64
	minValue int64
	maxValue int64
	avgValue int64
	total    int64
}

// newStdStaySetVariable creates a new stay-set variable out of a variable.
func newStdStaySetVariable(v *stdSSVChange) *stdStaySetVariable {
	return &stdStaySetVariable{
		id:       v.id,
		count:    1,
		actValue: v.variable,
		minValue: v.variable,
		maxValue: v.variable,
		avgValue: v.variable,
	}
}

// ID implements the StaySetVariable interface.
func (ssv *stdStaySetVariable) ID() string { return ssv.id }

// Count implements the StaySetVariable interface.
func (ssv *stdStaySetVariable) Count() int64 { return ssv.count }

// ActValue implements the StaySetVariable interface.
func (ssv *stdStaySetVariable) ActValue() int64 { return ssv.actValue }

// MinValue implements the StaySetVariable interface.
func (ssv *stdStaySetVariable) MinValue() int64 { return ssv.minValue }

// MaxValue implements the StaySetVariable interface.
func (ssv *stdStaySetVariable) MaxValue() int64 { return ssv.maxValue }

// MinValue implements the StaySetVariable interface.
func (ssv *stdStaySetVariable) AvgValue() int64 { return ssv.avgValue }

// update a stay-set variable with a change.
func (ssv *stdStaySetVariable) update(chg *stdSSVChange) {
	ssv.count++
	if chg.absolute {
		ssv.actValue = chg.variable
	} else {
		ssv.actValue += chg.variable
	}
	ssv.total += chg.variable
	if ssv.minValue > ssv.actValue {
		ssv.minValue = ssv.actValue
	}
	if ssv.maxValue < ssv.actValue {
		ssv.maxValue = ssv.actValue
	}
	ssv.avgValue = ssv.total / ssv.count
}

// String implements the Stringer interface.
func (ssv *stdStaySetVariable) String() string {
	return fmt.Sprintf("Stay-Set Variable %q (%dx / act %d / min %d / max %d / avg %d)",
		ssv.id, ssv.count, ssv.actValue, ssv.minValue, ssv.maxValue, ssv.avgValue)
}

//--------------------
// DYNAMIC STATUS RETRIEVER
//--------------------

// stdRetrieverRegistration allows the registration of a retriever function.
type stdRetrieverRegistration struct {
	id  string
	dsr DynamicStatusRetriever
}

// stdDynamicStatusValue implements the DynamicStatusValue interface.
type stdDynamicStatusValue struct {
	id    string
	value string
}

// ID implements the DynamicStatusValue interface.
func (dsv *stdDynamicStatusValue) ID() string { return dsv.id }

// Value implements the DynamicStatusValue interface.
func (dsv *stdDynamicStatusValue) Value() string { return dsv.value }

// String implements the Stringer interface.
func (dsv *stdDynamicStatusValue) String() string {
	return fmt.Sprintf("Dynamic Status Value %q (value = %q)", dsv.id, dsv.value)
}

//--------------------
// BACKEND
//--------------------

// stdBackend implements the Backend interface.
type stdBackend struct {
	etmFilter              IDFilter
	ssvFilter              IDFilter
	dsrFilter              IDFilter
	etmData                map[string]*stdMeasuringPoint
	ssvData                map[string]*stdStaySetVariable
	dsrData                map[string]DynamicStatusRetriever
	measuringC             chan *stdMeasuring
	ssvChangeC             chan *stdSSVChange
	retrieverRegistrationC chan *stdRetrieverRegistration
	commandC               chan *command
	backend                loop.Loop
}

// NewStandardBackend starts the standard monitoring backend.
func NewStandardBackend() Backend {
	m := &stdBackend{
		measuringC:             make(chan *stdMeasuring, 1024),
		ssvChangeC:             make(chan *stdSSVChange, 1024),
		retrieverRegistrationC: make(chan *stdRetrieverRegistration),
		commandC:               make(chan *command),
	}
	m.backend = loop.GoRecoverable(m.backendLoop, m.checkRecovering, "monitoring backend")
	return m
}

// BeginMeasuring implements the MonitorBackend interface.
func (b *stdBackend) BeginMeasuring(id string) Measuring {
	if b.etmFilter != nil && !b.etmFilter(id) {
		return &stdMeasuring{}
	}
	return &stdMeasuring{b, id, time.Now(), 0}
}

// ReadMeasuringPoint implements the MonitorBackend interface.
func (b *stdBackend) ReadMeasuringPoint(id string) (MeasuringPoint, error) {
	resp, err := b.command(cmdMeasuringPointRead, id)
	if err != nil {
		return nil, err
	}
	return resp.(MeasuringPoint), nil
}

// MeasuringPointsDo implements the MonitorBackend interface.
func (b *stdBackend) MeasuringPointsDo(f func(MeasuringPoint)) error {
	resp, err := b.command(cmdMeasuringPointsReadAll, nil)
	if err != nil {
		return err
	}
	mps := resp.(MeasuringPoints)
	for _, mp := range mps {
		f(mp)
	}
	return nil
}

// SetVariable implements the MonitorBackend interface.
func (b *stdBackend) SetVariable(id string, v int64) {
	if b.ssvFilter != nil && !b.ssvFilter(id) {
		return
	}
	b.ssvChangeC <- &stdSSVChange{id, true, v}
}

// IncrVariable implements the MonitorBackend interface.
func (b *stdBackend) IncrVariable(id string) {
	if b.ssvFilter != nil && !b.ssvFilter(id) {
		return
	}
	b.ssvChangeC <- &stdSSVChange{id, false, 1}
}

// DecrVariable implements the MonitorBackend interface.
func (b *stdBackend) DecrVariable(id string) {
	if b.ssvFilter != nil && !b.ssvFilter(id) {
		return
	}
	b.ssvChangeC <- &stdSSVChange{id, false, -1}
}

// ReadVariable implements the MonitorBackend interface.
func (b *stdBackend) ReadVariable(id string) (StaySetVariable, error) {
	resp, err := b.command(cmdStaySetVariableRead, id)
	if err != nil {
		return nil, err
	}
	return resp.(StaySetVariable), nil
}

// StaySetVariablesDo implements the MonitorBackend interface.
func (b *stdBackend) StaySetVariablesDo(f func(StaySetVariable)) error {
	resp, err := b.command(cmdStaySetVariablesReadAll, nil)
	if err != nil {
		return err
	}
	ssvs := resp.(StaySetVariables)
	for _, ssv := range ssvs {
		f(ssv)
	}
	return nil
}

// Register implements the MonitorBackend interface.
func (b *stdBackend) Register(id string, rf DynamicStatusRetriever) {
	if b.dsrFilter != nil && !b.dsrFilter(id) {
		return
	}
	b.retrieverRegistrationC <- &stdRetrieverRegistration{id, rf}
}

// ReadStatus implements the MonitorBackend interface.
func (b *stdBackend) ReadStatus(id string) (string, error) {
	resp, err := b.command(cmdDynamicStatusRetrieverRead, id)
	if err != nil {
		return "", err
	}
	return resp.(string), nil
}

// DynamicStatusValuesDo implements the MonitorBackend interface.
func (b *stdBackend) DynamicStatusValuesDo(f func(DynamicStatusValue)) error {
	resp, err := b.command(cmdDynamicStatusRetrieversReadAll, f)
	if err != nil {
		return err
	}
	dsvs := resp.(DynamicStatusValues)
	for _, dsv := range dsvs {
		f(dsv)
	}
	return nil
}

// SetMeasuringsFilter implements the MonitorBackend interface.
func (b *stdBackend) SetMeasuringsFilter(f IDFilter) IDFilter {
	old := b.etmFilter
	b.etmFilter = f
	return old
}

// SetVariablesFilter implements the MonitorBackend interface.
func (b *stdBackend) SetVariablesFilter(f IDFilter) IDFilter {
	old := b.ssvFilter
	b.ssvFilter = f
	return old
}

// SetRetrieversFilter implements the MonitorBackend interface.
func (b *stdBackend) SetRetrieversFilter(f IDFilter) IDFilter {
	old := b.dsrFilter
	b.dsrFilter = f
	return old
}

// Reset implements the MonitorBackend interface.
func (b *stdBackend) Reset() error {
	_, err := b.command(cmdReset, nil)
	if err != nil {
		return err
	}
	return nil
}

// Stop implements the MonitorBackend interface.
func (b *stdBackend) Stop() {
	b.backend.Stop()
}

// command sends a command to the system monitor and waits for a response.
func (b *stdBackend) command(opCode int, args interface{}) (interface{}, error) {
	cmd := &command{opCode, args, make(chan interface{})}
	b.commandC <- cmd
	resp, ok := <-cmd.respChan
	if !ok {
		return nil, errors.New(ErrMonitoringPanicked, errorMessages)
	}
	if err, ok := resp.(error); ok {
		return nil, err
	}
	return resp, nil
}

// init the system monitor.
func (b *stdBackend) init() {
	b.etmData = make(map[string]*stdMeasuringPoint)
	b.ssvData = make(map[string]*stdStaySetVariable)
	b.dsrData = make(map[string]DynamicStatusRetriever)
}

// backendLoop runs the system monitor.
func (b *stdBackend) backendLoop(l loop.Loop) error {
	// Init the monitor.
	b.init()
	// Run loop.
	for {
		select {
		case <-l.ShallStop():
			return nil
		case measuring := <-b.measuringC:
			// Received a new measuring.
			if mp, ok := b.etmData[measuring.id]; ok {
				mp.update(measuring)
			} else {
				b.etmData[measuring.id] = newStdMeasuringPoint(measuring)
			}
		case ssvChange := <-b.ssvChangeC:
			// Received a new change.
			if ssv, ok := b.ssvData[ssvChange.id]; ok {
				ssv.update(ssvChange)
			} else {
				b.ssvData[ssvChange.id] = newStdStaySetVariable(ssvChange)
			}
		case registration := <-b.retrieverRegistrationC:
			// Received a new retriever for registration.
			b.dsrData[registration.id] = registration.dsr
		case cmd := <-b.commandC:
			// Received a command to process.
			b.processCommand(cmd)
		}
	}
}

// processCommand handles the received commands of the monitor.
func (b *stdBackend) processCommand(cmd *command) {
	defer cmd.close()
	switch cmd.opCode {
	case cmdReset:
		// Reset monitoring.
		b.init()
		cmd.ok()
	case cmdMeasuringPointRead:
		// Read just one measuring point.
		id := cmd.args.(string)
		if mp, ok := b.etmData[id]; ok {
			// Measuring point found.
			clone := *mp
			cmd.respond(&clone)
		} else {
			// Measuring point does not exist.
			cmd.respond(errors.New(ErrMeasuringPointNotExists, errorMessages, id))
		}
	case cmdMeasuringPointsReadAll:
		// Read all measuring points.
		resp := MeasuringPoints{}
		for _, mp := range b.etmData {
			clone := *mp
			resp = append(resp, &clone)
		}
		sort.Sort(resp)
		cmd.respond(resp)
	case cmdStaySetVariableRead:
		// Read just one stay-set variable.
		id := cmd.args.(string)
		if ssv, ok := b.ssvData[id]; ok {
			// Variable found.
			clone := *ssv
			cmd.respond(&clone)
		} else {
			// Variable does not exist.
			cmd.respond(errors.New(ErrStaySetVariableNotExists, errorMessages, id))
		}
	case cmdStaySetVariablesReadAll:
		// Read all stay-set variables.
		resp := StaySetVariables{}
		for _, mp := range b.ssvData {
			clone := *mp
			resp = append(resp, &clone)
		}
		sort.Sort(resp)
		cmd.respond(resp)
	case cmdDynamicStatusRetrieverRead:
		// Read just one dynamic status value.
		id := cmd.args.(string)
		if dsr, ok := b.dsrData[id]; ok {
			// Dynamic status found.
			v, err := dsr()
			if err != nil {
				cmd.respond(err)
			} else {
				cmd.respond(v)
			}
		} else {
			// Dynamic status does not exist.
			cmd.respond(errors.New(ErrDynamicStatusNotExists, errorMessages, id))
		}
	case cmdDynamicStatusRetrieversReadAll:
		// Read all dynamic status values.
		resp := DynamicStatusValues{}
		for id, dsr := range b.dsrData {
			v, err := dsr()
			if err != nil {
				cmd.respond(err)
			}
			dsv := &stdDynamicStatusValue{id, v}
			resp = append(resp, dsv)
		}
		sort.Sort(resp)
		cmd.respond(resp)
	}
}

// checkRecovering checks if the backend can be recovered.
func (b *stdBackend) checkRecovering(rs loop.Recoverings) (loop.Recoverings, error) {
	if rs.Frequency(12, time.Minute) {
		logger.Errorf("standard monitor cannot be recovered: %v", rs.Last().Reason)
		return nil, errors.New(ErrMonitoringCannotBeRecovered, errorMessages, rs.Last().Reason)
	}
	logger.Warningf("standard monitor recovered: %v", rs.Last().Reason)
	return rs.Trim(12), nil
}

// EOF