8c5904d8698f207004c58e014691430748f4ceb2
[govpp.git] / adapter / statsclient / statsclient.go
1 // Copyright (c) 2019 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 statsclient is pure Go implementation of VPP stats API client.
16 package statsclient
17
18 import (
19         "bytes"
20         "fmt"
21         "net"
22         "os"
23         "path/filepath"
24         "regexp"
25         "sync/atomic"
26         "syscall"
27         "time"
28
29         "git.fd.io/govpp.git/adapter"
30         "github.com/fsnotify/fsnotify"
31         "github.com/ftrvxmtrx/fd"
32         logger "github.com/sirupsen/logrus"
33 )
34
35 const (
36         // DefaultSocketName is default VPP stats socket file path.
37         DefaultSocketName = adapter.DefaultStatsSocket
38
39         // DefaultSocketRetryPeriod is the time period after the socket availability
40         // will be re-checked
41         DefaultSocketRetryPeriod = 50 * time.Millisecond
42
43         // DefaultSocketRetryTimeout is the maximum time for the stats socket
44         DefaultSocketRetryTimeout = 3 * time.Second
45 )
46
47 var (
48         // Debug is global variable that determines debug mode
49         Debug = os.Getenv("DEBUG_GOVPP_STATS") != ""
50
51         // Log is global logger
52         Log = logger.New()
53 )
54
55 // init initializes global logger, which logs debug level messages to stdout.
56 func init() {
57         Log.Out = os.Stdout
58         if Debug {
59                 Log.Level = logger.DebugLevel
60                 Log.Debug("govpp/statsclient: enabled debug mode")
61         }
62 }
63
64 func debugf(f string, a ...interface{}) {
65         if Debug {
66                 Log.Debugf(f, a...)
67         }
68 }
69
70 // implements StatsAPI
71 var _ adapter.StatsAPI = (*StatsClient)(nil)
72
73 // StatsClient is the pure Go implementation for VPP stats API.
74 type StatsClient struct {
75         socket       string
76         retryPeriod  time.Duration
77         retryTimeout time.Duration
78
79         headerData []byte
80
81         // defines the adapter connection state
82         connected uint32
83
84         // to quit socket monitor
85         done chan struct{}
86
87         statSegment
88 }
89
90 // Option is a StatsClient option
91 type Option func(*StatsClient)
92
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) {
97                 c.retryPeriod = t
98         }
99 }
100
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) {
105                 c.retryTimeout = t
106         }
107 }
108
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 {
112         if socket == "" {
113                 socket = DefaultSocketName
114         }
115         s := &StatsClient{
116                 socket: socket,
117         }
118         for _, option := range options {
119                 option(s)
120         }
121         if s.retryPeriod == 0 {
122                 s.retryPeriod = DefaultSocketRetryPeriod
123         }
124         if s.retryTimeout == 0 {
125                 s.retryTimeout = DefaultSocketRetryTimeout
126         }
127         return s
128 }
129
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 {
134                 return err
135         }
136         sc.done = make(chan struct{})
137         if sc.statSegment, err = sc.connect(); err != nil {
138                 return err
139         }
140         sc.monitorSocket()
141         return nil
142 }
143
144 // Disconnect from the socket, unmap shared memory and terminate
145 // socket monitor
146 func (sc *StatsClient) Disconnect() error {
147         if sc.headerData == nil {
148                 return nil
149         }
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)
153         }
154         sc.headerData = nil
155
156         Log.Debugf("successfully unmapped shared memory")
157         return nil
158 }
159
160 func (sc *StatsClient) ListStats(patterns ...string) (entries []adapter.StatIdentifier, err error) {
161         if !sc.isConnected() {
162                 return nil, adapter.ErrStatsDisconnected
163         }
164         accessEpoch := sc.accessStart()
165         if accessEpoch == 0 {
166                 return nil, adapter.ErrStatsAccessFailed
167         }
168
169         entries, err = sc.getIdentifierEntries(patterns...)
170         if err != nil {
171                 return nil, err
172         }
173
174         if !sc.accessEnd(accessEpoch) {
175                 return nil, adapter.ErrStatsDataBusy
176         }
177         return entries, nil
178 }
179
180 func (sc *StatsClient) DumpStats(patterns ...string) (entries []adapter.StatEntry, err error) {
181         if !sc.isConnected() {
182                 return nil, adapter.ErrStatsDisconnected
183         }
184
185         accessEpoch := sc.accessStart()
186         if accessEpoch == 0 {
187                 return nil, adapter.ErrStatsAccessFailed
188         }
189
190         entries, err = sc.getStatEntries(patterns...)
191         if err != nil {
192                 return nil, err
193         }
194
195         if !sc.accessEnd(accessEpoch) {
196                 return nil, adapter.ErrStatsDataBusy
197         }
198         return entries, nil
199 }
200
201 func (sc *StatsClient) PrepareDir(patterns ...string) (*adapter.StatDir, error) {
202         if !sc.isConnected() {
203                 return nil, adapter.ErrStatsDisconnected
204         }
205
206         accessEpoch := sc.accessStart()
207         if accessEpoch == 0 {
208                 return nil, adapter.ErrStatsAccessFailed
209         }
210
211         entries, err := sc.getStatEntries(patterns...)
212         if err != nil {
213                 return nil, err
214         }
215
216         if !sc.accessEnd(accessEpoch) {
217                 return nil, adapter.ErrStatsDataBusy
218         }
219
220         dir := &adapter.StatDir{
221                 Epoch:   accessEpoch,
222                 Entries: entries,
223         }
224
225         return dir, nil
226 }
227
228 func (sc *StatsClient) PrepareDirOnIndex(indexes ...uint32) (*adapter.StatDir, error) {
229         if !sc.isConnected() {
230                 return nil, adapter.ErrStatsDisconnected
231         }
232
233         accessEpoch := sc.accessStart()
234         if accessEpoch == 0 {
235                 return nil, adapter.ErrStatsAccessFailed
236         }
237         vector := sc.GetDirectoryVector()
238         if vector == nil {
239                 return nil, fmt.Errorf("failed to prepare dir on index: directory vector is nil")
240         }
241         entries, err := sc.getStatEntriesOnIndex(vector, indexes...)
242         if err != nil {
243                 return nil, err
244         }
245
246         if !sc.accessEnd(accessEpoch) {
247                 return nil, adapter.ErrStatsDataBusy
248         }
249
250         dir := &adapter.StatDir{
251                 Epoch:   accessEpoch,
252                 Entries: entries,
253         }
254
255         return dir, nil
256 }
257
258 // UpdateDir refreshes directory data for all counters
259 func (sc *StatsClient) UpdateDir(dir *adapter.StatDir) (err error) {
260         if !sc.isConnected() {
261                 return adapter.ErrStatsDisconnected
262         }
263         epoch, _ := sc.GetEpoch()
264         if dir.Epoch != epoch {
265                 return adapter.ErrStatsDirStale
266         }
267
268         accessEpoch := sc.accessStart()
269         if accessEpoch == 0 {
270                 return adapter.ErrStatsAccessFailed
271         }
272         dirVector := sc.GetDirectoryVector()
273         if dirVector == nil {
274                 return err
275         }
276         for i := 0; i < len(dir.Entries); i++ {
277                 if err := sc.updateStatOnIndex(&dir.Entries[i], dirVector); err != nil {
278                         return err
279                 }
280         }
281         if !sc.accessEnd(accessEpoch) {
282                 return adapter.ErrStatsDataBusy
283         }
284         return nil
285 }
286
287 // checks the socket existence and waits for it for the designated
288 // time if it is not available immediately
289 func (sc *StatsClient) waitForSocket() error {
290         if _, err := os.Stat(sc.socket); err != nil {
291                 if os.IsNotExist(err) {
292                         n := time.Now()
293                         ticker := time.NewTicker(sc.retryPeriod)
294                         timeout := time.After(sc.retryTimeout)
295                         for {
296                                 select {
297                                 case <-ticker.C:
298                                         if _, err := os.Stat(sc.socket); err == nil {
299                                                 return nil
300                                         }
301                                 case <-timeout:
302                                         return fmt.Errorf("stats socket file %s is not ready within timeout (after %.2f s) ",
303                                                 sc.socket, time.Since(n).Seconds())
304                                 }
305                         }
306                 } else {
307                         return fmt.Errorf("stats socket error: %v", err)
308                 }
309         }
310         return nil
311 }
312
313 // connect to the socket and map it into the memory. According to the
314 // header version info, an appropriate segment handler is returned
315 func (sc *StatsClient) connect() (ss statSegment, err error) {
316         addr := net.UnixAddr{
317                 Net:  "unixpacket",
318                 Name: sc.socket,
319         }
320         Log.Debugf("connecting to: %v", addr)
321
322         conn, err := net.DialUnix(addr.Net, nil, &addr)
323         if err != nil {
324                 Log.Warnf("connecting to socket %s failed: %s", addr, err)
325                 return nil, err
326         }
327         defer func() {
328                 if err := conn.Close(); err != nil {
329                         Log.Warnf("closing socket failed: %v", err)
330                 }
331         }()
332         Log.Debugf("connected to socket")
333
334         files, err := fd.Get(conn, 1, nil)
335         if err != nil {
336                 return nil, fmt.Errorf("getting file descriptor over socket failed: %v", err)
337         }
338         if len(files) == 0 {
339                 return nil, fmt.Errorf("no files received over socket")
340         }
341
342         file := files[0]
343         defer func() {
344                 if err := file.Close(); err != nil {
345                         Log.Warnf("closing file failed: %v", err)
346                 }
347         }()
348
349         info, err := file.Stat()
350         if err != nil {
351                 return nil, err
352         }
353         size := info.Size()
354
355         sc.headerData, err = syscall.Mmap(int(file.Fd()), 0, int(size), syscall.PROT_READ, syscall.MAP_SHARED)
356         if err != nil {
357                 Log.Debugf("mapping shared memory failed: %v", err)
358                 return nil, fmt.Errorf("mapping shared memory failed: %v", err)
359         }
360         Log.Debugf("successfully mmapped shared memory segment (size: %v) %v", size, len(sc.headerData))
361
362         version := getVersion(sc.headerData)
363         switch version {
364         case 1:
365                 ss = newStatSegmentV1(sc.headerData, size)
366         case 2:
367                 ss = newStatSegmentV2(sc.headerData, size)
368         default:
369                 return nil, fmt.Errorf("stat segment version is not supported: %v (min: %v, max: %v)",
370                         version, minVersion, maxVersion)
371         }
372
373         // set connected
374         atomic.CompareAndSwapUint32(&sc.connected, 0, 1)
375
376         return ss, nil
377 }
378
379 // reconnect disconnects from the socket, re-validates it and
380 // connects again
381 func (sc *StatsClient) reconnect() (err error) {
382         if err = sc.disconnect(); err != nil {
383                 return fmt.Errorf("error disconnecting socket: %v", err)
384         }
385         if err = sc.waitForSocket(); err != nil {
386                 return fmt.Errorf("error while waiting on socket: %v", err)
387         }
388         if sc.statSegment, err = sc.connect(); err != nil {
389                 return fmt.Errorf("error connecting socket: %v", err)
390         }
391         return nil
392 }
393
394 // disconnect unmaps socket data from the memory and resets the header
395 func (sc *StatsClient) disconnect() error {
396         if !atomic.CompareAndSwapUint32(&sc.connected, 1, 0) {
397                 return fmt.Errorf("stats client is already disconnected")
398         }
399         if sc.headerData == nil {
400                 return nil
401         }
402         if err := syscall.Munmap(sc.headerData); err != nil {
403                 Log.Debugf("unmapping shared memory failed: %v", err)
404                 return fmt.Errorf("unmapping shared memory failed: %v", err)
405         }
406         sc.headerData = nil
407
408         Log.Debugf("successfully unmapped shared memory")
409         return nil
410 }
411
412 func (sc *StatsClient) monitorSocket() {
413         watcher, err := fsnotify.NewWatcher()
414         if err != nil {
415                 Log.Errorf("error starting socket monitor: %v", err)
416                 return
417         }
418
419         go func() {
420                 for {
421                         select {
422                         case event := <-watcher.Events:
423                                 if event.Op == fsnotify.Remove && event.Name == sc.socket {
424                                         if err := sc.reconnect(); err != nil {
425                                                 Log.Errorf("error occurred during socket reconnect: %v", err)
426                                         }
427                                 }
428                         case err := <-watcher.Errors:
429                                 Log.Errorf("socket monitor delivered error event: %v", err)
430                         case <-sc.done:
431                                 err := watcher.Close()
432                                 Log.Debugf("socket monitor closed (error: %v)", err)
433                                 return
434                         }
435                 }
436         }()
437
438         if err := watcher.Add(filepath.Dir(sc.socket)); err != nil {
439                 Log.Errorf("failed to add socket address to the watcher: %v", err)
440         }
441 }
442
443 // Starts monitoring 'inProgress' field. Returns stats segment
444 // access epoch when completed, or zero value if not finished
445 // within MaxWaitInProgress
446 func (sc *StatsClient) accessStart() (epoch int64) {
447         t := time.Now()
448
449         epoch, inProg := sc.GetEpoch()
450         for inProg {
451                 if time.Since(t) > MaxWaitInProgress {
452                         return int64(0)
453                 }
454                 time.Sleep(CheckDelayInProgress)
455                 epoch, inProg = sc.GetEpoch()
456         }
457         return epoch
458 }
459
460 // AccessEnd returns true if stats data reading was finished, false
461 // otherwise
462 func (sc *StatsClient) accessEnd(accessEpoch int64) bool {
463         epoch, inProgress := sc.GetEpoch()
464         if accessEpoch != epoch || inProgress {
465                 return false
466         }
467         return true
468 }
469
470 // getStatEntries retrieves all stats matching desired patterns, or all stats if no pattern is provided.
471 func (sc *StatsClient) getStatEntries(patterns ...string) (entries []adapter.StatEntry, err error) {
472         vector := sc.GetDirectoryVector()
473         if vector == nil {
474                 return nil, fmt.Errorf("failed to get stat entries: directory vector is nil")
475         }
476         indexes, err := sc.listIndexes(vector, patterns...)
477         if err != nil {
478                 return nil, err
479         }
480         return sc.getStatEntriesOnIndex(vector, indexes...)
481 }
482
483 // getIdentifierEntries retrieves all identifiers matching desired patterns, or all identifiers
484 // if no pattern is provided.
485 func (sc *StatsClient) getIdentifierEntries(patterns ...string) (identifiers []adapter.StatIdentifier, err error) {
486         vector := sc.GetDirectoryVector()
487         if vector == nil {
488                 return nil, fmt.Errorf("failed to get identifier entries: directory vector is nil")
489         }
490         indexes, err := sc.listIndexes(vector, patterns...)
491         if err != nil {
492                 return nil, err
493         }
494         return sc.getIdentifierEntriesOnIndex(vector, indexes...)
495 }
496
497 // getStatEntriesOnIndex retrieves stats on indexes, or all stats if indexes are not defined.
498 func (sc *StatsClient) getStatEntriesOnIndex(vector dirVector, indexes ...uint32) (entries []adapter.StatEntry, err error) {
499         dirLen := *(*uint32)(vectorLen(vector))
500         for _, index := range indexes {
501                 if index >= dirLen {
502                         return nil, fmt.Errorf("stat entry index %d out of dir vector length (%d)", index, dirLen)
503                 }
504                 dirPtr, dirName, dirType := sc.GetStatDirOnIndex(vector, index)
505                 if len(dirName) == 0 {
506                         return
507                 }
508                 var t adapter.StatType
509                 d := sc.CopyEntryData(dirPtr, ^uint32(0))
510                 if d != nil {
511                         t = d.Type()
512                 }
513                 entries = append(entries, adapter.StatEntry{
514                         StatIdentifier: adapter.StatIdentifier{
515                                 Index: index,
516                                 Name:  dirName,
517                         },
518                         Type:    t,
519                         Data:    d,
520                         Symlink: adapter.StatType(dirType) == adapter.Symlink,
521                 })
522         }
523         return entries, nil
524 }
525
526 // getIdentifierEntriesOnIndex retrieves identifiers on indexes, or all identifiers if indexes are not defined.
527 func (sc *StatsClient) getIdentifierEntriesOnIndex(vector dirVector, indexes ...uint32) (identifiers []adapter.StatIdentifier, err error) {
528         dirLen := *(*uint32)(vectorLen(vector))
529         for _, index := range indexes {
530                 if index >= dirLen {
531                         return nil, fmt.Errorf("stat entry index %d out of dir vector length (%d)", index, dirLen)
532                 }
533                 _, dirName, _ := sc.GetStatDirOnIndex(vector, index)
534                 if len(dirName) == 0 {
535                         return
536                 }
537                 identifiers = append(identifiers, adapter.StatIdentifier{
538                         Index: index,
539                         Name:  dirName,
540                 })
541         }
542         return identifiers, nil
543 }
544
545 // listIndexes lists indexes for all stat entries that match any of the regex patterns.
546 func (sc *StatsClient) listIndexes(vector dirVector, patterns ...string) (indexes []uint32, err error) {
547         if len(patterns) == 0 {
548                 return sc.listIndexesFunc(vector, nil)
549         }
550         var regexes = make([]*regexp.Regexp, len(patterns))
551         for i, pattern := range patterns {
552                 r, err := regexp.Compile(pattern)
553                 if err != nil {
554                         return nil, fmt.Errorf("compiling regexp failed: %v", err)
555                 }
556                 regexes[i] = r
557         }
558         nameMatches := func(name dirName) bool {
559                 for _, r := range regexes {
560                         if r.Match(name) {
561                                 return true
562                         }
563                 }
564                 return false
565         }
566         return sc.listIndexesFunc(vector, nameMatches)
567 }
568
569 // listIndexesFunc lists stats indexes. The optional function
570 // argument filters returned values or returns all if empty
571 func (sc *StatsClient) listIndexesFunc(vector dirVector, f func(name dirName) bool) (indexes []uint32, err error) {
572         if f == nil {
573                 // there is around ~3157 stats, so to avoid too many allocations
574                 // we set capacity to 3200 when listing all stats
575                 indexes = make([]uint32, 0, 3200)
576         }
577         vecLen := *(*uint32)(vectorLen(vector))
578         for i := uint32(0); i < vecLen; i++ {
579                 _, dirName, _ := sc.GetStatDirOnIndex(vector, i)
580                 if f != nil {
581                         if len(dirName) == 0 || !f(dirName) {
582                                 continue
583                         }
584                 }
585                 indexes = append(indexes, i)
586         }
587
588         return indexes, nil
589 }
590
591 func (sc *StatsClient) isConnected() bool {
592         return atomic.LoadUint32(&sc.connected) == 1
593 }
594
595 // updateStatOnIndex refreshes the entry data.
596 func (sc *StatsClient) updateStatOnIndex(entry *adapter.StatEntry, vector dirVector) (err error) {
597         dirLen := *(*uint32)(vectorLen(vector))
598         if entry.Index >= dirLen {
599                 return fmt.Errorf("stat entry index %d out of dir vector length (%d)", entry.Index, dirLen)
600         }
601         dirPtr, dirName, dirType := sc.GetStatDirOnIndex(vector, entry.Index)
602         if len(dirName) == 0 ||
603                 !bytes.Equal(dirName, entry.Name) ||
604                 adapter.StatType(dirType) != entry.Type ||
605                 entry.Data == nil {
606                 return nil
607         }
608         if err := sc.UpdateEntryData(dirPtr, &entry.Data); err != nil {
609                 err = fmt.Errorf("updating stat data for entry %s failed: %v", dirName, err)
610         }
611         return
612 }