mirror of
https://github.com/cgrates/cgrates.git
synced 2026-02-16 13:49:53 +05:00
Partial refactoring for SessionS component
This commit is contained in:
@@ -63,4 +63,8 @@
|
||||
"enabled": true,
|
||||
},
|
||||
|
||||
"chargers": {
|
||||
"enabled": true,
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
@@ -480,12 +480,15 @@ func (self *CGRConfig) checkConfigSanity() error {
|
||||
// SessionS checks
|
||||
if self.sessionSCfg.Enabled {
|
||||
if len(self.sessionSCfg.RALsConns) == 0 {
|
||||
return errors.New("<SessionS> RALs definition is mandatory!")
|
||||
return errors.New("<SessionS> RALs definition is mandatory")
|
||||
}
|
||||
if len(self.sessionSCfg.ChargerSConns) == 0 {
|
||||
return fmt.Errorf("<%s> %s connection is mandatory", utils.SessionS, utils.ChargerS)
|
||||
}
|
||||
if !self.chargerSCfg.Enabled {
|
||||
for _, conn := range self.sessionSCfg.ChargerSConns {
|
||||
if conn.Address == utils.MetaInternal {
|
||||
return errors.New("<SessionS> ChargerS not enabled but requested")
|
||||
return errors.New("<SessionS> ChargerS not enabled")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,7 +293,9 @@ const CGRATES_CFG_JSON = `
|
||||
"sessions": {
|
||||
"enabled": false, // starts session manager service: <true|false>
|
||||
"listen_bijson": "127.0.0.1:2014", // address where to listen for bidirectional JSON-RPC requests
|
||||
"chargers_conns": [], // address where to reach the charger service, empty to disable charger functionality: <""|*internal|x.y.z.y:1234>
|
||||
"chargers_conns": [
|
||||
{"address": "*internal"} // address where to reach the charger service <*internal|x.y.z.y:1234>
|
||||
],
|
||||
"rals_conns": [
|
||||
{"address": "*internal"} // address where to reach the RALs <""|*internal|127.0.0.1:2013>
|
||||
],
|
||||
|
||||
@@ -469,17 +469,17 @@ func TestDfCdrcJsonCfg(t *testing.T) {
|
||||
|
||||
func TestSmgJsonCfg(t *testing.T) {
|
||||
eCfg := &SessionSJsonCfg{
|
||||
Enabled: utils.BoolPointer(false),
|
||||
Listen_bijson: utils.StringPointer("127.0.0.1:2014"),
|
||||
Chargers_conns: &[]*HaPoolJsonCfg{},
|
||||
Rals_conns: &[]*HaPoolJsonCfg{
|
||||
{
|
||||
Address: utils.StringPointer(utils.MetaInternal),
|
||||
}},
|
||||
Cdrs_conns: &[]*HaPoolJsonCfg{
|
||||
{
|
||||
Address: utils.StringPointer(utils.MetaInternal),
|
||||
}},
|
||||
Enabled: utils.BoolPointer(false),
|
||||
Listen_bijson: utils.StringPointer("127.0.0.1:2014"),
|
||||
Chargers_conns: &[]*HaPoolJsonCfg{{
|
||||
Address: utils.StringPointer(utils.MetaInternal),
|
||||
}},
|
||||
Rals_conns: &[]*HaPoolJsonCfg{{
|
||||
Address: utils.StringPointer(utils.MetaInternal),
|
||||
}},
|
||||
Cdrs_conns: &[]*HaPoolJsonCfg{{
|
||||
Address: utils.StringPointer(utils.MetaInternal),
|
||||
}},
|
||||
Resources_conns: &[]*HaPoolJsonCfg{},
|
||||
Thresholds_conns: &[]*HaPoolJsonCfg{},
|
||||
Stats_conns: &[]*HaPoolJsonCfg{},
|
||||
|
||||
@@ -634,9 +634,10 @@ func TestCgrCfgJSONDefaultsCdreProfiles(t *testing.T) {
|
||||
|
||||
func TestCgrCfgJSONDefaultsSMGenericCfg(t *testing.T) {
|
||||
eSessionSCfg := &SessionSCfg{
|
||||
Enabled: false,
|
||||
ListenBijson: "127.0.0.1:2014",
|
||||
ChargerSConns: []*HaPoolConfig{},
|
||||
Enabled: false,
|
||||
ListenBijson: "127.0.0.1:2014",
|
||||
ChargerSConns: []*HaPoolConfig{
|
||||
{Address: "*internal"}},
|
||||
RALsConns: []*HaPoolConfig{
|
||||
{Address: "*internal"}},
|
||||
CDRsConns: []*HaPoolConfig{
|
||||
|
||||
@@ -101,6 +101,25 @@ func (me MapEvent) GetDurationIgnoreErrors(fldName string) (d time.Duration) {
|
||||
return
|
||||
}
|
||||
|
||||
// GetDurationPointer returns pointer towards duration, useful to detect presence of duration
|
||||
func (me MapEvent) GetDurationPtr(fldName string) (d *time.Duration, err error) {
|
||||
fldIface, has := me[fldName]
|
||||
if !has {
|
||||
return nil, utils.ErrNotFound
|
||||
}
|
||||
var dReal time.Duration
|
||||
if dReal, err = utils.IfaceAsDuration(fldIface); err != nil {
|
||||
return
|
||||
}
|
||||
return &dReal, nil
|
||||
}
|
||||
|
||||
// GetDurationPointer returns pointer towards duration, useful to detect presence of duration
|
||||
func (me MapEvent) GetDurationPtrIgnoreErrors(fldName string) (d *time.Duration) {
|
||||
d, _ = me.GetDurationPtr(fldName)
|
||||
return
|
||||
}
|
||||
|
||||
// GetTime returns a field as Time
|
||||
func (me MapEvent) GetTime(fldName string, timezone string) (t time.Time, err error) {
|
||||
fldIface, has := me[fldName]
|
||||
|
||||
@@ -167,6 +167,12 @@ func (se *SafEvent) GetDurationPtr(fldName string) (d *time.Duration, err error)
|
||||
return &dReal, nil
|
||||
}
|
||||
|
||||
// GetDurationPointer returns pointer towards duration, useful to detect presence of duration
|
||||
func (se *SafEvent) GetDurationPtrIgnoreErrors(fldName string) (d *time.Duration) {
|
||||
d, _ = se.GetDurationPtr(fldName)
|
||||
return
|
||||
}
|
||||
|
||||
// GetDurationPointer returns pointer towards duration, useful to detect presence of duration
|
||||
func (se *SafEvent) GetDurationPtrOrDefault(fldName string, dflt *time.Duration) (d *time.Duration, err error) {
|
||||
fldIface, has := se.Get(fldName)
|
||||
|
||||
@@ -19,54 +19,13 @@ along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/cgrates/cgrates/engine"
|
||||
"github.com/cgrates/cgrates/utils"
|
||||
"github.com/cgrates/rpcclient"
|
||||
)
|
||||
|
||||
// One session handled by SM
|
||||
type SMGSession struct {
|
||||
sync.RWMutex // protects the SMGSession in places where is concurrently accessed
|
||||
stopDebit chan struct{} // Channel to communicate with debit loops when closing the session
|
||||
clntConn rpcclient.RpcClientConnection // Reference towards client connection on SMG side so we can disconnect.
|
||||
rals rpcclient.RpcClientConnection // Connector to rals service
|
||||
cdrsrv rpcclient.RpcClientConnection // Connector to CDRS service
|
||||
clientProto float64
|
||||
|
||||
Tenant string // store original Tenant so we can use it in API calls
|
||||
CGRID string // Unique identifier for this session
|
||||
RunID string // Keep a reference for the derived run
|
||||
Timezone string
|
||||
ResourceID string
|
||||
|
||||
EventStart *engine.SafEvent // Event which started the session
|
||||
CD *engine.CallDescriptor // initial CD used for debits, updated on each debit
|
||||
EventCost *engine.EventCost
|
||||
|
||||
ExtraDuration time.Duration // keeps the current duration debited on top of what has been asked
|
||||
LastUsage time.Duration // last requested Duration
|
||||
LastDebit time.Duration // last real debited duration
|
||||
TotalUsage time.Duration // sum of lastUsage
|
||||
}
|
||||
|
||||
// Clone returns the cloned version of SMGSession
|
||||
func (s *SMGSession) Clone() *SMGSession {
|
||||
return &SMGSession{CGRID: s.CGRID, RunID: s.RunID,
|
||||
Timezone: s.Timezone, ResourceID: s.ResourceID,
|
||||
EventStart: s.EventStart.Clone(),
|
||||
CD: s.CD.Clone(),
|
||||
EventCost: s.EventCost.Clone(),
|
||||
ExtraDuration: s.ExtraDuration, LastUsage: s.LastUsage,
|
||||
LastDebit: s.LastDebit, TotalUsage: s.TotalUsage,
|
||||
}
|
||||
}
|
||||
|
||||
type SessionID struct {
|
||||
OriginHost string
|
||||
OriginID string
|
||||
@@ -76,268 +35,15 @@ func (s *SessionID) CGRID() string {
|
||||
return utils.Sha1(s.OriginID, s.OriginHost)
|
||||
}
|
||||
|
||||
// Called in case of automatic debits
|
||||
func (self *SMGSession) debitLoop(debitInterval time.Duration) {
|
||||
loopIndex := 0
|
||||
sleepDur := time.Duration(0) // start with empty duration for debit
|
||||
for {
|
||||
select {
|
||||
case <-self.stopDebit:
|
||||
return
|
||||
case <-time.After(sleepDur):
|
||||
if maxDebit, err := self.debit(debitInterval, nil); err != nil {
|
||||
utils.Logger.Err(fmt.Sprintf("<%s> Could not complete debit operation on session: %s, error: %s", utils.SessionS, self.CGRID, err.Error()))
|
||||
disconnectReason := utils.ErrServerError.Error()
|
||||
if err.Error() == utils.ErrUnauthorizedDestination.Error() {
|
||||
disconnectReason = err.Error()
|
||||
}
|
||||
if err := self.disconnectSession(disconnectReason); err != nil {
|
||||
utils.Logger.Err(fmt.Sprintf("<%s> Could not disconnect session: %s, error: %s", utils.SessionS, self.CGRID, err.Error()))
|
||||
}
|
||||
return
|
||||
} else if maxDebit < debitInterval {
|
||||
time.Sleep(maxDebit)
|
||||
if err := self.disconnectSession(utils.ErrInsufficientCredit.Error()); err != nil {
|
||||
utils.Logger.Err(fmt.Sprintf("<%s> Could not disconnect session: %s, error: %s", utils.SessionS, self.CGRID, err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
sleepDur = debitInterval
|
||||
loopIndex++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attempts to debit a duration, returns maximum duration which can be debitted or error
|
||||
func (self *SMGSession) debit(dur time.Duration, lastUsed *time.Duration) (time.Duration, error) {
|
||||
self.Lock()
|
||||
defer self.Unlock()
|
||||
requestedDuration := dur
|
||||
if lastUsed != nil {
|
||||
self.ExtraDuration = self.LastDebit - *lastUsed
|
||||
if *lastUsed != self.LastUsage {
|
||||
// total usage correction
|
||||
self.TotalUsage -= self.LastUsage
|
||||
self.TotalUsage += *lastUsed
|
||||
}
|
||||
}
|
||||
// apply correction from previous run
|
||||
if self.ExtraDuration < dur {
|
||||
dur -= self.ExtraDuration
|
||||
} else {
|
||||
self.LastUsage = requestedDuration
|
||||
self.TotalUsage += self.LastUsage
|
||||
self.ExtraDuration -= dur
|
||||
return requestedDuration, nil
|
||||
}
|
||||
initialExtraDuration := self.ExtraDuration
|
||||
self.ExtraDuration = 0
|
||||
if self.CD.LoopIndex > 0 {
|
||||
self.CD.TimeStart = self.CD.TimeEnd
|
||||
}
|
||||
self.CD.TimeEnd = self.CD.TimeStart.Add(dur)
|
||||
self.CD.DurationIndex += dur
|
||||
cc := &engine.CallCost{}
|
||||
if err := self.rals.Call("Responder.MaxDebit", self.CD, cc); err != nil || cc.GetDuration() == 0 {
|
||||
self.LastUsage = 0
|
||||
self.LastDebit = 0
|
||||
return 0, err
|
||||
}
|
||||
// cd corrections
|
||||
self.CD.TimeEnd = cc.GetEndTime() // set debited timeEnd
|
||||
// update call duration with real debited duration
|
||||
ccDuration := cc.GetDuration()
|
||||
if ccDuration > dur {
|
||||
self.ExtraDuration = ccDuration - dur
|
||||
}
|
||||
if ccDuration >= dur {
|
||||
self.LastUsage = requestedDuration
|
||||
} else {
|
||||
self.LastUsage = ccDuration
|
||||
}
|
||||
self.CD.DurationIndex -= dur
|
||||
self.CD.DurationIndex += ccDuration
|
||||
self.CD.MaxCostSoFar += cc.Cost
|
||||
self.CD.LoopIndex += 1
|
||||
self.LastDebit = initialExtraDuration + ccDuration
|
||||
self.TotalUsage += self.LastUsage
|
||||
ec := engine.NewEventCostFromCallCost(cc, self.CGRID, self.RunID)
|
||||
if self.EventCost == nil {
|
||||
self.EventCost = ec
|
||||
} else {
|
||||
self.EventCost.Merge(ec)
|
||||
}
|
||||
if ccDuration < dur {
|
||||
return initialExtraDuration + ccDuration, nil
|
||||
}
|
||||
return requestedDuration, nil
|
||||
}
|
||||
|
||||
// Send disconnect order to remote connection
|
||||
func (self *SMGSession) disconnectSession(reason string) error {
|
||||
if self.clntConn == nil || reflect.ValueOf(self.clntConn).IsNil() {
|
||||
return errors.New("Calling SMGClientV1.DisconnectSession requires bidirectional JSON connection")
|
||||
}
|
||||
self.EventStart.Set(utils.Usage, self.TotalUsage) // Set the usage to total one debitted
|
||||
var reply string
|
||||
servMethod := "SessionSv1.DisconnectSession"
|
||||
if self.clientProto == 0 { // competibility with OpenSIPS
|
||||
servMethod = "SMGClientV1.DisconnectSession"
|
||||
}
|
||||
if err := self.clntConn.Call(servMethod,
|
||||
utils.AttrDisconnectSession{EventStart: self.EventStart.AsMapInterface(),
|
||||
Reason: reason},
|
||||
&reply); err != nil {
|
||||
if err != utils.ErrNotImplemented {
|
||||
return err
|
||||
}
|
||||
err = nil
|
||||
} else if reply != utils.OK {
|
||||
return errors.New(fmt.Sprintf("Unexpected disconnect reply: %s", reply))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Session has ended, check debits and refund the extra charged duration
|
||||
func (self *SMGSession) close(usage time.Duration) (err error) {
|
||||
self.Lock()
|
||||
defer self.Unlock()
|
||||
if self.EventCost == nil {
|
||||
return
|
||||
}
|
||||
if notCharged := usage - self.EventCost.GetUsage(); notCharged > 0 { // we did not charge enough, make a manual debit here
|
||||
if self.CD.LoopIndex > 0 {
|
||||
self.CD.TimeStart = self.CD.TimeEnd
|
||||
}
|
||||
self.CD.TimeEnd = self.CD.TimeStart.Add(notCharged)
|
||||
self.CD.DurationIndex += notCharged
|
||||
cc := &engine.CallCost{}
|
||||
if err = self.rals.Call("Responder.Debit", self.CD, cc); err == nil {
|
||||
self.EventCost.Merge(
|
||||
engine.NewEventCostFromCallCost(cc, self.CGRID, self.RunID))
|
||||
}
|
||||
} else if notCharged < 0 { // charged too much, try refund
|
||||
err = self.refund(usage)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Attempts to refund a duration, error on failure
|
||||
// usage represents the real usage
|
||||
func (self *SMGSession) refund(usage time.Duration) (err error) {
|
||||
if self.EventCost == nil {
|
||||
return
|
||||
}
|
||||
srplsEC, err := self.EventCost.Trim(usage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if srplsEC == nil {
|
||||
return
|
||||
}
|
||||
|
||||
cc := srplsEC.AsCallCost()
|
||||
var incrmts engine.Increments
|
||||
for _, tmspn := range cc.Timespans {
|
||||
for _, incr := range tmspn.Increments {
|
||||
if incr.BalanceInfo == nil ||
|
||||
(incr.BalanceInfo.Unit == nil &&
|
||||
incr.BalanceInfo.Monetary == nil) {
|
||||
continue // not enough information for refunds, most probably free units uncounted
|
||||
}
|
||||
incrmts = append(incrmts, incr)
|
||||
}
|
||||
}
|
||||
cd := &engine.CallDescriptor{
|
||||
CgrID: self.CGRID,
|
||||
RunID: self.RunID,
|
||||
Direction: self.CD.Direction,
|
||||
Category: self.CD.Category,
|
||||
Tenant: self.CD.Tenant,
|
||||
Subject: self.CD.Subject,
|
||||
Account: self.CD.Account,
|
||||
Destination: self.CD.Destination,
|
||||
TOR: self.CD.TOR,
|
||||
Increments: incrmts,
|
||||
}
|
||||
var acnt engine.Account
|
||||
err = self.rals.Call("Responder.RefundIncrements", cd, &acnt)
|
||||
if acnt.ID != "" { // Account info updated, update also cached AccountSummary
|
||||
self.EventCost.AccountSummary = acnt.AsAccountSummary()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// storeSMCost will send the SMCost to CDRs for storing
|
||||
func (self *SMGSession) storeSMCost() error {
|
||||
if self.EventCost == nil {
|
||||
return nil // There are no costs to save, ignore the operation
|
||||
}
|
||||
self.Lock()
|
||||
self.Unlock()
|
||||
smCost := &engine.V2SMCost{
|
||||
CGRID: self.CGRID,
|
||||
CostSource: utils.MetaSessionS,
|
||||
RunID: self.RunID,
|
||||
OriginHost: self.EventStart.GetStringIgnoreErrors(utils.OriginHost),
|
||||
OriginID: self.EventStart.GetStringIgnoreErrors(utils.OriginID),
|
||||
Usage: self.TotalUsage,
|
||||
CostDetails: self.EventCost,
|
||||
}
|
||||
var reply string
|
||||
if err := self.cdrsrv.Call("CdrsV2.StoreSMCost",
|
||||
engine.ArgsV2CDRSStoreSMCost{Cost: smCost,
|
||||
CheckDuplicate: true}, &reply); err != nil {
|
||||
if err == utils.ErrExists {
|
||||
self.refund(self.CD.GetDuration()) // Refund entire duration
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SMGSession) AsActiveSession(timezone string) *ActiveSession {
|
||||
self.RLock()
|
||||
defer self.RUnlock()
|
||||
aSession := &ActiveSession{
|
||||
CGRID: self.CGRID,
|
||||
TOR: self.EventStart.GetStringIgnoreErrors(utils.ToR),
|
||||
RunID: self.RunID,
|
||||
OriginID: self.EventStart.GetStringIgnoreErrors(utils.OriginID),
|
||||
CdrHost: self.EventStart.GetStringIgnoreErrors(utils.OriginHost),
|
||||
CdrSource: utils.SessionS + "_" + self.EventStart.GetStringIgnoreErrors(utils.EVENT_NAME),
|
||||
ReqType: self.EventStart.GetStringIgnoreErrors(utils.RequestType),
|
||||
Tenant: self.EventStart.GetStringIgnoreErrors(utils.Tenant),
|
||||
Category: self.EventStart.GetStringIgnoreErrors(utils.Category),
|
||||
Account: self.EventStart.GetStringIgnoreErrors(utils.Account),
|
||||
Subject: self.EventStart.GetStringIgnoreErrors(utils.Subject),
|
||||
Destination: self.EventStart.GetStringIgnoreErrors(utils.Destination),
|
||||
SetupTime: self.EventStart.GetTimeIgnoreErrors(utils.SetupTime, self.Timezone),
|
||||
AnswerTime: self.EventStart.GetTimeIgnoreErrors(utils.AnswerTime, self.Timezone),
|
||||
Usage: self.TotalUsage,
|
||||
ExtraFields: self.EventStart.AsMapStringIgnoreErrors(utils.MainCDRFieldsMap),
|
||||
SMId: "CGR-DA",
|
||||
}
|
||||
if self.CD != nil {
|
||||
aSession.LoopIndex = self.CD.LoopIndex
|
||||
aSession.DurationIndex = self.CD.DurationIndex
|
||||
aSession.MaxRate = self.CD.MaxRate
|
||||
aSession.MaxRateUnit = self.CD.MaxRateUnit
|
||||
aSession.MaxCostSoFar = self.CD.MaxCostSoFar
|
||||
}
|
||||
return aSession
|
||||
}
|
||||
|
||||
// Will be used when displaying active sessions via RPC
|
||||
type ActiveSession struct {
|
||||
CGRID string
|
||||
TOR string // type of record, meta-field, should map to one of the TORs hardcoded inside the server <*voice|*data|*sms|*generic>
|
||||
RunID string
|
||||
ToR string // type of record, meta-field, should map to one of the TORs hardcoded inside the server <*voice|*data|*sms|*generic>
|
||||
OriginID string // represents the unique accounting id given by the telecom switch generating the CDR
|
||||
CdrHost string // represents the IP address of the host generating the CDR (automatically populated by the server)
|
||||
CdrSource string // formally identifies the source of the CDR (free form field)
|
||||
ReqType string // matching the supported request types by the **CGRateS**, accepted values are hardcoded in the server <prepaid|postpaid|pseudoprepaid|rated>
|
||||
OriginHost string // represents the IP address of the host generating the CDR (automatically populated by the server)
|
||||
Source string // formally identifies the source of the CDR (free form field)
|
||||
RequestType string // matching the supported request types by the **CGRateS**, accepted values are hardcoded in the server <prepaid|postpaid|pseudoprepaid|rated>
|
||||
Tenant string // tenant whom this record belongs
|
||||
Category string // free-form filter for this record, matching the category defined in rating profiles.
|
||||
Account string // account id (accounting subsystem) the record should be attached to
|
||||
@@ -347,12 +53,134 @@ type ActiveSession struct {
|
||||
AnswerTime time.Time // answer time of the event. Supported formats: datetime RFC3339 compatible, SQL datetime (eg: MySQL), unix timestamp.
|
||||
Usage time.Duration // event usage information (eg: in case of tor=*voice this will represent the total duration of a call)
|
||||
ExtraFields map[string]string // Extra fields to be stored in CDR
|
||||
SMId string
|
||||
SMConnId string
|
||||
RunID string
|
||||
NodeID string
|
||||
LoopIndex float64 // indicates the position of this segment in a cost request loop
|
||||
DurationIndex time.Duration // the call duration so far (till TimeEnd)
|
||||
MaxRate float64
|
||||
MaxRateUnit time.Duration
|
||||
MaxCostSoFar float64
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
sync.RWMutex
|
||||
|
||||
CGRID string
|
||||
Tenant string
|
||||
ResourceID string
|
||||
ClientConnID string // connection ID towards the client so we can recover from passive
|
||||
EventStart *engine.SafEvent // Event which started the session
|
||||
SRuns []*SRun // forked based on ChargerS
|
||||
|
||||
debitStop chan struct{}
|
||||
sTerminator *sTerminator // automatic timeout for the session
|
||||
}
|
||||
|
||||
// CGRid is a thread-safe method to return the CGRID of a session
|
||||
func (s *Session) CGRid() (cgrID string) {
|
||||
s.RLock()
|
||||
cgrID = s.CGRID
|
||||
s.RUnlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Clone is a thread safe method to clone the sessions information
|
||||
func (s Session) Clone() (cln *Session) {
|
||||
s.RLock()
|
||||
cln = &Session{
|
||||
CGRID: s.CGRID,
|
||||
Tenant: s.Tenant,
|
||||
ResourceID: s.ResourceID,
|
||||
EventStart: s.EventStart.Clone(),
|
||||
ClientConnID: s.ClientConnID,
|
||||
}
|
||||
if s.SRuns != nil {
|
||||
cln.SRuns = make([]*SRun, len(s.SRuns))
|
||||
for i, sR := range s.SRuns {
|
||||
cln.SRuns[i] = sR.Clone()
|
||||
}
|
||||
}
|
||||
s.RUnlock()
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Session) AsActiveSessions(tmz, nodeID string) (aSs []*ActiveSession) {
|
||||
s.RLock()
|
||||
aSs = make([]*ActiveSession, len(s.SRuns))
|
||||
for i, sr := range s.SRuns {
|
||||
aSs[i] = &ActiveSession{
|
||||
CGRID: s.CGRID,
|
||||
RunID: sr.Event.GetStringIgnoreErrors(utils.RunID),
|
||||
ToR: sr.Event.GetStringIgnoreErrors(utils.ToR),
|
||||
OriginID: s.EventStart.GetStringIgnoreErrors(utils.OriginID),
|
||||
OriginHost: s.EventStart.GetStringIgnoreErrors(utils.OriginHost),
|
||||
Source: utils.SessionS + "_" + s.EventStart.GetStringIgnoreErrors(utils.EVENT_NAME),
|
||||
RequestType: sr.Event.GetStringIgnoreErrors(utils.RequestType),
|
||||
Tenant: s.Tenant,
|
||||
Category: sr.Event.GetStringIgnoreErrors(utils.Category),
|
||||
Account: sr.Event.GetStringIgnoreErrors(utils.Account),
|
||||
Subject: sr.Event.GetStringIgnoreErrors(utils.Subject),
|
||||
Destination: sr.Event.GetStringIgnoreErrors(utils.Destination),
|
||||
SetupTime: sr.Event.GetTimeIgnoreErrors(utils.SetupTime, tmz),
|
||||
AnswerTime: sr.Event.GetTimeIgnoreErrors(utils.AnswerTime, tmz),
|
||||
Usage: sr.TotalUsage,
|
||||
ExtraFields: sr.Event.AsMapStringIgnoreErrors(
|
||||
utils.NewStringMap(utils.PrimaryCdrFields...)),
|
||||
NodeID: nodeID,
|
||||
}
|
||||
if sr.CD != nil {
|
||||
aSs[i].LoopIndex = sr.CD.LoopIndex
|
||||
aSs[i].DurationIndex = sr.CD.DurationIndex
|
||||
aSs[i].MaxRate = sr.CD.MaxRate
|
||||
aSs[i].MaxRateUnit = sr.CD.MaxRateUnit
|
||||
aSs[i].MaxCostSoFar = sr.CD.MaxCostSoFar
|
||||
}
|
||||
}
|
||||
s.RUnlock()
|
||||
return
|
||||
}
|
||||
|
||||
// SRun is one billing run for the Session
|
||||
type SRun struct {
|
||||
Event engine.MapEvent // Event received from ChargerS
|
||||
CD *engine.CallDescriptor // initial CD used for debits, updated on each debit
|
||||
EventCost *engine.EventCost
|
||||
|
||||
ExtraDuration time.Duration // keeps the current duration debited on top of what has been asked
|
||||
LastUsage time.Duration // last requested Duration
|
||||
TotalUsage time.Duration // sum of lastUsage
|
||||
}
|
||||
|
||||
// Clone returns the cloned version of SRun
|
||||
func (sr *SRun) Clone() *SRun {
|
||||
return &SRun{
|
||||
CD: sr.CD.Clone(),
|
||||
EventCost: sr.EventCost.Clone(),
|
||||
ExtraDuration: sr.ExtraDuration,
|
||||
LastUsage: sr.LastUsage,
|
||||
TotalUsage: sr.TotalUsage,
|
||||
}
|
||||
}
|
||||
|
||||
// debitReserve attempty to debit from ExtraDuration and returns remaining duration
|
||||
// if lastUsage is not nil, the ExtraDuration is corrected
|
||||
func (sr *SRun) debitReserve(dur time.Duration, lastUsage *time.Duration) (rDur time.Duration) {
|
||||
if lastUsage != nil &&
|
||||
sr.LastUsage != *lastUsage {
|
||||
sr.ExtraDuration -= sr.LastUsage
|
||||
sr.ExtraDuration += *lastUsage
|
||||
sr.TotalUsage -= sr.LastUsage
|
||||
sr.TotalUsage += *lastUsage
|
||||
sr.LastUsage = *lastUsage
|
||||
}
|
||||
// debit from reserved
|
||||
if sr.ExtraDuration >= dur {
|
||||
sr.ExtraDuration -= dur
|
||||
sr.LastUsage = dur
|
||||
sr.TotalUsage += dur
|
||||
rDur = time.Duration(0) // complete debit from reserve
|
||||
} else {
|
||||
rDur = dur - sr.ExtraDuration
|
||||
sr.ExtraDuration = 0
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
2685
sessions/sessions.go
2685
sessions/sessions.go
File diff suppressed because it is too large
Load Diff
@@ -18,6 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
|
||||
package sessions
|
||||
|
||||
/*
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -359,3 +360,4 @@ func TestV1ProcessEventReplyAsNavigableMap(t *testing.T) {
|
||||
t.Errorf("Expecting \n%+v\n, received: \n%+v", expected, rply)
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
@@ -18,6 +18,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
|
||||
package utils
|
||||
|
||||
import "sort"
|
||||
|
||||
var (
|
||||
CDRExportFormats = []string{DRYRUN, MetaFileCSV, MetaFileFWV, MetaHTTPjsonCDR, MetaHTTPjsonMap,
|
||||
MetaHTTPjson, META_HTTP_POST, MetaAMQPjsonCDR, MetaAMQPjsonMap, MetaAWSjsonMap}
|
||||
@@ -774,6 +776,7 @@ const (
|
||||
SessionSv1GetActiveSessions = "SessionSv1.GetActiveSessions"
|
||||
SessionSv1ForceDisconnect = "SessionSv1.ForceDisconnect"
|
||||
SessionSv1GetPassiveSessions = "SessionSv1.GetPassiveSessions"
|
||||
SessionSv1SetPassiveSessions = "SessionSV1.SetPassiveSessions"
|
||||
SMGenericV1InitiateSession = "SMGenericV1.InitiateSession"
|
||||
SMGenericV2InitiateSession = "SMGenericV2.InitiateSession"
|
||||
SMGenericV2UpdateSession = "SMGenericV2.UpdateSession"
|
||||
@@ -782,6 +785,13 @@ const (
|
||||
SessionSv1RegisterInternalBiJSONConn = "SessionSv1.RegisterInternalBiJSONConn"
|
||||
)
|
||||
|
||||
// Responder APIs
|
||||
const (
|
||||
ResponderDebit = "Responder.Debit"
|
||||
ResponderRefundIncrements = "Responder.RefundIncrements"
|
||||
ResponderGetMaxSessionTime = "Responder.GetMaxSessionTime"
|
||||
)
|
||||
|
||||
// DispatcherS APIs
|
||||
const (
|
||||
DispatcherSv1Ping = "DispatcherSv1.Ping"
|
||||
@@ -814,10 +824,11 @@ const (
|
||||
|
||||
// Cdrs APIs
|
||||
const (
|
||||
CdrsV1CountCDRs = "CdrsV1.CountCDRs"
|
||||
CdrsV1GetCDRs = "CdrsV1.GetCDRs"
|
||||
CdrsV2ProcessCDR = "CdrsV2.ProcessCDR"
|
||||
CdrsV2RateCDRs = "CdrsV2.RateCDRs"
|
||||
CdrsV1CountCDRs = "CdrsV1.CountCDRs"
|
||||
CdrsV1GetCDRs = "CdrsV1.GetCDRs"
|
||||
CdrsV2ProcessCDR = "CdrsV2.ProcessCDR"
|
||||
CdrsV2RateCDRs = "CdrsV2.RateCDRs"
|
||||
CdrsV2StoreSMCost = "CdrsV2.StoreSMCost"
|
||||
)
|
||||
|
||||
// Scheduler
|
||||
@@ -979,7 +990,16 @@ func buildCacheIndexesToPrefix() {
|
||||
}
|
||||
}
|
||||
|
||||
// sortStringSlices makes sure the slices are string sorted
|
||||
// so we can search inside using SliceHasMember
|
||||
func sortStringSlices() {
|
||||
sort.Strings(CDRExportFormats)
|
||||
sort.Strings(PrimaryCdrFields)
|
||||
sort.Strings(NotExtraCDRFields)
|
||||
}
|
||||
|
||||
func init() {
|
||||
sortStringSlices()
|
||||
buildCacheInstRevPrefixes()
|
||||
buildCacheIndexesToPrefix()
|
||||
MainCDRFieldsMap = NewStringMap(MainCDRFields...)
|
||||
|
||||
@@ -32,16 +32,13 @@ func IsSliceMember(ss []string, s string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// SliceHasMember is a simpler mode to match inside a slice
|
||||
// SliceHasMember searches within a *sorted* slice
|
||||
// useful to search in shared vars (no slice sort)
|
||||
func SliceHasMember(ss []string, s string) (has bool) {
|
||||
for _, mbr := range ss {
|
||||
if mbr == s {
|
||||
has = true
|
||||
break
|
||||
}
|
||||
func SliceHasMember(ss []string, s string) bool {
|
||||
if i := sort.SearchStrings(ss, s); i < len(ss) && ss[i] == s {
|
||||
return true
|
||||
}
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
func SliceWithoutMember(ss []string, s string) []string {
|
||||
|
||||
Reference in New Issue
Block a user