1 // Copyright (c) 2019 Cisco and/or its affiliates.
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:
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 // Package statsclient is pure Go implementation of VPP stats API client.
29 "go.fd.io/govpp/adapter"
30 "github.com/fsnotify/fsnotify"
31 "github.com/ftrvxmtrx/fd"
32 logger "github.com/sirupsen/logrus"
36 // DefaultSocketName is default VPP stats socket file path.
37 DefaultSocketName = adapter.DefaultStatsSocket
39 // DefaultSocketRetryPeriod is the time period after the socket availability
41 DefaultSocketRetryPeriod = 50 * time.Millisecond
43 // DefaultSocketRetryTimeout is the maximum time for the stats socket
44 DefaultSocketRetryTimeout = 3 * time.Second
48 // Debug is global variable that determines debug mode
49 Debug = os.Getenv("DEBUG_GOVPP_STATS") != ""
51 // Log is global logger
55 // init initializes global logger, which logs debug level messages to stdout.
59 Log.Level = logger.DebugLevel
60 Log.Debug("govpp/statsclient: enabled debug mode")
64 func debugf(f string, a ...interface{}) {
70 // implements StatsAPI
71 var _ adapter.StatsAPI = (*StatsClient)(nil)
73 // StatsClient is the pure Go implementation for VPP stats API.
74 type StatsClient struct {
76 retryPeriod time.Duration
77 retryTimeout time.Duration
81 // defines the adapter connection state
84 // to quit socket monitor
90 // Option is a StatsClient option
91 type Option func(*StatsClient)
93 // SetSocketRetryPeriod is and optional parameter to define a custom
94 // retry period while waiting for the VPP socket
95 func SetSocketRetryPeriod(t time.Duration) Option {
96 return func(c *StatsClient) {
101 // SetSocketRetryTimeout is and optional parameter to define a custom
102 // timeout while waiting for the VPP socket
103 func SetSocketRetryTimeout(t time.Duration) Option {
104 return func(c *StatsClient) {
109 // NewStatsClient returns a new StatsClient using socket.
110 // If socket is empty string DefaultSocketName is used.
111 func NewStatsClient(socket string, options ...Option) *StatsClient {
113 socket = DefaultSocketName
118 for _, option := range options {
121 if s.retryPeriod == 0 {
122 s.retryPeriod = DefaultSocketRetryPeriod
124 if s.retryTimeout == 0 {
125 s.retryTimeout = DefaultSocketRetryTimeout
130 // Connect to validated VPP stats socket and start monitoring
131 // socket file changes
132 func (sc *StatsClient) Connect() (err error) {
133 if err := sc.waitForSocket(); err != nil {
136 sc.done = make(chan struct{})
137 if sc.statSegment, err = sc.connect(); err != nil {
144 // Disconnect from the socket, unmap shared memory and terminate
146 func (sc *StatsClient) Disconnect() error {
147 if sc.headerData == nil {
150 if err := syscall.Munmap(sc.headerData); err != nil {
151 Log.Debugf("unmapping shared memory failed: %v", err)
152 return fmt.Errorf("unmapping shared memory failed: %v", err)
155 sc.done <- struct{}{}
157 Log.Debugf("successfully unmapped shared memory")
161 func (sc *StatsClient) ListStats(patterns ...string) (entries []adapter.StatIdentifier, err error) {
162 if !sc.isConnected() {
163 return nil, adapter.ErrStatsDisconnected
165 accessEpoch := sc.accessStart()
166 if accessEpoch == 0 {
167 return nil, adapter.ErrStatsAccessFailed
170 entries, err = sc.getIdentifierEntries(patterns...)
175 if !sc.accessEnd(accessEpoch) {
176 return nil, adapter.ErrStatsDataBusy
181 func (sc *StatsClient) DumpStats(patterns ...string) (entries []adapter.StatEntry, err error) {
182 if !sc.isConnected() {
183 return nil, adapter.ErrStatsDisconnected
186 accessEpoch := sc.accessStart()
187 if accessEpoch == 0 {
188 return nil, adapter.ErrStatsAccessFailed
191 entries, err = sc.getStatEntries(patterns...)
196 if !sc.accessEnd(accessEpoch) {
197 return nil, adapter.ErrStatsDataBusy
202 func (sc *StatsClient) PrepareDir(patterns ...string) (*adapter.StatDir, error) {
203 if !sc.isConnected() {
204 return nil, adapter.ErrStatsDisconnected
207 accessEpoch := sc.accessStart()
208 if accessEpoch == 0 {
209 return nil, adapter.ErrStatsAccessFailed
212 entries, err := sc.getStatEntries(patterns...)
217 if !sc.accessEnd(accessEpoch) {
218 return nil, adapter.ErrStatsDataBusy
221 dir := &adapter.StatDir{
229 func (sc *StatsClient) PrepareDirOnIndex(indexes ...uint32) (*adapter.StatDir, error) {
230 if !sc.isConnected() {
231 return nil, adapter.ErrStatsDisconnected
234 accessEpoch := sc.accessStart()
235 if accessEpoch == 0 {
236 return nil, adapter.ErrStatsAccessFailed
238 vector := sc.GetDirectoryVector()
240 return nil, fmt.Errorf("failed to prepare dir on index: directory vector is nil")
242 entries, err := sc.getStatEntriesOnIndex(vector, indexes...)
247 if !sc.accessEnd(accessEpoch) {
248 return nil, adapter.ErrStatsDataBusy
251 dir := &adapter.StatDir{
259 // UpdateDir refreshes directory data for all counters
260 func (sc *StatsClient) UpdateDir(dir *adapter.StatDir) (err error) {
261 if !sc.isConnected() {
262 return adapter.ErrStatsDisconnected
264 epoch, _ := sc.GetEpoch()
265 if dir.Epoch != epoch {
266 return adapter.ErrStatsDirStale
269 accessEpoch := sc.accessStart()
270 if accessEpoch == 0 {
271 return adapter.ErrStatsAccessFailed
273 dirVector := sc.GetDirectoryVector()
274 if dirVector == nil {
277 for i := 0; i < len(dir.Entries); i++ {
278 if err := sc.updateStatOnIndex(&dir.Entries[i], dirVector); err != nil {
282 if !sc.accessEnd(accessEpoch) {
283 return adapter.ErrStatsDataBusy
288 // checks the socket existence and waits for it for the designated
289 // time if it is not available immediately
290 func (sc *StatsClient) waitForSocket() error {
291 if _, err := os.Stat(sc.socket); err != nil {
292 if os.IsNotExist(err) {
294 ticker := time.NewTicker(sc.retryPeriod)
295 timeout := time.After(sc.retryTimeout)
299 if _, err := os.Stat(sc.socket); err == nil {
303 return fmt.Errorf("stats socket file %s is not ready within timeout (after %.2f s) ",
304 sc.socket, time.Since(n).Seconds())
308 return fmt.Errorf("stats socket error: %v", err)
314 // connect to the socket and map it into the memory. According to the
315 // header version info, an appropriate segment handler is returned
316 func (sc *StatsClient) connect() (ss statSegment, err error) {
317 addr := net.UnixAddr{
321 Log.Debugf("connecting to: %v", addr)
323 conn, err := net.DialUnix(addr.Net, nil, &addr)
325 Log.Warnf("connecting to socket %s failed: %s", addr, err)
329 if err := conn.Close(); err != nil {
330 Log.Warnf("closing socket failed: %v", err)
333 Log.Debugf("connected to socket")
335 files, err := fd.Get(conn, 1, nil)
337 return nil, fmt.Errorf("getting file descriptor over socket failed: %v", err)
340 return nil, fmt.Errorf("no files received over socket")
345 if err := file.Close(); err != nil {
346 Log.Warnf("closing file failed: %v", err)
350 info, err := file.Stat()
356 sc.headerData, err = syscall.Mmap(int(file.Fd()), 0, int(size), syscall.PROT_READ, syscall.MAP_SHARED)
358 Log.Debugf("mapping shared memory failed: %v", err)
359 return nil, fmt.Errorf("mapping shared memory failed: %v", err)
361 Log.Debugf("successfully mmapped shared memory segment (size: %v) %v", size, len(sc.headerData))
363 version := getVersion(sc.headerData)
366 ss = newStatSegmentV1(sc.headerData, size)
368 ss = newStatSegmentV2(sc.headerData, size)
370 return nil, fmt.Errorf("stat segment version is not supported: %v (min: %v, max: %v)",
371 version, minVersion, maxVersion)
375 atomic.CompareAndSwapUint32(&sc.connected, 0, 1)
380 // reconnect disconnects from the socket, re-validates it and
382 func (sc *StatsClient) reconnect() (err error) {
383 if err = sc.disconnect(); err != nil {
384 return fmt.Errorf("error disconnecting socket: %v", err)
386 if err = sc.waitForSocket(); err != nil {
387 return fmt.Errorf("error while waiting on socket: %v", err)
389 if sc.statSegment, err = sc.connect(); err != nil {
390 return fmt.Errorf("error connecting socket: %v", err)
395 // disconnect unmaps socket data from the memory and resets the header
396 func (sc *StatsClient) disconnect() error {
397 if !atomic.CompareAndSwapUint32(&sc.connected, 1, 0) {
398 return fmt.Errorf("stats client is already disconnected")
400 if sc.headerData == nil {
403 if err := syscall.Munmap(sc.headerData); err != nil {
404 Log.Debugf("unmapping shared memory failed: %v", err)
405 return fmt.Errorf("unmapping shared memory failed: %v", err)
409 Log.Debugf("successfully unmapped shared memory")
413 func (sc *StatsClient) monitorSocket() {
414 watcher, err := fsnotify.NewWatcher()
416 Log.Errorf("error starting socket monitor: %v", err)
423 case event := <-watcher.Events:
424 if event.Op == fsnotify.Remove && event.Name == sc.socket {
425 if err := sc.reconnect(); err != nil {
426 Log.Errorf("error occurred during socket reconnect: %v", err)
429 case err := <-watcher.Errors:
430 Log.Errorf("socket monitor delivered error event: %v", err)
432 err := watcher.Close()
433 Log.Debugf("socket monitor closed (error: %v)", err)
439 if err := watcher.Add(filepath.Dir(sc.socket)); err != nil {
440 Log.Errorf("failed to add socket address to the watcher: %v", err)
444 // Starts monitoring 'inProgress' field. Returns stats segment
445 // access epoch when completed, or zero value if not finished
446 // within MaxWaitInProgress
447 func (sc *StatsClient) accessStart() (epoch int64) {
450 epoch, inProg := sc.GetEpoch()
452 if time.Since(t) > MaxWaitInProgress {
455 time.Sleep(CheckDelayInProgress)
456 epoch, inProg = sc.GetEpoch()
461 // AccessEnd returns true if stats data reading was finished, false
463 func (sc *StatsClient) accessEnd(accessEpoch int64) bool {
464 epoch, inProgress := sc.GetEpoch()
465 if accessEpoch != epoch || inProgress {
471 // getStatEntries retrieves all stats matching desired patterns, or all stats if no pattern is provided.
472 func (sc *StatsClient) getStatEntries(patterns ...string) (entries []adapter.StatEntry, err error) {
473 vector := sc.GetDirectoryVector()
475 return nil, fmt.Errorf("failed to get stat entries: directory vector is nil")
477 indexes, err := sc.listIndexes(vector, patterns...)
481 return sc.getStatEntriesOnIndex(vector, indexes...)
484 // getIdentifierEntries retrieves all identifiers matching desired patterns, or all identifiers
485 // if no pattern is provided.
486 func (sc *StatsClient) getIdentifierEntries(patterns ...string) (identifiers []adapter.StatIdentifier, err error) {
487 vector := sc.GetDirectoryVector()
489 return nil, fmt.Errorf("failed to get identifier entries: directory vector is nil")
491 indexes, err := sc.listIndexes(vector, patterns...)
495 return sc.getIdentifierEntriesOnIndex(vector, indexes...)
498 // getStatEntriesOnIndex retrieves stats on indexes, or all stats if indexes are not defined.
499 func (sc *StatsClient) getStatEntriesOnIndex(vector dirVector, indexes ...uint32) (entries []adapter.StatEntry, err error) {
500 dirLen := *(*uint32)(vectorLen(vector))
501 for _, index := range indexes {
503 return nil, fmt.Errorf("stat entry index %d out of dir vector length (%d)", index, dirLen)
505 dirPtr, dirName, dirType := sc.GetStatDirOnIndex(vector, index)
506 if len(dirName) == 0 {
509 var t adapter.StatType
510 d := sc.CopyEntryData(dirPtr, ^uint32(0))
514 entries = append(entries, adapter.StatEntry{
515 StatIdentifier: adapter.StatIdentifier{
521 Symlink: dirType == adapter.Symlink,
527 // getIdentifierEntriesOnIndex retrieves identifiers on indexes, or all identifiers if indexes are not defined.
528 func (sc *StatsClient) getIdentifierEntriesOnIndex(vector dirVector, indexes ...uint32) (identifiers []adapter.StatIdentifier, err error) {
529 dirLen := *(*uint32)(vectorLen(vector))
530 for _, index := range indexes {
532 return nil, fmt.Errorf("stat entry index %d out of dir vector length (%d)", index, dirLen)
534 _, dirName, _ := sc.GetStatDirOnIndex(vector, index)
535 if len(dirName) == 0 {
538 identifiers = append(identifiers, adapter.StatIdentifier{
543 return identifiers, nil
546 // listIndexes lists indexes for all stat entries that match any of the regex patterns.
547 func (sc *StatsClient) listIndexes(vector dirVector, patterns ...string) (indexes []uint32, err error) {
548 if len(patterns) == 0 {
549 return sc.listIndexesFunc(vector, nil)
551 var regexes = make([]*regexp.Regexp, len(patterns))
552 for i, pattern := range patterns {
553 r, err := regexp.Compile(pattern)
555 return nil, fmt.Errorf("compiling regexp failed: %v", err)
559 nameMatches := func(name dirName) bool {
560 for _, r := range regexes {
567 return sc.listIndexesFunc(vector, nameMatches)
570 // listIndexesFunc lists stats indexes. The optional function
571 // argument filters returned values or returns all if empty
572 func (sc *StatsClient) listIndexesFunc(vector dirVector, f func(name dirName) bool) (indexes []uint32, err error) {
574 // there is around ~3157 stats, so to avoid too many allocations
575 // we set capacity to 3200 when listing all stats
576 indexes = make([]uint32, 0, 3200)
578 vecLen := *(*uint32)(vectorLen(vector))
579 for i := uint32(0); i < vecLen; i++ {
580 _, dirName, _ := sc.GetStatDirOnIndex(vector, i)
582 if len(dirName) == 0 || !f(dirName) {
586 indexes = append(indexes, i)
592 func (sc *StatsClient) isConnected() bool {
593 return atomic.LoadUint32(&sc.connected) == 1
596 // updateStatOnIndex refreshes the entry data.
597 func (sc *StatsClient) updateStatOnIndex(entry *adapter.StatEntry, vector dirVector) (err error) {
598 dirLen := *(*uint32)(vectorLen(vector))
599 if entry.Index >= dirLen {
600 return fmt.Errorf("stat entry index %d out of dir vector length (%d)", entry.Index, dirLen)
602 dirPtr, dirName, dirType := sc.GetStatDirOnIndex(vector, entry.Index)
603 if len(dirName) == 0 ||
604 !bytes.Equal(dirName, entry.Name) ||
605 dirType != entry.Type ||
609 if err := sc.UpdateEntryData(dirPtr, &entry.Data); err != nil {
610 err = fmt.Errorf("updating stat data for entry %s failed: %v", dirName, err)