go.ligato.io/vpp-agent/v3@v3.5.0/plugins/configurator/metrics.go (about)

     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 configurator
    16  
    17  import (
    18  	"expvar"
    19  	"sync"
    20  	"time"
    21  
    22  	"go.ligato.io/vpp-agent/v3/pkg/metrics"
    23  )
    24  
    25  var (
    26  	stats   Stats
    27  	statsMu sync.RWMutex
    28  )
    29  
    30  func init() {
    31  	stats.Operations = make(metrics.Calls)
    32  }
    33  
    34  func GetStats() *Stats {
    35  	s := new(Stats)
    36  	statsMu.RLock()
    37  	*s = stats
    38  	statsMu.RUnlock()
    39  	return s
    40  }
    41  
    42  type Stats struct {
    43  	AllOperations metrics.CallStats
    44  	Operations    metrics.Calls
    45  }
    46  
    47  func (s *Stats) getOrCreateOperation(msg string) *metrics.CallStats {
    48  	statsMu.RLock()
    49  	ms, ok := s.Operations[msg]
    50  	statsMu.RUnlock()
    51  	if !ok {
    52  		ms = &metrics.CallStats{Name: msg}
    53  		statsMu.Lock()
    54  		s.Operations[msg] = ms
    55  		statsMu.Unlock()
    56  	}
    57  	return ms
    58  }
    59  
    60  func trackOperation(m string) func() {
    61  	t := time.Now()
    62  	ms := stats.getOrCreateOperation(m)
    63  	return func() {
    64  		took := time.Since(t)
    65  		statsMu.Lock()
    66  		ms.Increment(took)
    67  		stats.AllOperations.Increment(took)
    68  		statsMu.Unlock()
    69  	}
    70  }
    71  
    72  func init() {
    73  	expvar.Publish("configurator-stats", expvar.Func(func() interface{} {
    74  		return GetStats()
    75  	}))
    76  }