github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/services/openvpn/service/stats_publisher.go (about)

     1  /*
     2   * Copyright (C) 2020 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package service
    19  
    20  import (
    21  	"github.com/mysteriumnetwork/go-openvpn/openvpn/middlewares/server/bytecount"
    22  	"github.com/mysteriumnetwork/node/eventbus"
    23  	"github.com/mysteriumnetwork/node/session/event"
    24  	"github.com/rs/zerolog/log"
    25  )
    26  
    27  func newStatsPublisher(clientMap *clientMap, bus eventbus.Publisher, frequencySeconds int) *statsPublisher {
    28  	sb := new(statsPublisher)
    29  	sb.Middleware = bytecount.NewMiddleware(sb.handleStatsEvent, frequencySeconds)
    30  	sb.clientMap = clientMap
    31  	sb.bus = bus
    32  	return sb
    33  }
    34  
    35  type statsPublisher struct {
    36  	*bytecount.Middleware
    37  
    38  	clientMap *clientMap
    39  	bus       eventbus.Publisher
    40  }
    41  
    42  func (sb *statsPublisher) handleStatsEvent(clientStats bytecount.SessionByteCount) {
    43  	session, exist := sb.clientMap.GetClientSession(clientStats.ClientID)
    44  	if !exist {
    45  		log.Warn().Msgf("Stats for unknown session of client %d", clientStats.ClientID)
    46  		return
    47  	}
    48  
    49  	sb.bus.Publish(event.AppTopicDataTransferred, event.AppEventDataTransferred{
    50  		ID:   string(session),
    51  		Up:   clientStats.BytesOut,
    52  		Down: clientStats.BytesIn,
    53  	})
    54  }