github.com/TeaOSLab/EdgeNode@v1.3.8/internal/metrics/task_base.go (about)

     1  // Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package metrics
     4  
     5  import (
     6  	"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
     7  	"sync"
     8  	"sync/atomic"
     9  )
    10  
    11  type BaseTask struct {
    12  	itemConfig *serverconfigs.MetricItemConfig
    13  	isLoaded   bool
    14  	isStopped  bool
    15  
    16  	statsMap    map[string]*Stat // 待写入队列,hash => *Stat
    17  	statsLocker sync.RWMutex
    18  }
    19  
    20  // Add 添加数据
    21  func (this *BaseTask) Add(obj MetricInterface) {
    22  	if this.isStopped || !this.isLoaded {
    23  		return
    24  	}
    25  
    26  	var keys = []string{}
    27  	for _, key := range this.itemConfig.Keys {
    28  		var k = obj.MetricKey(key)
    29  
    30  		// 忽略499状态
    31  		if key == "${status}" && k == "499" {
    32  			return
    33  		}
    34  
    35  		keys = append(keys, k)
    36  	}
    37  
    38  	v, ok := obj.MetricValue(this.itemConfig.Value)
    39  	if !ok {
    40  		return
    41  	}
    42  
    43  	var hash = UniqueKey(obj.MetricServerId(), keys, this.itemConfig.CurrentTime(), this.itemConfig.Version, this.itemConfig.Id)
    44  	var countItems int
    45  	this.statsLocker.RLock()
    46  	oldStat, ok := this.statsMap[hash]
    47  	if !ok {
    48  		countItems = len(this.statsMap)
    49  	}
    50  	this.statsLocker.RUnlock()
    51  	if ok {
    52  		atomic.AddInt64(&oldStat.Value, 1)
    53  	} else {
    54  		// 防止过载
    55  		if countItems < MaxQueueSize {
    56  			this.statsLocker.Lock()
    57  			this.statsMap[hash] = &Stat{
    58  				ServerId: obj.MetricServerId(),
    59  				Keys:     keys,
    60  				Value:    v,
    61  				Time:     this.itemConfig.CurrentTime(),
    62  				Hash:     hash,
    63  			}
    64  			this.statsLocker.Unlock()
    65  		}
    66  	}
    67  }
    68  
    69  func (this *BaseTask) Item() *serverconfigs.MetricItemConfig {
    70  	return this.itemConfig
    71  }
    72  
    73  func (this *BaseTask) SetItem(itemConfig *serverconfigs.MetricItemConfig) {
    74  	this.itemConfig = itemConfig
    75  }