engine

package
v0.9.1-rc3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2014 License: GPL-3.0 Imports: 36 Imported by: 0

Documentation

Overview

Rating system designed to be used in VoIP Carriers World Copyright (C) 2013 ITsysCOM

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>

Index

Constants

View Source
const (
	LOG            = "*log"
	RESET_TRIGGERS = "*reset_triggers"
	SET_POSTPAID   = "*set_postpaid"
	RESET_POSTPAID = "*reset_postpaid"
	SET_PREPAID    = "*set_prepaid"
	RESET_PREPAID  = "*reset_prepaid"
	TOPUP_RESET    = "*topup_reset"
	TOPUP          = "*topup"
	DEBIT          = "*debit"
	RESET_COUNTER  = "*reset_counter"
	RESET_COUNTERS = "*reset_counters"
	CALL_URL       = "*call_url"
	UNLIMITED      = "*unlimited"
)
View Source
const (
	FORMAT     = "2006-1-2 15:04:05 MST"
	ASAP       = "*asap"
	ASAP_DELAY = "1m"
)
View Source
const (
	RECURSION_MAX_DEPTH = 3
	FALLBACK_SUBJECT    = utils.ANY
)
View Source
const (
	ACTION_TIMING_PREFIX      = "atm_"
	RATING_PLAN_PREFIX        = "rpl_"
	RATING_PROFILE_PREFIX     = "rpf_"
	ACTION_PREFIX             = "act_"
	USER_BALANCE_PREFIX       = "ubl_"
	DESTINATION_PREFIX        = "dst_"
	TEMP_DESTINATION_PREFIX   = "tmp_"
	LOG_CALL_COST_PREFIX      = "cco_"
	LOG_ACTION_TIMMING_PREFIX = "ltm_"
	LOG_ACTION_TRIGGER_PREFIX = "ltr_"
	LOG_ERR                   = "ler_"
	LOG_CDR                   = "cdr_"
	LOG_MEDIATED_CDR          = "mcd_"
	// sources
	SESSION_MANAGER_SOURCE = "SMR"
	MEDIATOR_SOURCE        = "MED"
	SCHED_SOURCE           = "SCH"
	RATER_SOURCE           = "RAT"
	// Some consts used in tests
	CREATE_CDRS_TABLES_SQL        = "create_cdrs_tables.sql"
	CREATE_COSTDETAILS_TABLES_SQL = "create_costdetails_tables.sql"
	CREATE_MEDIATOR_TABLES_SQL    = "create_mediator_tables.sql"
	CREATE_TARIFFPLAN_TABLES_SQL  = "create_tariffplan_tables.sql"
	TEST_SQL                      = "TEST_SQL"
)
View Source
const (
	UB_TYPE_POSTPAID = "*postpaid"
	UB_TYPE_PREPAID  = "*prepaid"
	// Direction type
	INBOUND  = "*in"
	OUTBOUND = "*out"
	// Balance types
	CREDIT       = "*monetary"
	SMS          = "*sms"
	TRAFFIC      = "*internet"
	TRAFFIC_TIME = "*internet_time"
	MINUTES      = "*minutes"
	// action price type
	PRICE_PERCENT  = "*percent"
	PRICE_ABSOLUTE = "*absolute"
	// action trigger threshold types
	TRIGGER_MIN_COUNTER = "*min_counter"
	TRIGGER_MAX_COUNTER = "*max_counter"
	TRIGGER_MIN_BALANCE = "*min_balance"
	TRIGGER_MAX_BALANCE = "*max_balance"
	// minute subjects
	ZEROSECOND = "*zerosecond"
	ZEROMINUTE = "*zerominute"
)

Variables

View Source
var (
	AMOUNT_TOO_BIG = errors.New("Amount excedes balance!")
)
View Source
var FileValidators = map[string]*FileLineRegexValidator{
	utils.DESTINATIONS_CSV: &FileLineRegexValidator{utils.DESTINATIONS_NRCOLS,
		regexp.MustCompile(`(?:\w+\s*,\s*){1}(?:\+?\d+.?\d*){1}$`),
		"Tag([0-9A-Za-z_]),Prefix([0-9])"},
	utils.TIMINGS_CSV: &FileLineRegexValidator{utils.TIMINGS_NRCOLS,
		regexp.MustCompile(`(?:\w+\s*,\s*){1}(?:\*any\s*,\s*|(?:\d{1,4};?)+\s*,\s*|\s*,\s*){4}(?:\d{2}:\d{2}:\d{2}|\*asap){1}$`),
		"Tag([0-9A-Za-z_]),Years([0-9;]|*any|<empty>),Months([0-9;]|*any|<empty>),MonthDays([0-9;]|*any|<empty>),WeekDays([0-9;]|*any|<empty>),Time([0-9:]|*asap)"},
	utils.RATES_CSV: &FileLineRegexValidator{utils.RATES_NRCOLS,
		regexp.MustCompile(`(?:\w+\s*,\s*){1}(?:\d+\.?\d*,){2}(?:\d+s*,){3}(?:\*\w+,){1}(?:\d+\.?\d*,?){1}$`),
		"Tag([0-9A-Za-z_]),ConnectFee([0-9.]),Rate([0-9.]),RateUnit([0-9.]),RateIncrementStart([0-9.])"},
	utils.DESTINATION_RATES_CSV: &FileLineRegexValidator{utils.DESTINATION_RATES_NRCOLS,
		regexp.MustCompile(`^(?:\w+\s*),(?:\w+\s*),(?:\w+\s*)$`),
		"Tag([0-9A-Za-z_]),DestinationsTag([0-9A-Za-z_]),RateTag([0-9A-Za-z_])"},
	utils.RATING_PLANS_CSV: &FileLineRegexValidator{utils.DESTRATE_TIMINGS_NRCOLS,
		regexp.MustCompile(`(?:\w+\s*,\s*){3}(?:\d+.?\d*){1}$`),
		"Tag([0-9A-Za-z_]),DestinationRatesTag([0-9A-Za-z_]),TimingProfile([0-9A-Za-z_]),Weight([0-9.])"},
	utils.RATING_PROFILES_CSV: &FileLineRegexValidator{utils.RATE_PROFILES_NRCOLS,
		regexp.MustCompile(`(?:\w+\s*,\s*){2}(?:\*out\s*,\s*){1}(?:\*any\s*,\s*|\w+\s*,\s*){1}(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z){1}(?:\w*\s*,?\s*){2}$`),
		"Tenant([0-9A-Za-z_]),TOR([0-9A-Za-z_]),Direction(*out),Subject([0-9A-Za-z_]|*all),RatesFallbackSubject([0-9A-Za-z_]|<empty>),RatesTimingTag([0-9A-Za-z_]),ActivationTime([0-9T:X])"},
	utils.ACTIONS_CSV: &FileLineRegexValidator{utils.ACTIONS_NRCOLS,
		regexp.MustCompile(`(?:\w+\s*),(?:\*\w+\s*),(?:\*\w+\s*)?,(?:\*out\s*)?,(?:\d+\s*)?,(?:\*\w+\s*|\+\d+[smh]\s*|\d+\s*)?,(?:\*any|\w+\s*)?,(?:\*\w+\s*)?,(?:\d+\.?\d*\s*)?,(?:\S+\s*)?,(?:\d+\.?\d*\s*)$`),
		"Tag([0-9A-Za-z_]),Action([0-9A-Za-z_]),BalanceType([*a-z_]),Direction(*out),Units([0-9]),ExpiryTime(*[a-z_]|+[0-9][smh]|[0-9])DestinationTag([0-9A-Za-z_]|*all),RatingSubject([0-9A-Za-z_]),BalanceWeight([0-9.]),ExtraParameters([0-9A-Za-z_:;]),Weight([0-9.])"},
	utils.ACTION_TIMINGS_CSV: &FileLineRegexValidator{utils.ACTION_TIMINGS_NRCOLS,
		regexp.MustCompile(`(?:\w+\s*,\s*){3}(?:\d+\.?\d*){1}`),
		"Tag([0-9A-Za-z_]),ActionsTag([0-9A-Za-z_]),TimingTag([0-9A-Za-z_]),Weight([0-9.])"},
	utils.ACTION_TRIGGERS_CSV: &FileLineRegexValidator{utils.ACTION_TRIGGERS_NRCOLS,
		regexp.MustCompile(`(?:\w+),(?:\*\w+),(?:\*out),(?:\*\w+),(?:\d+\.?\d*),(?:\w+|\*any)?,(?:\w+),(?:\d+\.?\d*)$`),
		"Tag([0-9A-Za-z_]),BalanceType(*[a-z_]),Direction(*out),ThresholdType(*[a-z_]),ThresholdValue([0-9]+),DestinationTag([0-9A-Za-z_]|*all),ActionsTag([0-9A-Za-z_]),Weight([0-9]+)"},
	utils.ACCOUNT_ACTIONS_CSV: &FileLineRegexValidator{utils.ACCOUNT_ACTIONS_NRCOLS,
		regexp.MustCompile(`(?:\w+\s*,\s*){1}(?:\w+\s*,\s*){1}(?:\*out\s*,\s*){1}(?:\w+\s*,?\s*){2}$`),
		"Tenant([0-9A-Za-z_]),Account([0-9A-Za-z_.]),Direction(*out),ActionTimingsTag([0-9A-Za-z_]),ActionTriggersTag([0-9A-Za-z_])"},
}

Functions

func NewLoadRate

func NewLoadRate(tag, connectFee, price, ratedUnits, rateIncrements, groupInterval, roundingMethod, roundingDecimals string) (r *utils.TPRate, err error)

func NewRatingPlan

func NewRatingPlan(timing *utils.TPTiming, weight string) (drt *utils.TPRatingPlanBinding)

func NewTiming

func NewTiming(timingInfo ...string) (rt *utils.TPTiming)

func SetAccountingStorage

func SetAccountingStorage(ag AccountingStorage)

func SetDebitPeriod

func SetDebitPeriod(d time.Duration)

Exported method to set the debit period for caching purposes.

func SetHistoryScribe

func SetHistoryScribe(scribe history.Scribe)

Exported method to set the history scribe.

func SetRatingStorage

func SetRatingStorage(sg RatingStorage)

Exported method to set the storage getter.

func SetRoundingMethodAndDecimals

func SetRoundingMethodAndDecimals(rm string, rd int)

Sets the global rounding method and decimal precision for GetCost method

func SetStorageLogger

func SetStorageLogger(sg LogStorage)

Sets the database for logging (can be de same as storage getter or different db)

func ValidNextGroup

func ValidNextGroup(present, next *utils.RateSlot) error

func ValidateCSVData

func ValidateCSVData(fn string, re *regexp.Regexp) (err error)

Types

type AcKeyValue

type AcKeyValue struct {
	Key   string
	Value Actions
}

type AccountAction

type AccountAction struct {
	Tenant, Account, Direction, ActionTimingsTag, ActionTriggersTag string
}

type AccountLock

type AccountLock struct {
	sync.RWMutex
	// contains filtered or unexported fields
}
var AccLock *AccountLock

func NewAccountLock

func NewAccountLock() *AccountLock

func (*AccountLock) Guard

func (cm *AccountLock) Guard(name string, handler func() (float64, error)) (reply float64, err error)

func (*AccountLock) GuardGetCost

func (cm *AccountLock) GuardGetCost(name string, handler func() (*CallCost, error)) (reply *CallCost, err error)

func (*AccountLock) GuardMany

func (cm *AccountLock) GuardMany(names []string, handler func() (float64, error)) (reply float64, err error)

type AccountingStorage

type AccountingStorage interface {
	Storage
	ExistsData(string, string) (bool, error)
	CacheAccounting([]string) error
	GetActions(string, bool) (Actions, error)
	SetActions(string, Actions) error
	GetUserBalance(string) (*UserBalance, error)
	SetUserBalance(*UserBalance) error
	GetActionTimings(string) (ActionTimings, error)
	SetActionTimings(string, ActionTimings) error
	GetAllActionTimings() (map[string]ActionTimings, error)
}

func ConfigureAccountingStorage

func ConfigureAccountingStorage(db_type, host, port, name, user, pass, marshaler string) (db AccountingStorage, err error)

type Action

type Action struct {
	Id               string
	ActionType       string
	BalanceId        string
	Direction        string
	ExtraParameters  string
	ExpirationString string
	Weight           float64
	Balance          *Balance
}

Structure to be filled for each tariff plan with the bonus value for received calls minutes.

type ActionTiming

type ActionTiming struct {
	Id             string // uniquely identify the timing
	Tag            string // informative purpose only
	UserBalanceIds []string
	Timing         *RateInterval
	Weight         float64
	ActionsId      string
	// contains filtered or unexported fields
}

func (*ActionTiming) CheckForASAP

func (at *ActionTiming) CheckForASAP() bool

checks for *asap string as start time and replaces it wit an actual time in the newar future returns true if the *asap string was found

func (*ActionTiming) Execute

func (at *ActionTiming) Execute() (err error)

func (*ActionTiming) GetNextStartTime

func (at *ActionTiming) GetNextStartTime() (t time.Time)

func (*ActionTiming) IsOneTimeRun

func (at *ActionTiming) IsOneTimeRun() bool

returns true if only the starting time was is filled in the Timing field

func (*ActionTiming) SetActions

func (at *ActionTiming) SetActions(as Actions)

func (*ActionTiming) String_DISABLED

func (at *ActionTiming) String_DISABLED() string

type ActionTimingPriotityList

type ActionTimingPriotityList []*ActionTiming

Structure to store actions according to weight

func (ActionTimingPriotityList) Len

func (atpl ActionTimingPriotityList) Len() int

func (ActionTimingPriotityList) Less

func (atpl ActionTimingPriotityList) Less(i, j int) bool

func (ActionTimingPriotityList) Sort

func (atpl ActionTimingPriotityList) Sort()

func (ActionTimingPriotityList) Swap

func (atpl ActionTimingPriotityList) Swap(i, j int)

type ActionTimings

type ActionTimings []*ActionTiming

func RemActionTiming

func RemActionTiming(ats ActionTimings, actionTimingId, balanceId string) ActionTimings

Helper to remove ActionTiming members based on specific filters, empty data means no always match

type ActionTrigger

type ActionTrigger struct {
	Id             string // uniquely identify the trigger
	BalanceId      string
	Direction      string
	ThresholdType  string //*min_counter, *max_counter, *min_balance, *max_balance
	ThresholdValue float64
	DestinationId  string
	Weight         float64
	ActionsId      string
	Executed       bool
}

func (*ActionTrigger) Execute

func (at *ActionTrigger) Execute(ub *UserBalance) (err error)

func (*ActionTrigger) Match

func (at *ActionTrigger) Match(a *Action) bool

returns true if the field of the action timing are equeal to the non empty fields of the action

type ActionTriggerPriotityList

type ActionTriggerPriotityList []*ActionTrigger

Structure to store actions according to weight

func (ActionTriggerPriotityList) Len

func (atpl ActionTriggerPriotityList) Len() int

func (ActionTriggerPriotityList) Less

func (atpl ActionTriggerPriotityList) Less(i, j int) bool

func (ActionTriggerPriotityList) Sort

func (atpl ActionTriggerPriotityList) Sort()

func (ActionTriggerPriotityList) Swap

func (atpl ActionTriggerPriotityList) Swap(i, j int)

type Actions

type Actions []*Action

Structure to store actions according to weight

func (Actions) Len

func (apl Actions) Len() int

func (Actions) Less

func (apl Actions) Less(i, j int) bool

func (Actions) Sort

func (apl Actions) Sort()

func (Actions) Swap

func (apl Actions) Swap(i, j int)

type AtKeyValue

type AtKeyValue struct {
	Key   string
	Value ActionTimings
}

type BSONMarshaler

type BSONMarshaler struct{}

func (*BSONMarshaler) Marshal

func (jm *BSONMarshaler) Marshal(v interface{}) ([]byte, error)

func (*BSONMarshaler) Unmarshal

func (jm *BSONMarshaler) Unmarshal(data []byte, v interface{}) error

type Balance

type Balance struct {
	Uuid           string
	Value          float64
	ExpirationDate time.Time
	Weight         float64
	GroupIds       []string
	DestinationId  string
	RateSubject    string
	// contains filtered or unexported fields
}

Can hold different units as seconds or monetary

func (*Balance) Clone

func (b *Balance) Clone() *Balance

func (*Balance) DebitMinutes

func (b *Balance) DebitMinutes(cc *CallCost, count bool, ub *UserBalance, moneyBalances BalanceChain) error

func (*Balance) DebitMoney

func (b *Balance) DebitMoney(cc *CallCost, count bool, ub *UserBalance) error

func (*Balance) Equal

func (b *Balance) Equal(o *Balance) bool

func (*Balance) GetCost

func (b *Balance) GetCost(cd *CallDescriptor) (*CallCost, error)

func (*Balance) GetMinutesForCredit

func (b *Balance) GetMinutesForCredit(cd *CallDescriptor, initialCredit float64) (duration time.Duration, credit float64)

Returns the available number of seconds for a specified credit

func (*Balance) HasDestination

func (b *Balance) HasDestination() bool

func (*Balance) IsDefault

func (b *Balance) IsDefault() bool

the default balance has no destinationid, Expirationdate or ratesubject

func (*Balance) IsExpired

func (b *Balance) IsExpired() bool

func (*Balance) MatchDestination

func (b *Balance) MatchDestination(destinationId string) bool

type BalanceChain

type BalanceChain []*Balance

Structure to store minute buckets according to weight, precision or price.

func (BalanceChain) Clone

func (bc BalanceChain) Clone() BalanceChain

func (BalanceChain) Debit

func (bc BalanceChain) Debit(amount float64) float64

func (BalanceChain) Equal

func (bc BalanceChain) Equal(o BalanceChain) bool

func (BalanceChain) GetBalance

func (bc BalanceChain) GetBalance(uuid string) *Balance

func (BalanceChain) GetTotalValue

func (bc BalanceChain) GetTotalValue() (total float64)

func (BalanceChain) HasBalance

func (bc BalanceChain) HasBalance(balance *Balance) bool

func (BalanceChain) Len

func (bc BalanceChain) Len() int

func (BalanceChain) Less

func (bc BalanceChain) Less(j, i int) bool

func (BalanceChain) Sort

func (bc BalanceChain) Sort()

func (BalanceChain) Swap

func (bc BalanceChain) Swap(i, j int)

type BincMarshaler

type BincMarshaler struct {
	// contains filtered or unexported fields
}

func NewBincMarshaler

func NewBincMarshaler() *BincMarshaler

func (*BincMarshaler) Marshal

func (bm *BincMarshaler) Marshal(v interface{}) (b []byte, err error)

func (*BincMarshaler) Unmarshal

func (bm *BincMarshaler) Unmarshal(data []byte, v interface{}) error

type CSVReader

type CSVReader struct {
	// contains filtered or unexported fields
}

func NewFileCSVReader

func NewFileCSVReader(dataStorage RatingStorage, accountingStorage AccountingStorage, sep rune, destinationsFn, timingsFn, ratesFn, destinationratesFn, destinationratetimingsFn, ratingprofilesFn, actionsFn, actiontimingsFn, actiontriggersFn, accountactionsFn string) *CSVReader

func NewStringCSVReader

func NewStringCSVReader(dataStorage RatingStorage, accountingStorage AccountingStorage, sep rune, destinationsFn, timingsFn, ratesFn, destinationratesFn, destinationratetimingsFn, ratingprofilesFn, actionsFn, actiontimingsFn, actiontriggersFn, accountactionsFn string) *CSVReader

func (*CSVReader) GetLoadedIds

func (csvr *CSVReader) GetLoadedIds(categ string) ([]string, error)

Returns the identities loaded for a specific category, useful for cache reloads

func (*CSVReader) LoadAccountActions

func (csvr *CSVReader) LoadAccountActions() (err error)

func (*CSVReader) LoadActionTimings

func (csvr *CSVReader) LoadActionTimings() (err error)

func (*CSVReader) LoadActionTriggers

func (csvr *CSVReader) LoadActionTriggers() (err error)

func (*CSVReader) LoadActions

func (csvr *CSVReader) LoadActions() (err error)

func (*CSVReader) LoadAll

func (csvr *CSVReader) LoadAll() error

Automated loading

func (*CSVReader) LoadDestinationRates

func (csvr *CSVReader) LoadDestinationRates() (err error)

func (*CSVReader) LoadDestinations

func (csvr *CSVReader) LoadDestinations() (err error)

func (*CSVReader) LoadRates

func (csvr *CSVReader) LoadRates() (err error)

func (*CSVReader) LoadRatingPlans

func (csvr *CSVReader) LoadRatingPlans() (err error)

func (*CSVReader) LoadRatingProfiles

func (csvr *CSVReader) LoadRatingProfiles() (err error)

func (*CSVReader) LoadTimings

func (csvr *CSVReader) LoadTimings() (err error)

func (*CSVReader) ShowStatistics

func (csvr *CSVReader) ShowStatistics()

func (*CSVReader) WriteToDatabase

func (csvr *CSVReader) WriteToDatabase(flush, verbose bool) (err error)

type CallCost

type CallCost struct {
	Direction, TOR, Tenant, Subject, Account, Destination string
	Cost, ConnectFee                                      float64
	Timespans                                             TimeSpans
}

The output structure that will be returned with the call cost information.

func (*CallCost) CreateCallDescriptor

func (cc *CallCost) CreateCallDescriptor() *CallDescriptor

Creates a CallDescriptor structure copying related data from CallCost

func (*CallCost) GetDuration

func (cc *CallCost) GetDuration() (td time.Duration)

func (*CallCost) GetEndTime

func (cc *CallCost) GetEndTime() time.Time

func (*CallCost) GetStartTime

func (cc *CallCost) GetStartTime() time.Time

func (*CallCost) Merge

func (cc *CallCost) Merge(other *CallCost)

Merges the received timespan if they are similar (same activation period, same interval, same minute info.

func (*CallCost) String

func (cc *CallCost) String() (r string)

Pretty printing for call cost

type CallDescriptor

type CallDescriptor struct {
	Direction                             string
	TOR                                   string
	Tenant, Subject, Account, Destination string
	TimeStart, TimeEnd                    time.Time
	LoopIndex                             float64       // indicates the position of this segment in a cost request loop
	CallDuration                          time.Duration // the call duration so far (till TimeEnd)
	Amount                                float64
	FallbackSubject                       string // the subject to check for destination if not found on primary subject
	RatingInfos                           RatingInfos
	Increments                            Increments
	// contains filtered or unexported fields
}

The input stucture that contains call information.

func (*CallDescriptor) AddRatingInfo

func (cd *CallDescriptor) AddRatingInfo(ris ...*RatingInfo)

Adds a rating plan that applyes to current call descriptor.

func (*CallDescriptor) AddRecievedCallSeconds

func (cd *CallDescriptor) AddRecievedCallSeconds() (err error)

Adds the specified amount of seconds to the received call seconds. When the threshold specified in the user's tariff plan is reached then the received call balance is reseted and the bonus specified in the tariff plan is applied. The amount filed has to be filled in call descriptor.

func (*CallDescriptor) CreateCallCost

func (cd *CallDescriptor) CreateCallCost() *CallCost

Creates a CallCost structure copying related data from CallDescriptor

func (*CallDescriptor) Debit

func (cd *CallDescriptor) Debit() (cc *CallCost, err error)

Interface method used to add/substract an amount of cents or bonus seconds (as returned by GetCost method) from user's money balance.

func (*CallDescriptor) DebitCents

func (cd *CallDescriptor) DebitCents() (left float64, err error)

Interface method used to add/substract an amount of cents from user's money balance. The amount filed has to be filled in call descriptor.

func (*CallDescriptor) DebitSMS

func (cd *CallDescriptor) DebitSMS() (left float64, err error)

Interface method used to add/substract an amount of units from user's sms balance. The amount filed has to be filled in call descriptor.

func (*CallDescriptor) DebitSeconds

func (cd *CallDescriptor) DebitSeconds() (err error)

Interface method used to add/substract an amount of seconds from user's minutes balance. The amount filed has to be filled in call descriptor.

func (*CallDescriptor) FlushCache

func (cd *CallDescriptor) FlushCache() (err error)

func (*CallDescriptor) GetCost

func (cd *CallDescriptor) GetCost() (*CallCost, error)

Creates a CallCost structure with the cost information calculated for the received CallDescriptor.

func (*CallDescriptor) GetDuration

func (cd *CallDescriptor) GetDuration() time.Duration

Returns call descripor's total duration

func (*CallDescriptor) GetKey

func (cd *CallDescriptor) GetKey(subject string) string

Constructs the key for the storage lookup. The prefixLen is limiting the length of the destination prefix.

func (*CallDescriptor) GetMaxSessionDuration

func (cd *CallDescriptor) GetMaxSessionDuration() (time.Duration, error)

Returns the approximate max allowed session for user balance. It will try the max amount received in the call descriptor and will decrease it by 10% for nine times. So if the user has little credit it will still allow 10% of the initial amount. If the user has no credit then it will return 0. If the user has postpayed plan it returns -1.

func (*CallDescriptor) GetUserBalanceKey

func (cd *CallDescriptor) GetUserBalanceKey() string

Returns the key used to retrive the user balance involved in this call

func (*CallDescriptor) LoadRatingPlans

func (cd *CallDescriptor) LoadRatingPlans() (err error)

Restores the activation periods for the specified prefix from storage.

func (*CallDescriptor) MaxDebit

func (cd *CallDescriptor) MaxDebit() (cc *CallCost, err error)

Interface method used to add/substract an amount of cents or bonus seconds (as returned by GetCost method) from user's money balance. This methods combines the Debit and GetMaxSessionDuration and will debit the max available time as returned by the GetMaxSessionTime method. The amount filed has to be filled in call descriptor.

func (*CallDescriptor) RefundIncrements

func (cd *CallDescriptor) RefundIncrements() (left float64, err error)

func (*CallDescriptor) ValidateCallData

func (cd *CallDescriptor) ValidateCallData() error

type CdrStorage

type CdrStorage interface {
	Storage
	SetCdr(utils.RawCDR) error
	SetRatedCdr(*utils.RatedCDR, string) error
	GetRatedCdrs(time.Time, time.Time) ([]*utils.RatedCDR, error)
	RemRatedCdrs([]string) error
}

func ConfigureCdrStorage

func ConfigureCdrStorage(db_type, host, port, name, user, pass string) (db CdrStorage, err error)

type CodecMsgpackMarshaler

type CodecMsgpackMarshaler struct {
	// contains filtered or unexported fields
}

func NewCodecMsgpackMarshaler

func NewCodecMsgpackMarshaler() *CodecMsgpackMarshaler

func (*CodecMsgpackMarshaler) Marshal

func (cmm *CodecMsgpackMarshaler) Marshal(v interface{}) (b []byte, err error)

func (*CodecMsgpackMarshaler) Unmarshal

func (cmm *CodecMsgpackMarshaler) Unmarshal(data []byte, v interface{}) error

type Connector

type Connector interface {
	GetCost(CallDescriptor, *CallCost) error
	Debit(CallDescriptor, *CallCost) error
	MaxDebit(CallDescriptor, *CallCost) error
	RefundIncrements(CallDescriptor, *float64) error
	DebitCents(CallDescriptor, *float64) error
	DebitSeconds(CallDescriptor, *float64) error
	GetMaxSessionTime(CallDescriptor, *float64) error
}

type DbReader

type DbReader struct {
	// contains filtered or unexported fields
}

func NewDbReader

func NewDbReader(storDB LoadStorage, ratingDb RatingStorage, accountDb AccountingStorage, tpid string) *DbReader

func (*DbReader) GetLoadedIds

func (dbr *DbReader) GetLoadedIds(categ string) ([]string, error)

Returns the identities loaded for a specific entity category

func (*DbReader) LoadAccountActions

func (dbr *DbReader) LoadAccountActions() (err error)

func (*DbReader) LoadAccountActionsFiltered

func (dbr *DbReader) LoadAccountActionsFiltered(qriedAA *utils.TPAccountActions) error

func (*DbReader) LoadActionTimings

func (dbr *DbReader) LoadActionTimings() (err error)

func (*DbReader) LoadActionTriggers

func (dbr *DbReader) LoadActionTriggers() (err error)

func (*DbReader) LoadActions

func (dbr *DbReader) LoadActions() (err error)

func (*DbReader) LoadAll

func (dbr *DbReader) LoadAll() error

Automated loading

func (*DbReader) LoadDestinationRates

func (dbr *DbReader) LoadDestinationRates() (err error)

func (*DbReader) LoadDestinations

func (dbr *DbReader) LoadDestinations() (err error)

func (*DbReader) LoadRates

func (dbr *DbReader) LoadRates() (err error)

func (*DbReader) LoadRatingPlanByTag

func (dbr *DbReader) LoadRatingPlanByTag(tag string) (bool, error)

Returns true, nil in case of load success, false, nil in case of RatingPlan not found in storDb

func (*DbReader) LoadRatingPlans

func (dbr *DbReader) LoadRatingPlans() error

func (*DbReader) LoadRatingProfileFiltered

func (dbr *DbReader) LoadRatingProfileFiltered(qriedRpf *utils.TPRatingProfile) error

func (*DbReader) LoadRatingProfiles

func (dbr *DbReader) LoadRatingProfiles() error

func (*DbReader) LoadTimings

func (dbr *DbReader) LoadTimings() (err error)

func (*DbReader) ShowStatistics

func (dbr *DbReader) ShowStatistics()

FIXME: this method is code duplication from csv loader

func (*DbReader) WriteToDatabase

func (dbr *DbReader) WriteToDatabase(flush, verbose bool) (err error)

type Destination

type Destination struct {
	Id       string
	Prefixes []string
}

Structure that gathers multiple destination prefixes under a common id.

func (*Destination) AddPrefix

func (d *Destination) AddPrefix(pfx string)

func (*Destination) String

func (d *Destination) String() (result string)

type FileLineRegexValidator

type FileLineRegexValidator struct {
	FieldsPerRecord int            // Number of fields in one record, useful for crosschecks
	Rule            *regexp.Regexp // Regexp rule
	Message         string         // Pass this message as helper
}

type GOBMarshaler

type GOBMarshaler struct{}

func (*GOBMarshaler) Marshal

func (gm *GOBMarshaler) Marshal(v interface{}) (data []byte, err error)

func (*GOBMarshaler) Unmarshal

func (gm *GOBMarshaler) Unmarshal(data []byte, v interface{}) error
type GroupLink struct {
	Id     string
	Weight float64
}
type GroupLinks []*GroupLink

func (GroupLinks) Len

func (gls GroupLinks) Len() int

func (GroupLinks) Less

func (gls GroupLinks) Less(j, i int) bool

func (GroupLinks) Sort

func (gls GroupLinks) Sort()

func (GroupLinks) Swap

func (gls GroupLinks) Swap(i, j int)

type Increment

type Increment struct {
	Duration            time.Duration
	Cost                float64
	BalanceUuids        []string // need more than one for minutes with cost
	BalanceRateInterval *RateInterval
	MinuteInfo          *MinuteInfo
	// contains filtered or unexported fields
}

func (*Increment) Clone

func (incr *Increment) Clone() *Increment

func (*Increment) GetMinuteBalance

func (incr *Increment) GetMinuteBalance() string

func (*Increment) GetMoneyBalance

func (incr *Increment) GetMoneyBalance() string

func (*Increment) SetMinuteBalance

func (incr *Increment) SetMinuteBalance(bUuid string)

func (*Increment) SetMoneyBalance

func (incr *Increment) SetMoneyBalance(bUuid string)

type Increments

type Increments []*Increment

func (Increments) GetTotalCost

func (incs Increments) GetTotalCost() float64

type JSONBufMarshaler

type JSONBufMarshaler struct{}

func (*JSONBufMarshaler) Marshal

func (jbm *JSONBufMarshaler) Marshal(v interface{}) (data []byte, err error)

func (*JSONBufMarshaler) Unmarshal

func (jbm *JSONBufMarshaler) Unmarshal(data []byte, v interface{}) error

type JSONMarshaler

type JSONMarshaler struct{}

func (*JSONMarshaler) Marshal

func (jm *JSONMarshaler) Marshal(v interface{}) ([]byte, error)

func (*JSONMarshaler) Unmarshal

func (jm *JSONMarshaler) Unmarshal(data []byte, v interface{}) error

type LoadStorage

type LoadStorage interface {
	Storage
	// Apier functions
	RemTPData(string, string, ...string) error
	GetTPIds() ([]string, error)

	SetTPTiming(string, *utils.TPTiming) error
	GetTpTimings(string, string) (map[string]*utils.TPTiming, error)
	GetTPTimingIds(string) ([]string, error)

	SetTPDestination(string, *Destination) error
	GetTpDestinations(string, string) ([]*Destination, error)
	GetTPDestinationIds(string) ([]string, error)

	SetTPRates(string, map[string][]*utils.RateSlot) error
	GetTpRates(string, string) (map[string]*utils.TPRate, error)
	GetTPRateIds(string) ([]string, error)

	SetTPDestinationRates(string, map[string][]*utils.DestinationRate) error
	GetTpDestinationRates(string, string) (map[string]*utils.TPDestinationRate, error)
	GetTPDestinationRateIds(string) ([]string, error)

	SetTPRatingPlans(string, map[string][]*utils.TPRatingPlanBinding) error
	GetTpRatingPlans(string, string) (map[string][]*utils.TPRatingPlanBinding, error)
	GetTPRatingPlanIds(string) ([]string, error)

	SetTPRatingProfiles(string, map[string]*utils.TPRatingProfile) error
	GetTpRatingProfiles(*utils.TPRatingProfile) (map[string]*utils.TPRatingProfile, error)
	GetTPRatingProfileIds(*utils.AttrTPRatingProfileIds) ([]string, error)

	SetTPActions(string, map[string][]*utils.TPAction) error
	GetTpActions(string, string) (map[string][]*utils.TPAction, error)
	GetTPActionIds(string) ([]string, error)

	SetTPActionTimings(string, map[string][]*utils.TPActionTiming) error
	GetTPActionTimings(string, string) (map[string][]*utils.TPActionTiming, error)
	GetTPActionTimingIds(string) ([]string, error)

	SetTPActionTriggers(string, map[string][]*utils.TPActionTrigger) error
	GetTpActionTriggers(string, string) (map[string][]*utils.TPActionTrigger, error)
	GetTPActionTriggerIds(string) ([]string, error)

	SetTPAccountActions(string, map[string]*utils.TPAccountActions) error
	GetTpAccountActions(*utils.TPAccountActions) (map[string]*utils.TPAccountActions, error)
	GetTPAccountActionIds(string) ([]string, error)
}

func ConfigureLoadStorage

func ConfigureLoadStorage(db_type, host, port, name, user, pass, marshaler string) (db LoadStorage, err error)

type LogCostEntry

type LogCostEntry struct {
	Id       string `bson:"_id,omitempty"`
	CallCost *CallCost
	Source   string
}

type LogErrEntry

type LogErrEntry struct {
	Id     string `bson:"_id,omitempty"`
	ErrStr string
	Source string
}

type LogStorage

type LogStorage interface {
	Storage
	//GetAllActionTimingsLogs() (map[string]ActionsTimings, error)
	LogCallCost(uuid, source, runid string, cc *CallCost) error
	LogError(uuid, source, runid, errstr string) error
	LogActionTrigger(ubId, source string, at *ActionTrigger, as Actions) error
	LogActionTiming(source string, at *ActionTiming, as Actions) error
	GetCallCostLog(uuid, source, runid string) (*CallCost, error)
}

func ConfigureLogStorage

func ConfigureLogStorage(db_type, host, port, name, user, pass, marshaler string) (db LogStorage, err error)

type LogTimingEntry

type LogTimingEntry struct {
	ActionTiming *ActionTiming
	Actions      Actions
	LogTime      time.Time
	Source       string
}

type LogTriggerEntry

type LogTriggerEntry struct {
	ActionTrigger *ActionTrigger
	Actions       Actions
	LogTime       time.Time
	Source        string
	// contains filtered or unexported fields
}

type MapStorage

type MapStorage struct {
	// contains filtered or unexported fields
}

func NewMapStorage

func NewMapStorage() (*MapStorage, error)

func (*MapStorage) CacheAccounting

func (ms *MapStorage) CacheAccounting(actKeys []string) error

func (*MapStorage) CacheRating

func (ms *MapStorage) CacheRating(dKeys, rpKeys, rpfKeys []string) error

func (*MapStorage) Close

func (ms *MapStorage) Close()

func (*MapStorage) ExistsData

func (ms *MapStorage) ExistsData(categ, subject string) (bool, error)

Used to check if specific subject is stored using prefix key attached to entity

func (*MapStorage) Flush

func (ms *MapStorage) Flush() error

func (*MapStorage) GetActionTimings

func (ms *MapStorage) GetActionTimings(key string) (ats ActionTimings, err error)

func (*MapStorage) GetActions

func (ms *MapStorage) GetActions(key string, checkDb bool) (as Actions, err error)

func (*MapStorage) GetAllActionTimings

func (ms *MapStorage) GetAllActionTimings() (ats map[string]ActionTimings, err error)

func (*MapStorage) GetCallCostLog

func (ms *MapStorage) GetCallCostLog(uuid, source, runid string) (cc *CallCost, err error)

func (*MapStorage) GetDestination

func (ms *MapStorage) GetDestination(key string) (dest *Destination, err error)

func (*MapStorage) GetRatingPlan

func (ms *MapStorage) GetRatingPlan(key string, checkDb bool) (rp *RatingPlan, err error)

func (*MapStorage) GetRatingProfile

func (ms *MapStorage) GetRatingProfile(key string, checkDb bool) (rpf *RatingProfile, err error)

func (*MapStorage) GetUserBalance

func (ms *MapStorage) GetUserBalance(key string) (ub *UserBalance, err error)

func (*MapStorage) LogActionTiming

func (ms *MapStorage) LogActionTiming(source string, at *ActionTiming, as Actions) (err error)

func (*MapStorage) LogActionTrigger

func (ms *MapStorage) LogActionTrigger(ubId, source string, at *ActionTrigger, as Actions) (err error)

func (*MapStorage) LogCallCost

func (ms *MapStorage) LogCallCost(uuid, source, runid string, cc *CallCost) error

func (*MapStorage) LogError

func (ms *MapStorage) LogError(uuid, source, runid, errstr string) (err error)

func (*MapStorage) SetActionTimings

func (ms *MapStorage) SetActionTimings(key string, ats ActionTimings) (err error)

func (*MapStorage) SetActions

func (ms *MapStorage) SetActions(key string, as Actions) (err error)

func (*MapStorage) SetDestination

func (ms *MapStorage) SetDestination(dest *Destination) (err error)

func (*MapStorage) SetRatingPlan

func (ms *MapStorage) SetRatingPlan(rp *RatingPlan) (err error)

func (*MapStorage) SetRatingProfile

func (ms *MapStorage) SetRatingProfile(rpf *RatingProfile) (err error)

func (*MapStorage) SetUserBalance

func (ms *MapStorage) SetUserBalance(ub *UserBalance) (err error)

type Marshaler

type Marshaler interface {
	Marshal(v interface{}) ([]byte, error)
	Unmarshal(data []byte, v interface{}) error
}

type MinuteInfo

type MinuteInfo struct {
	DestinationId string
	Quantity      float64
	Price         float64
}

Holds the minute information related to a specified timespan

type MongoStorage

type MongoStorage struct {
	// contains filtered or unexported fields
}

func (*MongoStorage) Close

func (ms *MongoStorage) Close()

func (*MongoStorage) Flush

func (ms *MongoStorage) Flush() (err error)

func (*MongoStorage) GetActionTimings

func (ms *MongoStorage) GetActionTimings(key string) (ats ActionTimings, err error)

func (*MongoStorage) GetActions

func (ms *MongoStorage) GetActions(key string) (as Actions, err error)

func (*MongoStorage) GetAllActionTimings

func (ms *MongoStorage) GetAllActionTimings() (ats map[string]ActionTimings, err error)

func (*MongoStorage) GetCallCostLog

func (ms *MongoStorage) GetCallCostLog(uuid, source string) (cc *CallCost, err error)

func (*MongoStorage) GetDestination

func (ms *MongoStorage) GetDestination(key string) (result *Destination, err error)

func (*MongoStorage) GetRatingPlan

func (ms *MongoStorage) GetRatingPlan(key string) (rp *RatingPlan, err error)

func (*MongoStorage) GetRatingProfile

func (ms *MongoStorage) GetRatingProfile(key string) (rp *RatingProfile, err error)

func (*MongoStorage) GetUserBalance

func (ms *MongoStorage) GetUserBalance(key string) (result *UserBalance, err error)

func (*MongoStorage) LogActionTiming

func (ms *MongoStorage) LogActionTiming(source string, at *ActionTiming, as Actions) (err error)

func (*MongoStorage) LogActionTrigger

func (ms *MongoStorage) LogActionTrigger(ubId, source string, at *ActionTrigger, as Actions) (err error)

func (*MongoStorage) LogCallCost

func (ms *MongoStorage) LogCallCost(uuid, source string, cc *CallCost) error

func (*MongoStorage) LogError

func (ms *MongoStorage) LogError(uuid, source, errstr string) (err error)

func (*MongoStorage) SetActionTimings

func (ms *MongoStorage) SetActionTimings(key string, ats ActionTimings) error

func (*MongoStorage) SetActions

func (ms *MongoStorage) SetActions(key string, as Actions) error

func (*MongoStorage) SetDestination

func (ms *MongoStorage) SetDestination(dest *Destination) error

func (*MongoStorage) SetRatingPlan

func (ms *MongoStorage) SetRatingPlan(rp *RatingPlan) error

func (*MongoStorage) SetRatingProfile

func (ms *MongoStorage) SetRatingProfile(rp *RatingProfile) error

func (*MongoStorage) SetUserBalance

func (ms *MongoStorage) SetUserBalance(ub *UserBalance) error

type MySQLStorage

type MySQLStorage struct {
	*SQLStorage
}

type PostgresStorage

type PostgresStorage struct {
	*SQLStorage
}

type RIRate

type RIRate struct {
	ConnectFee       float64
	Rates            RateGroups // GroupRateInterval (start time): Rate
	RoundingMethod   string     //ROUNDING_UP, ROUNDING_DOWN, ROUNDING_MIDDLE
	RoundingDecimals int
}

Separate structure used for rating plan size optimization

func (*RIRate) Stringify

func (rir *RIRate) Stringify() string

type RITiming

type RITiming struct {
	Years              utils.Years
	Months             utils.Months
	MonthDays          utils.MonthDays
	WeekDays           utils.WeekDays
	StartTime, EndTime string // ##:##:## format
}

Separate structure used for rating plan size optimization

func (*RITiming) Stringify

func (rit *RITiming) Stringify() string

type RPCClientConnector

type RPCClientConnector struct {
	Client *rpc.Client
}

func (*RPCClientConnector) Debit

func (rcc *RPCClientConnector) Debit(cd CallDescriptor, cc *CallCost) error

func (*RPCClientConnector) DebitCents

func (rcc *RPCClientConnector) DebitCents(cd CallDescriptor, resp *float64) error

func (*RPCClientConnector) DebitSeconds

func (rcc *RPCClientConnector) DebitSeconds(cd CallDescriptor, resp *float64) error

func (*RPCClientConnector) GetCost

func (rcc *RPCClientConnector) GetCost(cd CallDescriptor, cc *CallCost) error

func (*RPCClientConnector) GetMaxSessionTime

func (rcc *RPCClientConnector) GetMaxSessionTime(cd CallDescriptor, resp *float64) error

func (*RPCClientConnector) MaxDebit

func (rcc *RPCClientConnector) MaxDebit(cd CallDescriptor, cc *CallCost) error

func (*RPCClientConnector) RefundIncrements

func (rcc *RPCClientConnector) RefundIncrements(cd CallDescriptor, resp *float64) error

type RPRate

type RPRate struct {
	Timing string
	Rating string
	Weight float64
}

func (*RPRate) Equal

func (rpr *RPRate) Equal(orpr *RPRate) bool

type RPRateList

type RPRateList []*RPRate

type Rate

type Rate struct {
	GroupIntervalStart time.Duration
	Value              float64
	RateIncrement      time.Duration
	RateUnit           time.Duration
}

func (*Rate) Equal

func (p *Rate) Equal(o *Rate) bool

func (*Rate) Stringify

func (r *Rate) Stringify() string

type RateGroups

type RateGroups []*Rate

func (*RateGroups) AddRate

func (pg *RateGroups) AddRate(ps ...*Rate)

func (RateGroups) Equal

func (pg RateGroups) Equal(og RateGroups) bool

func (RateGroups) Len

func (pg RateGroups) Len() int

func (RateGroups) Less

func (pg RateGroups) Less(i, j int) bool

func (RateGroups) Sort

func (pg RateGroups) Sort()

func (RateGroups) Swap

func (pg RateGroups) Swap(i, j int)

type RateInterval

type RateInterval struct {
	Timing *RITiming
	Rating *RIRate
	Weight float64
}

Defines a time interval for which a certain set of prices will apply

func GetRateInterval

func GetRateInterval(rpl *utils.TPRatingPlanBinding, dr *utils.DestinationRate) (i *RateInterval)

func (*RateInterval) Contains

func (i *RateInterval) Contains(t time.Time, endTime bool) bool

Returns true if the received time result inside the interval

func (*RateInterval) Equal

func (i *RateInterval) Equal(o *RateInterval) bool

func (*RateInterval) GetCost

func (i *RateInterval) GetCost(duration, startSecond time.Duration) float64

func (*RateInterval) GetRateParameters

func (i *RateInterval) GetRateParameters(startSecond time.Duration) (price float64, rateIncrement, rateUnit time.Duration)

Gets the price for a the provided start second

func (*RateInterval) String_DISABLED

func (i *RateInterval) String_DISABLED() string

type RateIntervalList

type RateIntervalList []*RateInterval

Structure to store intervals according to weight

func (RateIntervalList) Len

func (il RateIntervalList) Len() int

func (RateIntervalList) Less

func (il RateIntervalList) Less(i, j int) bool

func (RateIntervalList) Sort

func (il RateIntervalList) Sort()

func (RateIntervalList) Swap

func (il RateIntervalList) Swap(i, j int)

type RatingInfo

type RatingInfo struct {
	MatchedSubject string
	MatchedPrefix  string
	ActivationTime time.Time
	RateIntervals  RateIntervalList
	FallbackKeys   []string
}

type RatingInfos

type RatingInfos []*RatingInfo

func (RatingInfos) Len

func (ris RatingInfos) Len() int

func (RatingInfos) Less

func (ris RatingInfos) Less(i, j int) bool

func (RatingInfos) Sort

func (ris RatingInfos) Sort()

func (RatingInfos) Swap

func (ris RatingInfos) Swap(i, j int)

type RatingPlan

type RatingPlan struct {
	Id               string
	Timings          map[string]*RITiming
	Ratings          map[string]*RIRate
	DestinationRates map[string]RPRateList
}

The struture that is saved to storage.

func (*RatingPlan) AddRateInterval

func (rp *RatingPlan) AddRateInterval(dId string, ris ...*RateInterval)

Adds one ore more intervals to the internal interval list only if it is not allready in the list.

func (*RatingPlan) Equal

func (rp *RatingPlan) Equal(o *RatingPlan) bool

func (*RatingPlan) RateIntervalList

func (rp *RatingPlan) RateIntervalList(dId string) RateIntervalList

type RatingPlanActivation

type RatingPlanActivation struct {
	ActivationTime time.Time
	RatingPlanId   string
	FallbackKeys   []string
}

func (*RatingPlanActivation) Equal

type RatingPlanActivations

type RatingPlanActivations []*RatingPlanActivation

func (RatingPlanActivations) GetActiveForCall

func (rpas RatingPlanActivations) GetActiveForCall(cd *CallDescriptor) RatingPlanActivations

func (RatingPlanActivations) Len

func (rpas RatingPlanActivations) Len() int

func (RatingPlanActivations) Less

func (rpas RatingPlanActivations) Less(i, j int) bool

func (RatingPlanActivations) Sort

func (rpas RatingPlanActivations) Sort()

func (RatingPlanActivations) Swap

func (rpas RatingPlanActivations) Swap(i, j int)

type RatingProfile

type RatingProfile struct {
	Id                    string
	RatingPlanActivations RatingPlanActivations
}

func (*RatingProfile) GetRatingPlansForPrefix

func (rp *RatingProfile) GetRatingPlansForPrefix(cd *CallDescriptor) (err error)

type RatingStorage

type RatingStorage interface {
	Storage
	CacheRating([]string, []string, []string) error
	ExistsData(string, string) (bool, error)
	GetRatingPlan(string, bool) (*RatingPlan, error)
	SetRatingPlan(*RatingPlan) error
	GetRatingProfile(string, bool) (*RatingProfile, error)
	SetRatingProfile(*RatingProfile) error
	GetDestination(string) (*Destination, error)
	SetDestination(*Destination) error
}

Interface for storage providers.

func ConfigureRatingStorage

func ConfigureRatingStorage(db_type, host, port, name, user, pass, marshaler string) (db RatingStorage, err error)

type RedisStorage

type RedisStorage struct {
	// contains filtered or unexported fields
}

func NewRedisStorage

func NewRedisStorage(address string, db int, pass, mrshlerStr string) (*RedisStorage, error)

func (*RedisStorage) CacheAccounting

func (rs *RedisStorage) CacheAccounting(actKeys []string) (err error)

func (*RedisStorage) CacheRating

func (rs *RedisStorage) CacheRating(dKeys, rpKeys, rpfKeys []string) (err error)

func (*RedisStorage) Close

func (rs *RedisStorage) Close()

func (*RedisStorage) ExistsData

func (rs *RedisStorage) ExistsData(category, subject string) (bool, error)

Used to check if specific subject is stored using prefix key attached to entity

func (*RedisStorage) Flush

func (rs *RedisStorage) Flush() (err error)

func (*RedisStorage) GetActionTimings

func (rs *RedisStorage) GetActionTimings(key string) (ats ActionTimings, err error)

func (*RedisStorage) GetActions

func (rs *RedisStorage) GetActions(key string, checkDb bool) (as Actions, err error)

func (*RedisStorage) GetAllActionTimings

func (rs *RedisStorage) GetAllActionTimings() (ats map[string]ActionTimings, err error)

func (*RedisStorage) GetCallCostLog

func (rs *RedisStorage) GetCallCostLog(uuid, source, runid string) (cc *CallCost, err error)

func (*RedisStorage) GetDestination

func (rs *RedisStorage) GetDestination(key string) (dest *Destination, err error)

func (*RedisStorage) GetRatingPlan

func (rs *RedisStorage) GetRatingPlan(key string, checkDb bool) (rp *RatingPlan, err error)

func (*RedisStorage) GetRatingProfile

func (rs *RedisStorage) GetRatingProfile(key string, checkDb bool) (rpf *RatingProfile, err error)

func (*RedisStorage) GetUserBalance

func (rs *RedisStorage) GetUserBalance(key string) (ub *UserBalance, err error)

func (*RedisStorage) LogActionTiming

func (rs *RedisStorage) LogActionTiming(source string, at *ActionTiming, as Actions) (err error)

func (*RedisStorage) LogActionTrigger

func (rs *RedisStorage) LogActionTrigger(ubId, source string, at *ActionTrigger, as Actions) (err error)

func (*RedisStorage) LogCallCost

func (rs *RedisStorage) LogCallCost(uuid, source, runid string, cc *CallCost) (err error)

func (*RedisStorage) LogError

func (rs *RedisStorage) LogError(uuid, source, runid, errstr string) (err error)

func (*RedisStorage) SetActionTimings

func (rs *RedisStorage) SetActionTimings(key string, ats ActionTimings) (err error)

func (*RedisStorage) SetActions

func (rs *RedisStorage) SetActions(key string, as Actions) (err error)

func (*RedisStorage) SetDestination

func (rs *RedisStorage) SetDestination(dest *Destination) (err error)

func (*RedisStorage) SetRatingPlan

func (rs *RedisStorage) SetRatingPlan(rp *RatingPlan) (err error)

func (*RedisStorage) SetRatingProfile

func (rs *RedisStorage) SetRatingProfile(rpf *RatingProfile) (err error)

func (*RedisStorage) SetUserBalance

func (rs *RedisStorage) SetUserBalance(ub *UserBalance) (err error)

type Responder

type Responder struct {
	Bal      *balancer2go.Balancer
	ExitChan chan bool
}

func (*Responder) AddRecievedCallSeconds

func (rs *Responder) AddRecievedCallSeconds(arg CallDescriptor, reply *float64) (err error)

func (*Responder) Debit

func (rs *Responder) Debit(arg CallDescriptor, reply *CallCost) (err error)

func (*Responder) DebitCents

func (rs *Responder) DebitCents(arg CallDescriptor, reply *float64) (err error)

func (*Responder) DebitSMS

func (rs *Responder) DebitSMS(arg CallDescriptor, reply *float64) (err error)

func (*Responder) DebitSeconds

func (rs *Responder) DebitSeconds(arg CallDescriptor, reply *float64) (err error)

func (*Responder) FlushCache

func (rs *Responder) FlushCache(arg CallDescriptor, reply *float64) (err error)

func (*Responder) GetCost

func (rs *Responder) GetCost(arg CallDescriptor, reply *CallCost) (err error)

RPC method thet provides the external RPC interface for getting the rating information.

func (*Responder) GetInternet

func (rs *Responder) GetInternet(arg CallDescriptor, reply *CallCost) (err error)

func (*Responder) GetInternetTime

func (rs *Responder) GetInternetTime(arg CallDescriptor, reply *CallCost) (err error)

func (*Responder) GetMaxSessionTime

func (rs *Responder) GetMaxSessionTime(arg CallDescriptor, reply *float64) (err error)

func (*Responder) GetMinutes

func (rs *Responder) GetMinutes(arg CallDescriptor, reply *CallCost) (err error)

func (*Responder) GetMonetary

func (rs *Responder) GetMonetary(arg CallDescriptor, reply *CallCost) (err error)

func (*Responder) GetSMS

func (rs *Responder) GetSMS(arg CallDescriptor, reply *CallCost) (err error)

func (*Responder) MaxDebit

func (rs *Responder) MaxDebit(arg CallDescriptor, reply *CallCost) (err error)

func (*Responder) RefundIncrements

func (rs *Responder) RefundIncrements(arg CallDescriptor, reply *float64) (err error)

func (*Responder) RegisterRater

func (rs *Responder) RegisterRater(clientAddress string, replay *int) error

RPC method that receives a rater address, connects to it and ads the pair to the rater list for balancing

func (*Responder) Shutdown

func (rs *Responder) Shutdown(arg string, reply *string) (err error)

func (*Responder) Status

func (rs *Responder) Status(arg string, reply *string) (err error)

func (*Responder) UnRegisterRater

func (rs *Responder) UnRegisterRater(clientAddress string, replay *int) error

RPC method that recives a rater addres gets the connections and closes it and removes the pair from rater list.

type ResponderWorker

type ResponderWorker struct{}

Reflection worker type for not standalone balancer

func (*ResponderWorker) Call

func (rw *ResponderWorker) Call(serviceMethod string, args interface{}, reply interface{}) error

func (*ResponderWorker) Close

func (rw *ResponderWorker) Close() error

type SQLStorage

type SQLStorage struct {
	Db *sql.DB
}

func (*SQLStorage) Close

func (self *SQLStorage) Close()

func (*SQLStorage) CreateTablesFromScript

func (self *SQLStorage) CreateTablesFromScript(scriptPath string) error

func (*SQLStorage) Flush

func (self *SQLStorage) Flush() (err error)

func (*SQLStorage) GetCallCostLog

func (self *SQLStorage) GetCallCostLog(cgrid, source, runid string) (cc *CallCost, err error)

func (*SQLStorage) GetRatedCdrs

func (self *SQLStorage) GetRatedCdrs(timeStart, timeEnd time.Time) ([]*utils.RatedCDR, error)

Return a slice of rated CDRs from storDb using optional timeStart and timeEnd as filters.

func (*SQLStorage) GetTPAccountActionIds

func (self *SQLStorage) GetTPAccountActionIds(tpid string) ([]string, error)

func (*SQLStorage) GetTPActionIds

func (self *SQLStorage) GetTPActionIds(tpid string) ([]string, error)

func (*SQLStorage) GetTPActionTimingIds

func (self *SQLStorage) GetTPActionTimingIds(tpid string) ([]string, error)

func (*SQLStorage) GetTPActionTimings

func (self *SQLStorage) GetTPActionTimings(tpid, atId string) (map[string][]*utils.TPActionTiming, error)

func (*SQLStorage) GetTPActionTriggerIds

func (self *SQLStorage) GetTPActionTriggerIds(tpid string) ([]string, error)

func (*SQLStorage) GetTPActions

func (self *SQLStorage) GetTPActions(tpid, actsId string) (*utils.TPActions, error)

func (*SQLStorage) GetTPDestination

func (self *SQLStorage) GetTPDestination(tpid, destTag string) (*Destination, error)

Extracts destinations from StorDB on specific tariffplan id

func (*SQLStorage) GetTPDestinationIds

func (self *SQLStorage) GetTPDestinationIds(tpid string) ([]string, error)

Extracts destinations from StorDB on specific tariffplan id

func (*SQLStorage) GetTPDestinationRateIds

func (self *SQLStorage) GetTPDestinationRateIds(tpid string) ([]string, error)

func (*SQLStorage) GetTPIds

func (self *SQLStorage) GetTPIds() ([]string, error)

Return a list with all TPids defined in the system, even if incomplete, isolated in some table.

func (*SQLStorage) GetTPRateIds

func (self *SQLStorage) GetTPRateIds(tpid string) ([]string, error)

func (*SQLStorage) GetTPRatingPlanIds

func (self *SQLStorage) GetTPRatingPlanIds(tpid string) ([]string, error)

func (*SQLStorage) GetTPRatingProfileIds

func (self *SQLStorage) GetTPRatingProfileIds(filters *utils.AttrTPRatingProfileIds) ([]string, error)

func (*SQLStorage) GetTPTimingIds

func (self *SQLStorage) GetTPTimingIds(tpid string) ([]string, error)

func (*SQLStorage) GetTpAccountActions

func (self *SQLStorage) GetTpAccountActions(aaFltr *utils.TPAccountActions) (map[string]*utils.TPAccountActions, error)

func (*SQLStorage) GetTpActionTriggers

func (self *SQLStorage) GetTpActionTriggers(tpid, tag string) (map[string][]*utils.TPActionTrigger, error)

func (*SQLStorage) GetTpActions

func (self *SQLStorage) GetTpActions(tpid, tag string) (map[string][]*utils.TPAction, error)

func (*SQLStorage) GetTpDestinationRates

func (self *SQLStorage) GetTpDestinationRates(tpid, tag string) (map[string]*utils.TPDestinationRate, error)

func (*SQLStorage) GetTpDestinations

func (self *SQLStorage) GetTpDestinations(tpid, tag string) ([]*Destination, error)

func (*SQLStorage) GetTpRates

func (self *SQLStorage) GetTpRates(tpid, tag string) (map[string]*utils.TPRate, error)

func (*SQLStorage) GetTpRatingPlans

func (self *SQLStorage) GetTpRatingPlans(tpid, tag string) (map[string][]*utils.TPRatingPlanBinding, error)

func (*SQLStorage) GetTpRatingProfiles

func (self *SQLStorage) GetTpRatingProfiles(qryRpf *utils.TPRatingProfile) (map[string]*utils.TPRatingProfile, error)

func (*SQLStorage) GetTpTimings

func (self *SQLStorage) GetTpTimings(tpid, tag string) (map[string]*utils.TPTiming, error)

func (*SQLStorage) LogActionTiming

func (self *SQLStorage) LogActionTiming(source string, at *ActionTiming, as Actions) (err error)

func (*SQLStorage) LogActionTrigger

func (self *SQLStorage) LogActionTrigger(ubId, source string, at *ActionTrigger, as Actions) (err error)

func (*SQLStorage) LogCallCost

func (self *SQLStorage) LogCallCost(uuid, source, runid string, cc *CallCost) (err error)

func (*SQLStorage) LogError

func (self *SQLStorage) LogError(uuid, source, runid, errstr string) (err error)

func (*SQLStorage) RemRatedCdrs

func (self *SQLStorage) RemRatedCdrs(cgrIds []string) error

Remove CDR data out of all CDR tables based on their cgrid

func (*SQLStorage) RemTPData

func (self *SQLStorage) RemTPData(table, tpid string, args ...string) error

func (*SQLStorage) SetCdr

func (self *SQLStorage) SetCdr(cdr utils.RawCDR) (err error)

func (*SQLStorage) SetRatedCdr

func (self *SQLStorage) SetRatedCdr(ratedCdr *utils.RatedCDR, extraInfo string) (err error)

func (*SQLStorage) SetTPAccountActions

func (self *SQLStorage) SetTPAccountActions(tpid string, aa map[string]*utils.TPAccountActions) error

Sets a group of account actions. Map key has the role of grouping within a tpid

func (*SQLStorage) SetTPActionTimings

func (self *SQLStorage) SetTPActionTimings(tpid string, ats map[string][]*utils.TPActionTiming) error

Sets actionTimings in sqlDB. Imput is expected in form map[actionTimingId][]rows, eg a full .csv file content

func (*SQLStorage) SetTPActionTriggers

func (self *SQLStorage) SetTPActionTriggers(tpid string, ats map[string][]*utils.TPActionTrigger) error

func (*SQLStorage) SetTPActions

func (self *SQLStorage) SetTPActions(tpid string, acts map[string][]*utils.TPAction) error

func (*SQLStorage) SetTPDestination

func (self *SQLStorage) SetTPDestination(tpid string, dest *Destination) error

func (*SQLStorage) SetTPDestinationRates

func (self *SQLStorage) SetTPDestinationRates(tpid string, drs map[string][]*utils.DestinationRate) error

func (*SQLStorage) SetTPRates

func (self *SQLStorage) SetTPRates(tpid string, rts map[string][]*utils.RateSlot) error

func (*SQLStorage) SetTPRatingPlans

func (self *SQLStorage) SetTPRatingPlans(tpid string, drts map[string][]*utils.TPRatingPlanBinding) error

func (*SQLStorage) SetTPRatingProfiles

func (self *SQLStorage) SetTPRatingProfiles(tpid string, rps map[string]*utils.TPRatingProfile) error

func (*SQLStorage) SetTPTiming

func (self *SQLStorage) SetTPTiming(tpid string, tm *utils.TPTiming) error

type Storage

type Storage interface {
	Close()
	Flush() error
}

func NewMongoStorage

func NewMongoStorage(host, port, db, user, pass string) (Storage, error)

func NewMySQLStorage

func NewMySQLStorage(host, port, name, user, password string) (Storage, error)

func NewPostgresStorage

func NewPostgresStorage(host, port, name, user, password string) (Storage, error)

type TPCSVFileParser

type TPCSVFileParser struct {
	// contains filtered or unexported fields
}

Opens the connection to a file and returns the parsed lines one by one when ParseNextLine() is called

func NewTPCSVFileParser

func NewTPCSVFileParser(dirPath, fileName string) (*TPCSVFileParser, error)

func (*TPCSVFileParser) ParseNextLine

func (self *TPCSVFileParser) ParseNextLine() ([]string, error)

type TPCSVImporter

type TPCSVImporter struct {
	TPid     string      // Load data on this tpid
	StorDb   LoadStorage // StorDb connection handle
	DirPath  string      // Directory path to import from
	Sep      rune        // Separator in the csv file
	Verbose  bool        // If true will print a detailed information instead of silently discarding it
	ImportId string      // Use this to differentiate between imports (eg: when autogenerating fields like RatingProfileId
}

Import tariff plan from csv into storDb

func (*TPCSVImporter) Run

func (self *TPCSVImporter) Run() error

type TPLoader

type TPLoader interface {
	LoadDestinations() error
	LoadRates() error
	LoadDestinationRates() error
	LoadTimings() error
	LoadRatingPlans() error
	LoadRatingProfiles() error
	LoadActions() error
	LoadActionTimings() error
	LoadActionTriggers() error
	LoadAccountActions() error
	LoadAll() error
	GetLoadedIds(string) ([]string, error)
	ShowStatistics()
	WriteToDatabase(bool, bool) error
}

type TimeSpan

type TimeSpan struct {
	TimeStart, TimeEnd time.Time
	Cost               float64

	RateInterval                  *RateInterval
	CallDuration                  time.Duration // the call duration so far till TimeEnd
	Increments                    Increments
	MatchedSubject, MatchedPrefix string
	// contains filtered or unexported fields
}

A unit in which a call will be split that has a specific price related interval attached to it.

func (*TimeSpan) Contains

func (ts *TimeSpan) Contains(t time.Time) bool

Returns true if the given time is inside timespan range.

func (*TimeSpan) GetDuration

func (ts *TimeSpan) GetDuration() time.Duration

Returns the duration of the timespan

func (*TimeSpan) GetGroupEnd

func (ts *TimeSpan) GetGroupEnd() time.Duration

func (*TimeSpan) GetGroupStart

func (ts *TimeSpan) GetGroupStart() time.Duration

Returns the starting time of this timespan

func (*TimeSpan) GetTimeStartForIncrement

func (ts *TimeSpan) GetTimeStartForIncrement(index int) time.Time

returns a time for the specified second in the time span

func (*TimeSpan) IsPaid

func (ts *TimeSpan) IsPaid() (bool, int)

returns whether the timespan has all increments marked as paid and if not it also returns the first unpaied increment

func (*TimeSpan) RoundToDuration

func (ts *TimeSpan) RoundToDuration(duration time.Duration)

func (*TimeSpan) SetNewCallDuration

func (ts *TimeSpan) SetNewCallDuration(nts *TimeSpan)

sets the CallDuration attribute to reflect new timespan

func (*TimeSpan) SetRateInterval

func (ts *TimeSpan) SetRateInterval(i *RateInterval)

Will set the interval as spans's interval if new Weight is lower then span's interval Weight or if the Weights are equal and new price is lower then spans's interval price

func (*TimeSpan) SplitByDuration

func (ts *TimeSpan) SplitByDuration(duration time.Duration) *TimeSpan

Split the timespan at the given second

func (*TimeSpan) SplitByIncrement

func (ts *TimeSpan) SplitByIncrement(index int) *TimeSpan

Split the timespan at the given increment start

func (*TimeSpan) SplitByRateInterval

func (ts *TimeSpan) SplitByRateInterval(i *RateInterval) (nts *TimeSpan)

Splits the given timespan according to how it relates to the interval. It will modify the endtime of the received timespan and it will return a new timespan starting from the end of the received one. The interval will attach itself to the timespan that overlaps the interval.

func (*TimeSpan) SplitByRatingPlan

func (ts *TimeSpan) SplitByRatingPlan(rp *RatingInfo) (newTs *TimeSpan)

Splits the given timespan on activation period's activation time.

type TimeSpans

type TimeSpans []*TimeSpan

func (*TimeSpans) OverlapWithTimeSpans

func (timespans *TimeSpans) OverlapWithTimeSpans(paidTs TimeSpans, newTs *TimeSpan, index int) bool

The paidTs will replace the timespans that are exactly under them from the reciver list

func (*TimeSpans) RemoveOverlapedFromIndex

func (timespans *TimeSpans) RemoveOverlapedFromIndex(index int)

type UnitsCounter

type UnitsCounter struct {
	Direction string
	BalanceId string
	//	Units     float64
	Balances BalanceChain // first balance is the general one (no destination)
}

Amount of a trafic of a certain type

func (*UnitsCounter) GetGeneralBalance

func (uc *UnitsCounter) GetGeneralBalance() *Balance

returns the first balance that has no destination attached

type UserBalance

type UserBalance struct {
	Id             string
	Type           string // prepaid-postpaid
	BalanceMap     map[string]BalanceChain
	UnitCounters   []*UnitsCounter
	ActionTriggers ActionTriggerPriotityList
	Groups         GroupLinks // user info about groups
	// group information
	UserIds []string // group info about users
}

Structure containing information about user's credit (minutes, cents, sms...).' This can represent a user or a shared group.

func (*UserBalance) CleanExpiredBalancesAndBuckets

func (ub *UserBalance) CleanExpiredBalancesAndBuckets()

func (*UserBalance) GetDefaultMoneyBalance

func (ub *UserBalance) GetDefaultMoneyBalance(direction string) *Balance

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL