github.com/cnotch/ipchub@v1.1.0/stats/flow.go (about)

     1  // Copyright (c) 2019,CAOHONGJU All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package stats
     6  
     7  import (
     8  	"sync/atomic"
     9  )
    10  
    11  // FlowSample 流统计采样
    12  type FlowSample struct {
    13  	InBytes  int64 `json:"inbytes"`
    14  	OutBytes int64 `json:"outbytes"`
    15  }
    16  
    17  // Flow 流统计接口
    18  type Flow interface {
    19  	AddIn(size int64)      // 增加输入
    20  	AddOut(size int64)     // 增加输出
    21  	GetSample() FlowSample // 获取当前时点采样
    22  }
    23  
    24  func (fs *FlowSample) clone() FlowSample {
    25  	return FlowSample{
    26  		InBytes:  atomic.LoadInt64(&fs.InBytes),
    27  		OutBytes: atomic.LoadInt64(&fs.OutBytes),
    28  	}
    29  }
    30  
    31  // Add 采样累加
    32  func (fs *FlowSample) Add(f FlowSample) {
    33  	fs.InBytes = fs.InBytes + f.InBytes
    34  	fs.OutBytes = fs.OutBytes + f.OutBytes
    35  }
    36  
    37  type flow struct {
    38  	sample FlowSample
    39  }
    40  
    41  // NewFlow 创建流量统计
    42  func NewFlow() Flow {
    43  	return &flow{}
    44  }
    45  
    46  func (r *flow) AddIn(size int64) {
    47  	atomic.AddInt64(&r.sample.InBytes, size)
    48  }
    49  
    50  func (r *flow) AddOut(size int64) {
    51  	atomic.AddInt64(&r.sample.OutBytes, size)
    52  }
    53  
    54  func (r *flow) GetSample() FlowSample {
    55  	return r.sample.clone()
    56  }
    57  
    58  type childFlow struct {
    59  	parent Flow
    60  	sample FlowSample
    61  }
    62  
    63  // NewChildFlow 创建子流量计数,它会把自己的计数Add到parent上
    64  func NewChildFlow(parent Flow) Flow {
    65  	return &childFlow{
    66  		parent: parent,
    67  	}
    68  }
    69  
    70  func (r *childFlow) AddIn(size int64) {
    71  	atomic.AddInt64(&r.sample.InBytes, size)
    72  	r.parent.AddIn(size)
    73  }
    74  
    75  func (r *childFlow) AddOut(size int64) {
    76  	atomic.AddInt64(&r.sample.OutBytes, size)
    77  	r.parent.AddOut(size)
    78  }
    79  
    80  func (r *childFlow) GetSample() FlowSample {
    81  	return r.sample.clone()
    82  }