github.com/kubewharf/katalyst-core@v0.5.3/pkg/util/timemonitor/time_monitor.go (about)

     1  /*
     2  Copyright 2022 The Katalyst Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package timemonitor
    18  
    19  import (
    20  	"sync"
    21  	"time"
    22  
    23  	"k8s.io/apimachinery/pkg/util/wait"
    24  
    25  	"github.com/kubewharf/katalyst-core/pkg/metrics"
    26  	"github.com/kubewharf/katalyst-core/pkg/util/general"
    27  )
    28  
    29  // TimeMonitor is used to periodically monitor if time.Now().Sub(refreshTime) is greater than durationThreshold
    30  type TimeMonitor struct {
    31  	name              string
    32  	refreshTime       time.Time
    33  	durationThreshold time.Duration
    34  	interval          time.Duration
    35  
    36  	metricName string
    37  	emitter    metrics.MetricEmitter
    38  
    39  	sync.RWMutex
    40  }
    41  
    42  func NewTimeMonitor(name string, durationThreshold, interval time.Duration, metricName string, emitter metrics.MetricEmitter) *TimeMonitor {
    43  	return &TimeMonitor{
    44  		name:              name,
    45  		durationThreshold: durationThreshold,
    46  		interval:          interval,
    47  		metricName:        metricName,
    48  		emitter:           emitter,
    49  	}
    50  }
    51  
    52  func (m *TimeMonitor) UpdateRefreshTime() {
    53  	m.Lock()
    54  	m.refreshTime = time.Now()
    55  	general.Warningf("TimeMonitor: %s update refreshTime: %s", m.name, m.refreshTime)
    56  	m.Unlock()
    57  }
    58  
    59  func (m *TimeMonitor) GetRefreshTime() time.Time {
    60  	m.RLock()
    61  	defer m.RUnlock()
    62  	return m.refreshTime
    63  }
    64  
    65  func (m *TimeMonitor) monitorRefreshTime() {
    66  	refreshTime := m.GetRefreshTime()
    67  
    68  	if refreshTime.IsZero() || time.Since(refreshTime) > m.durationThreshold {
    69  		general.Warningf("TimeMonitor: %s refreshTime stucks, refreshTime: %s", m.name, refreshTime)
    70  		if m.emitter != nil && m.metricName != "" {
    71  			_ = m.emitter.StoreInt64(m.metricName, 1, metrics.MetricTypeNameRaw)
    72  		}
    73  	}
    74  }
    75  
    76  // Run is blocking runned
    77  func (m *TimeMonitor) Run(stopCh <-chan struct{}) {
    78  	wait.Until(m.monitorRefreshTime, m.interval, stopCh)
    79  }