feat: api-trace
[govpp.git] / core / trace.go
1 // Copyright (c) 2021 Cisco and/or its affiliates.
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
15 package core
16
17 import (
18         "git.fd.io/govpp.git/api"
19         "sort"
20         "sync"
21         "sync/atomic"
22 )
23
24 // trace is the API tracer object synchronizing and keeping recoded messages.
25 type trace struct {
26         list []*api.Record
27         mux  *sync.Mutex
28
29         isEnabled int32
30 }
31
32 func (c *trace) Enable(enable bool) {
33         if enable && atomic.CompareAndSwapInt32(&c.isEnabled, 0, 1) {
34                 log.Debugf("API trace enabled")
35         } else if atomic.CompareAndSwapInt32(&c.isEnabled, 1, 0) {
36                 log.Debugf("API trace disabled")
37         }
38 }
39
40 func (c *trace) GetRecords() (list []*api.Record) {
41         c.mux.Lock()
42         for _, entry := range c.list {
43                 list = append(list, entry)
44         }
45         c.mux.Unlock()
46         sort.Slice(list, func(i, j int) bool {
47                 return list[i].Timestamp.Before(list[j].Timestamp)
48         })
49         return list
50 }
51
52 func (c *trace) GetRecordsForChannel(chId uint16) (list []*api.Record) {
53         c.mux.Lock()
54         for _, entry := range c.list {
55                 if entry.ChannelID == chId {
56                         list = append(list, entry)
57                 }
58         }
59         c.mux.Unlock()
60         sort.Slice(list, func(i, j int) bool {
61                 return list[i].Timestamp.Before(list[j].Timestamp)
62         })
63         return list
64 }
65
66 func (c *trace) Clear() {
67         c.mux.Lock()
68         c.list = make([]*api.Record, 0)
69         c.mux.Unlock()
70 }