From 7b5f6154ed87283ca3f837cd415657beb6d70d8f Mon Sep 17 00:00:00 2001 From: Trial97 Date: Tue, 30 Mar 2021 09:03:41 +0300 Subject: [PATCH] Remove in progress --- apier/v1/api_interfaces.go | 29 - apier/v1/api_interfaces_test.go | 5 - apier/v1/apier.go | 560 +---- apier/v1/apier_it_test.go | 1082 +-------- apier/v1/auth.go | 73 - apier/v1/costs.go | 114 - apier/v1/costs_it_test.go | 133 -- apier/v1/debit.go | 90 - apier/v1/debit_test.go | 165 -- apier/v1/dispatcher.go | 209 -- apier/v1/rals.go | 113 - apier/v1/replicator.go | 303 --- apier/v1/tpaccountactions.go | 149 -- apier/v1/tpaccountactions_it_test.go | 231 -- apier/v1/tpactionplans.go | 99 - apier/v1/tpactionplans_it_test.go | 242 -- apier/v1/tpactiontriggers.go | 94 - apier/v1/tpactiontriggers_it_test.go | 332 --- apier/v1/tpdestinationrates.go | 93 - apier/v1/tpdestinationrates_it_test.go | 202 -- apier/v1/tprates.go | 92 - apier/v1/tprates_it_test.go | 238 -- apier/v1/tpratingplans.go | 93 - apier/v1/tpratingplans_it_test.go | 237 -- apier/v1/tpratingprofiles.go | 161 -- apier/v1/tpratingprofiles_it_test.go | 287 --- apier/v1/tpsharedgroups.go | 90 - apier/v1/tpsharedgroups_it_test.go | 232 -- apier/v1/triggers.go | 604 ----- apier/v1/triggers_test.go | 208 -- apier/v2/apier.go | 197 -- cmd/cgr-engine/cgr-engine.go | 11 +- cmd/cgr-tester/parallel/parallel.go | 64 - cmd/cgr-tester/proc_event/proc_ev.go | 153 -- config/cachecfg.go | 8 - console/account_actionplan_get.go | 66 - console/account_actionplan_get_test.go | 54 - console/account_remove.go | 62 - console/account_remove_test.go | 54 - console/account_set.go | 65 - console/account_set_test.go | 54 - console/account_trigger_add.go | 66 - console/account_trigger_add_test.go | 55 - console/account_trigger_remove.go | 66 - console/account_trigger_remove_test.go | 53 - console/account_trigger_reset.go | 66 - console/account_trigger_reset_test.go | 53 - console/account_trigger_set.go | 66 - console/account_trigger_set_test.go | 53 - console/accounts.go | 72 - console/accounts_test.go | 65 - console/action_execute.go | 65 - console/action_execute_test.go | 54 - console/actionplan_get.go | 67 - console/actionplan_get_test.go | 54 - console/actionplan_remove.go | 66 - console/actionplan_remove_test.go | 54 - console/actionplan_set.go | 66 - console/actionplan_set_test.go | 54 - console/actions.go | 66 - console/actions_remove.go | 65 - console/actions_remove_test.go | 54 - console/actions_test.go | 54 - console/balance_add.go | 65 - console/balance_add_test.go | 54 - console/balance_debit.go | 66 - console/balance_debit_test.go | 54 - console/balance_remove.go | 64 - console/balance_remove_test.go | 53 - console/balance_set.go | 64 - console/balance_set_test.go | 54 - console/compute_actionplan_indexes.go | 65 - console/compute_actionplan_indexes_test.go | 55 - console/cost.go | 81 - console/cost_test.go | 70 - console/datacost.go | 80 - console/datacost_test.go | 70 - console/ping.go | 4 - console/ratingplan_cost.go | 66 - console/ratingplan_cost_test.go | 54 - console/ratingprofile.go | 66 - console/ratingprofile_ids.go | 64 - console/ratingprofile_ids_test.go | 54 - console/ratingprofile_remove.go | 71 - console/ratingprofile_remove_test.go | 81 - console/ratingprofile_set.go | 65 - console/ratingprofile_set_test.go | 54 - console/ratingprofile_test.go | 54 - console/sharedgroup.go | 64 - console/sharedgroup_test.go | 54 - console/trigger_remove.go | 66 - console/trigger_remove_test.go | 52 - console/trigger_set.go | 66 - console/trigger_set_test.go | 53 - console/triggers.go | 73 - console/triggers_test.go | 61 - dispatchers/rals.go | 53 - dispatchers/rals_it_test.go | 102 - dispatchers/replicator.go | 391 ---- dispatchers/responder.go | 123 - dispatchers/scheduler.go | 78 - dispatchers/scheduler_it_test.go | 79 - engine/account_test.go | 2369 -------------------- engine/action.go | 1028 --------- engine/responder.go | 348 +-- services/apierv1.go | 41 +- utils/apitpdata.go | 14 - utils/consts.go | 89 +- 108 files changed, 44 insertions(+), 15370 deletions(-) delete mode 100644 apier/v1/auth.go delete mode 100644 apier/v1/costs.go delete mode 100644 apier/v1/costs_it_test.go delete mode 100644 apier/v1/debit.go delete mode 100644 apier/v1/debit_test.go delete mode 100644 apier/v1/rals.go delete mode 100644 apier/v1/tpaccountactions.go delete mode 100644 apier/v1/tpaccountactions_it_test.go delete mode 100644 apier/v1/tpactionplans.go delete mode 100644 apier/v1/tpactionplans_it_test.go delete mode 100644 apier/v1/tpactiontriggers.go delete mode 100644 apier/v1/tpactiontriggers_it_test.go delete mode 100644 apier/v1/tpdestinationrates.go delete mode 100644 apier/v1/tpdestinationrates_it_test.go delete mode 100644 apier/v1/tprates.go delete mode 100644 apier/v1/tprates_it_test.go delete mode 100644 apier/v1/tpratingplans.go delete mode 100644 apier/v1/tpratingplans_it_test.go delete mode 100644 apier/v1/tpratingprofiles.go delete mode 100644 apier/v1/tpratingprofiles_it_test.go delete mode 100644 apier/v1/tpsharedgroups.go delete mode 100644 apier/v1/tpsharedgroups_it_test.go delete mode 100644 apier/v1/triggers.go delete mode 100644 apier/v1/triggers_test.go delete mode 100644 cmd/cgr-tester/parallel/parallel.go delete mode 100644 cmd/cgr-tester/proc_event/proc_ev.go delete mode 100644 console/account_actionplan_get.go delete mode 100644 console/account_actionplan_get_test.go delete mode 100644 console/account_remove.go delete mode 100644 console/account_remove_test.go delete mode 100644 console/account_set.go delete mode 100644 console/account_set_test.go delete mode 100644 console/account_trigger_add.go delete mode 100644 console/account_trigger_add_test.go delete mode 100644 console/account_trigger_remove.go delete mode 100644 console/account_trigger_remove_test.go delete mode 100644 console/account_trigger_reset.go delete mode 100644 console/account_trigger_reset_test.go delete mode 100644 console/account_trigger_set.go delete mode 100644 console/account_trigger_set_test.go delete mode 100644 console/accounts.go delete mode 100644 console/accounts_test.go delete mode 100644 console/action_execute.go delete mode 100644 console/action_execute_test.go delete mode 100644 console/actionplan_get.go delete mode 100644 console/actionplan_get_test.go delete mode 100644 console/actionplan_remove.go delete mode 100644 console/actionplan_remove_test.go delete mode 100644 console/actionplan_set.go delete mode 100644 console/actionplan_set_test.go delete mode 100644 console/actions.go delete mode 100644 console/actions_remove.go delete mode 100644 console/actions_remove_test.go delete mode 100644 console/actions_test.go delete mode 100644 console/balance_add.go delete mode 100644 console/balance_add_test.go delete mode 100644 console/balance_debit.go delete mode 100644 console/balance_debit_test.go delete mode 100644 console/balance_remove.go delete mode 100644 console/balance_remove_test.go delete mode 100644 console/balance_set.go delete mode 100644 console/balance_set_test.go delete mode 100644 console/compute_actionplan_indexes.go delete mode 100644 console/compute_actionplan_indexes_test.go delete mode 100644 console/cost.go delete mode 100644 console/cost_test.go delete mode 100644 console/datacost.go delete mode 100644 console/datacost_test.go delete mode 100644 console/ratingplan_cost.go delete mode 100644 console/ratingplan_cost_test.go delete mode 100755 console/ratingprofile.go delete mode 100644 console/ratingprofile_ids.go delete mode 100644 console/ratingprofile_ids_test.go delete mode 100644 console/ratingprofile_remove.go delete mode 100644 console/ratingprofile_remove_test.go delete mode 100644 console/ratingprofile_set.go delete mode 100644 console/ratingprofile_set_test.go delete mode 100644 console/ratingprofile_test.go delete mode 100644 console/sharedgroup.go delete mode 100644 console/sharedgroup_test.go delete mode 100644 console/trigger_remove.go delete mode 100644 console/trigger_remove_test.go delete mode 100644 console/trigger_set.go delete mode 100644 console/trigger_set_test.go delete mode 100644 console/triggers.go delete mode 100644 console/triggers_test.go delete mode 100644 dispatchers/rals.go delete mode 100644 dispatchers/rals_it_test.go delete mode 100644 dispatchers/responder.go delete mode 100644 dispatchers/scheduler.go delete mode 100644 dispatchers/scheduler_it_test.go delete mode 100644 engine/account_test.go delete mode 100644 engine/action.go diff --git a/apier/v1/api_interfaces.go b/apier/v1/api_interfaces.go index 4dd1427d6..110a6bc8e 100644 --- a/apier/v1/api_interfaces.go +++ b/apier/v1/api_interfaces.go @@ -106,7 +106,6 @@ type ResponderInterface interface { GetCost(arg *engine.CallDescriptorWithAPIOpts, reply *engine.CallCost) (err error) Debit(arg *engine.CallDescriptorWithAPIOpts, reply *engine.CallCost) (err error) MaxDebit(arg *engine.CallDescriptorWithAPIOpts, reply *engine.CallCost) (err error) - RefundIncrements(arg *engine.CallDescriptorWithAPIOpts, reply *engine.Account) (err error) RefundRounding(arg *engine.CallDescriptorWithAPIOpts, reply *float64) (err error) GetMaxSessionTime(arg *engine.CallDescriptorWithAPIOpts, reply *time.Duration) (err error) Shutdown(arg *utils.TenantWithAPIOpts, reply *string) (err error) @@ -163,11 +162,6 @@ type ServiceManagerV1Interface interface { Ping(ign *utils.CGREvent, reply *string) error } -type RALsV1Interface interface { - GetRatingPlansCost(arg *utils.RatingPlanCostArg, reply *dispatchers.RatingPlanCost) error - Ping(ign *utils.CGREvent, reply *string) error -} - type ConfigSv1Interface interface { GetConfig(section *config.SectionWithAPIOpts, reply *map[string]interface{}) (err error) ReloadConfig(section *config.ReloadArgs, reply *string) (err error) @@ -193,7 +187,6 @@ type RateProfileSv1Interface interface { type ReplicatorSv1Interface interface { Ping(ign *utils.CGREvent, reply *string) error - GetAccount(args *utils.StringWithAPIOpts, reply *engine.Account) error GetDestination(key *utils.StringWithAPIOpts, reply *engine.Destination) error GetReverseDestination(key *utils.StringWithAPIOpts, reply *[]string) error GetStatQueue(tntID *utils.TenantIDWithAPIOpts, reply *engine.StatQueue) error @@ -204,14 +197,6 @@ type ReplicatorSv1Interface interface { GetTiming(id *utils.StringWithAPIOpts, reply *utils.TPTiming) error GetResource(tntID *utils.TenantIDWithAPIOpts, reply *engine.Resource) error GetResourceProfile(tntID *utils.TenantIDWithAPIOpts, reply *engine.ResourceProfile) error - GetActionTriggers(id *utils.StringWithAPIOpts, reply *engine.ActionTriggers) error - GetSharedGroup(id *utils.StringWithAPIOpts, reply *engine.SharedGroup) error - GetActions(id *utils.StringWithAPIOpts, reply *engine.Actions) error - GetActionPlan(id *utils.StringWithAPIOpts, reply *engine.ActionPlan) error - GetAllActionPlans(_ *utils.StringWithAPIOpts, reply *map[string]*engine.ActionPlan) error - GetAccountActionPlans(id *utils.StringWithAPIOpts, reply *[]string) error - GetRatingPlan(id *utils.StringWithAPIOpts, reply *engine.RatingPlan) error - GetRatingProfile(id *utils.StringWithAPIOpts, reply *engine.RatingProfile) error GetRouteProfile(tntID *utils.TenantIDWithAPIOpts, reply *engine.RouteProfile) error GetAttributeProfile(tntID *utils.TenantIDWithAPIOpts, reply *engine.AttributeProfile) error GetChargerProfile(tntID *utils.TenantIDWithAPIOpts, reply *engine.ChargerProfile) error @@ -221,7 +206,6 @@ type ReplicatorSv1Interface interface { GetItemLoadIDs(itemID *utils.StringWithAPIOpts, reply *map[string]int64) error SetThresholdProfile(th *engine.ThresholdProfileWithAPIOpts, reply *string) error SetThreshold(th *engine.ThresholdWithAPIOpts, reply *string) error - SetAccount(acc *engine.AccountWithAPIOpts, reply *string) error SetDestination(dst *engine.DestinationWithAPIOpts, reply *string) error SetReverseDestination(dst *engine.DestinationWithAPIOpts, reply *string) error SetStatQueue(ssq *engine.StatQueueWithAPIOpts, reply *string) error @@ -230,23 +214,16 @@ type ReplicatorSv1Interface interface { SetTiming(tm *utils.TPTimingWithAPIOpts, reply *string) error SetResource(rs *engine.ResourceWithAPIOpts, reply *string) error SetResourceProfile(rs *engine.ResourceProfileWithAPIOpts, reply *string) error - SetActionTriggers(args *engine.SetActionTriggersArgWithAPIOpts, reply *string) error - SetSharedGroup(shg *engine.SharedGroupWithAPIOpts, reply *string) error SetActions(args *engine.SetActionsArgsWithAPIOpts, reply *string) error - SetRatingPlan(rp *engine.RatingPlanWithAPIOpts, reply *string) error - SetRatingProfile(rp *engine.RatingProfileWithAPIOpts, reply *string) error SetRouteProfile(sp *engine.RouteProfileWithAPIOpts, reply *string) error SetAttributeProfile(ap *engine.AttributeProfileWithAPIOpts, reply *string) error SetChargerProfile(cp *engine.ChargerProfileWithAPIOpts, reply *string) error SetDispatcherProfile(dpp *engine.DispatcherProfileWithAPIOpts, reply *string) error SetRateProfile(dpp *utils.RateProfileWithAPIOpts, reply *string) error - SetActionPlan(args *engine.SetActionPlanArgWithAPIOpts, reply *string) error - SetAccountActionPlans(args *engine.SetAccountActionPlansArgWithAPIOpts, reply *string) error SetDispatcherHost(dpp *engine.DispatcherHostWithAPIOpts, reply *string) error RemoveThreshold(args *utils.TenantIDWithAPIOpts, reply *string) error SetLoadIDs(args *utils.LoadIDsWithAPIOpts, reply *string) error RemoveDestination(id *utils.StringWithAPIOpts, reply *string) error - RemoveAccount(id *utils.StringWithAPIOpts, reply *string) error RemoveStatQueue(args *utils.TenantIDWithAPIOpts, reply *string) error RemoveFilter(args *utils.TenantIDWithAPIOpts, reply *string) error RemoveThresholdProfile(args *utils.TenantIDWithAPIOpts, reply *string) error @@ -254,13 +231,7 @@ type ReplicatorSv1Interface interface { RemoveTiming(id *utils.StringWithAPIOpts, reply *string) error RemoveResource(args *utils.TenantIDWithAPIOpts, reply *string) error RemoveResourceProfile(args *utils.TenantIDWithAPIOpts, reply *string) error - RemoveActionTriggers(id *utils.StringWithAPIOpts, reply *string) error - RemoveSharedGroup(id *utils.StringWithAPIOpts, reply *string) error RemoveActions(id *utils.StringWithAPIOpts, reply *string) error - RemoveActionPlan(id *utils.StringWithAPIOpts, reply *string) error - RemAccountActionPlans(args *engine.RemAccountActionPlansArgsWithAPIOpts, reply *string) error - RemoveRatingPlan(id *utils.StringWithAPIOpts, reply *string) error - RemoveRatingProfile(id *utils.StringWithAPIOpts, reply *string) error RemoveRouteProfile(args *utils.TenantIDWithAPIOpts, reply *string) error RemoveAttributeProfile(args *utils.TenantIDWithAPIOpts, reply *string) error RemoveChargerProfile(args *utils.TenantIDWithAPIOpts, reply *string) error diff --git a/apier/v1/api_interfaces_test.go b/apier/v1/api_interfaces_test.go index 633643f09..847b4e777 100644 --- a/apier/v1/api_interfaces_test.go +++ b/apier/v1/api_interfaces_test.go @@ -89,11 +89,6 @@ func TestServiceManagerV1Interface(t *testing.T) { _ = ServiceManagerV1Interface(NewServiceManagerV1(nil)) } -func TestRALsV1Interface(t *testing.T) { - _ = RALsV1Interface(NewDispatcherRALsV1(nil)) - _ = RALsV1Interface(NewRALsV1()) -} - func TestConfigSv1Interface(t *testing.T) { _ = ConfigSv1Interface(NewDispatcherConfigSv1(nil)) _ = ConfigSv1Interface(NewConfigSv1(nil)) diff --git a/apier/v1/apier.go b/apier/v1/apier.go index 992edf685..164f3ff20 100644 --- a/apier/v1/apier.go +++ b/apier/v1/apier.go @@ -20,7 +20,6 @@ package v1 import ( "encoding/csv" - "errors" "fmt" "os" "path" @@ -30,7 +29,6 @@ import ( "github.com/cgrates/cgrates/config" "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/guardian" "github.com/cgrates/cgrates/utils" ) @@ -39,12 +37,10 @@ type APIerSv1 struct { CdrDb engine.CdrStorage DataManager *engine.DataManager Config *config.CGRConfig - Responder *engine.Responder FilterS *engine.FilterS //Used for CDR Exporter ConnMgr *engine.ConnManager - StorDBChan chan engine.StorDB - ResponderChan chan *engine.Responder + StorDBChan chan engine.StorDB } // Call implements rpcclient.ClientConnector interface for internal RPC @@ -139,26 +135,6 @@ func (apierSv1 *APIerSv1) ComputeReverseDestinations(ignr *string, reply *string return } -// ComputeAccountActionPlans will rebuild complete reverse accountActions data -func (apierSv1 *APIerSv1) ComputeAccountActionPlans(ignr *string, reply *string) (err error) { - if err = apierSv1.DataManager.RebuildReverseForPrefix(utils.AccountActionPlansPrefix); err != nil { - return - } - *reply = utils.OK - return -} - -func (apierSv1 *APIerSv1) GetSharedGroup(sgId *string, reply *engine.SharedGroup) error { - if sg, err := apierSv1.DataManager.GetSharedGroup(*sgId, false, utils.NonTransactional); err != nil && err != utils.ErrNotFound { // Not found is not an error here - return err - } else { - if sg != nil { - *reply = *sg - } - } - return nil -} - func (apierSv1 *APIerSv1) SetDestination(attrs *utils.AttrSetDestination, reply *string) (err error) { if missing := utils.MissingStructFields(attrs, []string{"Id", "Prefixes"}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) @@ -189,59 +165,6 @@ func (apierSv1 *APIerSv1) SetDestination(attrs *utils.AttrSetDestination, reply return nil } -func (apierSv1 *APIerSv1) GetRatingPlan(rplnId *string, reply *engine.RatingPlan) error { - rpln, err := apierSv1.DataManager.GetRatingPlan(*rplnId, false, utils.NonTransactional) - if err != nil { - if err.Error() == utils.ErrNotFound.Error() { - return err - } - return utils.NewErrServerError(err) - } - *reply = *rpln - return nil -} - -func (apierSv1 *APIerSv1) RemoveRatingPlan(ID *string, reply *string) error { - if len(*ID) == 0 { - return utils.NewErrMandatoryIeMissing("ID") - } - err := apierSv1.DataManager.RemoveRatingPlan(*ID, utils.NonTransactional) - if err != nil { - return utils.NewErrServerError(err) - } - if err := apierSv1.ConnMgr.Call(apierSv1.Config.ApierCfg().CachesConns, nil, - utils.CacheSv1ReloadCache, utils.AttrReloadCacheWithAPIOpts{ - ArgsCache: map[string][]string{utils.RatingPlanIDs: {*ID}}, - }, reply); err != nil { - return err - } - //generate a loadID for CacheRatingPlans and store it in database - if err := apierSv1.DataManager.SetLoadIDs(map[string]int64{utils.CacheRatingPlans: time.Now().UnixNano()}); err != nil { - return utils.APIErrorHandler(err) - } - *reply = utils.OK - return nil -} - -func (apierSv1 *APIerSv1) ExecuteAction(attr *utils.AttrExecuteAction, reply *string) error { - at := &engine.ActionTiming{ - ActionsID: attr.ActionsId, - } - tnt := attr.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - if attr.Account != "" { - at.SetAccountIDs(utils.StringMap{utils.ConcatenatedKey(tnt, attr.Account): true}) - } - if err := at.Execute(nil, nil); err != nil { - *reply = err.Error() - return err - } - *reply = utils.OK - return nil -} - type AttrLoadDestination struct { TPid string ID string @@ -274,90 +197,11 @@ func (apierSv1 *APIerSv1) LoadDestination(attrs *AttrLoadDestination, reply *str return nil } -type AttrLoadRatingPlan struct { - TPid string - RatingPlanId string -} - -// Process dependencies and load a specific rating plan from storDb into dataDb. -func (apierSv1 *APIerSv1) LoadRatingPlan(attrs *AttrLoadRatingPlan, reply *string) error { - if len(attrs.TPid) == 0 { - return utils.NewErrMandatoryIeMissing("TPid") - } - dbReader, err := engine.NewTpReader(apierSv1.DataManager.DataDB(), apierSv1.StorDb, - attrs.TPid, apierSv1.Config.GeneralCfg().DefaultTimezone, - apierSv1.Config.ApierCfg().CachesConns, apierSv1.Config.ApierCfg().ActionConns, - apierSv1.Config.DataDbCfg().Type == utils.INTERNAL) - if err != nil { - return utils.NewErrServerError(err) - } - if loaded, err := dbReader.LoadRatingPlansFiltered(attrs.RatingPlanId); err != nil { - return utils.NewErrServerError(err) - } else if !loaded { - return utils.ErrNotFound - } - *reply = utils.OK - return nil -} - -// Process dependencies and load a specific rating profile from storDb into dataDb. -func (apierSv1 *APIerSv1) LoadRatingProfile(attrs *utils.TPRatingProfile, reply *string) error { - if len(attrs.TPid) == 0 { - return utils.NewErrMandatoryIeMissing("TPid") - } - if attrs.Tenant == utils.EmptyString { - attrs.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - dbReader, err := engine.NewTpReader(apierSv1.DataManager.DataDB(), apierSv1.StorDb, - attrs.TPid, apierSv1.Config.GeneralCfg().DefaultTimezone, - apierSv1.Config.ApierCfg().CachesConns, apierSv1.Config.ApierCfg().ActionConns, - apierSv1.Config.DataDbCfg().Type == utils.INTERNAL) - if err != nil { - return utils.NewErrServerError(err) - } - if err := dbReader.LoadRatingProfilesFiltered(attrs); err != nil { - return utils.NewErrServerError(err) - } - if err := apierSv1.DataManager.SetLoadIDs(map[string]int64{utils.CacheRatingProfiles: time.Now().UnixNano()}); err != nil { - return utils.APIErrorHandler(err) - } - if err = dbReader.ReloadCache(config.CgrConfig().GeneralCfg().DefaultCaching, true, make(map[string]interface{})); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -type AttrLoadSharedGroup struct { - TPid string - SharedGroupId string -} - -// Load destinations from storDb into dataDb. -func (apierSv1 *APIerSv1) LoadSharedGroup(attrs *AttrLoadSharedGroup, reply *string) error { - if len(attrs.TPid) == 0 { - return utils.NewErrMandatoryIeMissing("TPid") - } - dbReader, err := engine.NewTpReader(apierSv1.DataManager.DataDB(), apierSv1.StorDb, - attrs.TPid, apierSv1.Config.GeneralCfg().DefaultTimezone, - apierSv1.Config.ApierCfg().CachesConns, apierSv1.Config.ApierCfg().ActionConns, - apierSv1.Config.DataDbCfg().Type == utils.INTERNAL) - if err != nil { - return utils.NewErrServerError(err) - } - if err := dbReader.LoadSharedGroupsFiltered(attrs.SharedGroupId, true); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - type AttrLoadTpFromStorDb struct { - TPid string - DryRun bool // Only simulate, no write - Validate bool // Run structural checks - APIOpts map[string]interface{} - Caching *string // Caching strategy + TPid string + DryRun bool // Only simulate, no write + APIOpts map[string]interface{} + Caching *string // Caching strategy } // Loads complete data in a TP from storDb @@ -375,12 +219,6 @@ func (apierSv1 *APIerSv1) LoadTariffPlanFromStorDb(attrs *AttrLoadTpFromStorDb, if err := dbReader.LoadAll(); err != nil { return utils.NewErrServerError(err) } - if attrs.Validate { - if !dbReader.IsValid() { - *reply = utils.OK - return errors.New("invalid data") - } - } if attrs.DryRun { *reply = utils.OK return nil // Mission complete, no errors @@ -440,106 +278,6 @@ func (apierSv1 *APIerSv1) ImportTariffPlanFromFolder(attrs *utils.AttrImportTPFr return nil } -// SetRatingProfile sets a specific rating profile working with data directly in the DataDB without involving storDb -func (apierSv1 *APIerSv1) SetRatingProfile(attrs *utils.AttrSetRatingProfile, reply *string) (err error) { - if missing := utils.MissingStructFields(attrs, []string{"ToR", "Subject", "RatingPlanActivations"}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - for _, rpa := range attrs.RatingPlanActivations { - if missing := utils.MissingStructFields(rpa, []string{"ActivationTimes", "RatingPlanId"}); len(missing) != 0 { - return fmt.Errorf("%s:RatingPlanActivation:%v", utils.ErrMandatoryIeMissing.Error(), missing) - } - } - tnt := attrs.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - keyID := utils.ConcatenatedKey(utils.MetaOut, - tnt, attrs.Category, attrs.Subject) - var rpfl *engine.RatingProfile - if !attrs.Overwrite { - if rpfl, err = apierSv1.DataManager.GetRatingProfile(keyID, false, utils.NonTransactional); err != nil && err != utils.ErrNotFound { - return utils.NewErrServerError(err) - } - } - if rpfl == nil { - rpfl = &engine.RatingProfile{Id: keyID, RatingPlanActivations: make(engine.RatingPlanActivations, 0)} - } - for _, ra := range attrs.RatingPlanActivations { - at, err := utils.ParseTimeDetectLayout(ra.ActivationTime, - apierSv1.Config.GeneralCfg().DefaultTimezone) - if err != nil { - return fmt.Errorf(fmt.Sprintf("%s:Cannot parse activation time from %v", utils.ErrServerError.Error(), ra.ActivationTime)) - } - if exists, err := apierSv1.DataManager.HasData(utils.RatingPlanPrefix, - ra.RatingPlanId, ""); err != nil { - return utils.NewErrServerError(err) - } else if !exists { - return fmt.Errorf(fmt.Sprintf("%s:RatingPlanId:%s", utils.ErrNotFound.Error(), ra.RatingPlanId)) - } - rpfl.RatingPlanActivations = append(rpfl.RatingPlanActivations, - &engine.RatingPlanActivation{ - ActivationTime: at, - RatingPlanId: ra.RatingPlanId, - FallbackKeys: utils.FallbackSubjKeys(tnt, - attrs.Category, ra.FallbackSubjects)}) - } - if err := apierSv1.DataManager.SetRatingProfile(rpfl, utils.NonTransactional); err != nil { - return utils.NewErrServerError(err) - } - //CacheReload - if err := apierSv1.ConnMgr.Call(apierSv1.Config.ApierCfg().CachesConns, nil, - utils.CacheSv1ReloadCache, utils.AttrReloadCacheWithAPIOpts{ - ArgsCache: map[string][]string{utils.RatingProfileIDs: {rpfl.Id}}, - }, reply); err != nil { - return err - } - //generate a loadID for CacheRatingProfiles and store it in database - if err := apierSv1.DataManager.SetLoadIDs(map[string]int64{utils.CacheRatingProfiles: time.Now().UnixNano()}); err != nil { - return utils.APIErrorHandler(err) - } - *reply = utils.OK - return nil -} - -// GetRatingProfileIDs returns list of resourceProfile IDs registered for a tenant -func (apierSv1 *APIerSv1) GetRatingProfileIDs(args *utils.PaginatorWithTenant, rsPrfIDs *[]string) error { - tnt := args.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - prfx := utils.RatingProfilePrefix + "*out:" + tnt + utils.ConcatenatedKeySep - keys, err := apierSv1.DataManager.DataDB().GetKeysForPrefix(prfx) - if err != nil { - return err - } - if len(keys) == 0 { - return utils.ErrNotFound - } - retIDs := make([]string, len(keys)) - for i, key := range keys { - retIDs[i] = key[len(prfx):] - } - *rsPrfIDs = args.PaginateStringSlice(retIDs) - return nil -} - -func (apierSv1 *APIerSv1) GetRatingProfile(attrs *utils.AttrGetRatingProfile, reply *engine.RatingProfile) (err error) { - if missing := utils.MissingStructFields(attrs, []string{utils.Category, utils.Subject}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if attrs.Tenant == utils.EmptyString { - attrs.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - if rpPrf, err := apierSv1.DataManager.GetRatingProfile(attrs.GetID(), - false, utils.NonTransactional); err != nil { - return utils.APIErrorHandler(err) - } else { - *reply = *rpPrf - } - return -} - // Deprecated attrs type V1AttrSetActions struct { ActionsId string // Actions id @@ -572,58 +310,6 @@ type V1TPAction struct { Weight float64 // Action's weight } -type AttrSetActionPlan struct { - Id string // Profile id - ActionPlan []*AttrActionPlan // Set of actions this Actions profile will perform - Overwrite bool // If previously defined, will be overwritten -} - -type AttrActionPlan struct { - ActionsId string // Actions id - TimingID string // timingID is used to specify the ID of the timing for a corner case ( e.g. *monthly_estimated ) - Years string // semicolon separated list of years this timing is valid on, *any or empty supported - Months string // semicolon separated list of months this timing is valid on, *any or empty supported - MonthDays string // semicolon separated list of month's days this timing is valid on, *any or empty supported - WeekDays string // semicolon separated list of week day names this timing is valid on *any or empty supported - Time string // String representing the time this timing starts on, *asap supported - Weight float64 // Binding's weight -} - -func (attr *AttrActionPlan) getRITiming(dm *engine.DataManager) (timing *engine.RITiming, err error) { - if dfltTiming, isDefault := checkDefaultTiming(attr.Time); isDefault { - return dfltTiming, nil - } - timing = new(engine.RITiming) - - if attr.TimingID != utils.EmptyString && - !strings.HasPrefix(attr.TimingID, utils.Meta) { // in case of dynamic timing - if dbTiming, err := dm.GetTiming(attr.TimingID, false, utils.NonTransactional); err != nil { - if err != utils.ErrNotFound { // if not found let the user to populate all the timings values - return nil, err - } - } else { - timing.ID = dbTiming.ID - timing.Years = dbTiming.Years - timing.Months = dbTiming.Months - timing.MonthDays = dbTiming.MonthDays - timing.WeekDays = dbTiming.WeekDays - timing.StartTime = dbTiming.StartTime - timing.EndTime = dbTiming.EndTime - } - } - timing.ID = attr.TimingID - timing.Years.Parse(attr.Years, ";") - timing.Months.Parse(attr.Months, ";") - timing.MonthDays.Parse(attr.MonthDays, ";") - timing.WeekDays.Parse(attr.WeekDays, ";") - if !verifyFormat(attr.Time) { - err = fmt.Errorf("%s:%s", utils.ErrUnsupportedFormat.Error(), attr.Time) - return - } - timing.StartTime = attr.Time - return -} - func verifyFormat(tStr string) bool { if tStr == utils.EmptyString || tStr == utils.MetaASAP { @@ -647,157 +333,6 @@ func verifyFormat(tStr string) bool { return true } -// checkDefaultTiming will check the tStr if it's of the the default timings ( the same as in TPReader ) -// and will compute it properly -func checkDefaultTiming(tStr string) (rTm *engine.RITiming, isDefault bool) { - startTime := time.Now().Format("15:04:05") - switch tStr { - case utils.MetaEveryMinute: - return &engine.RITiming{ - ID: utils.MetaEveryMinute, - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{}, - StartTime: utils.ConcatenatedKey(utils.Meta, utils.Meta, strconv.Itoa(time.Now().Second())), - EndTime: "", - }, true - case utils.MetaHourly: - return &engine.RITiming{ - ID: utils.MetaHourly, - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{}, - StartTime: utils.ConcatenatedKey(utils.Meta, strconv.Itoa(time.Now().Minute()), strconv.Itoa(time.Now().Second())), - EndTime: "", - }, true - case utils.MetaDaily: - return &engine.RITiming{ - ID: utils.MetaDaily, - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{}, - StartTime: startTime, - EndTime: ""}, true - case utils.MetaWeekly: - return &engine.RITiming{ - ID: utils.MetaWeekly, - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{time.Now().Weekday()}, - StartTime: startTime, - EndTime: "", - }, true - case utils.MetaMonthly: - return &engine.RITiming{ - ID: utils.MetaMonthly, - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{time.Now().Day()}, - WeekDays: utils.WeekDays{}, - StartTime: startTime, - EndTime: "", - }, true - case utils.MetaMonthlyEstimated: - return &engine.RITiming{ - ID: utils.MetaMonthlyEstimated, - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{time.Now().Day()}, - WeekDays: utils.WeekDays{}, - StartTime: startTime, - EndTime: "", - }, true - case utils.MetaMonthEnd: - return &engine.RITiming{ - ID: utils.MetaMonthEnd, - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{-1}, - WeekDays: utils.WeekDays{}, - StartTime: startTime, - EndTime: "", - }, true - case utils.MetaYearly: - return &engine.RITiming{ - ID: utils.MetaYearly, - Years: utils.Years{}, - Months: utils.Months{time.Now().Month()}, - MonthDays: utils.MonthDays{time.Now().Day()}, - WeekDays: utils.WeekDays{}, - StartTime: startTime, - EndTime: "", - }, true - default: - return nil, false - } -} - -type AttrGetActionPlan struct { - ID string -} - -func (apierSv1 *APIerSv1) GetActionPlan(attr *AttrGetActionPlan, reply *[]*engine.ActionPlan) error { - var result []*engine.ActionPlan - if attr.ID == "" || attr.ID == "*" { - result = make([]*engine.ActionPlan, 0) - aplsMap, err := apierSv1.DataManager.GetAllActionPlans() - if err != nil { - return err - } - for _, apls := range aplsMap { - result = append(result, apls) - } - } else { - apls, err := apierSv1.DataManager.GetActionPlan(attr.ID, false, utils.NonTransactional) - if err != nil { - return err - } - result = append(result, apls) - } - *reply = result - return nil -} - -func (apierSv1 *APIerSv1) RemoveActionPlan(attr *AttrGetActionPlan, reply *string) (err error) { - if missing := utils.MissingStructFields(attr, []string{"ID"}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if _, err = guardian.Guardian.Guard(func() (interface{}, error) { - var prevAccountIDs utils.StringMap - if prevAP, err := apierSv1.DataManager.GetActionPlan(attr.ID, false, utils.NonTransactional); err != nil && err != utils.ErrNotFound { - return 0, err - } else if prevAP != nil { - prevAccountIDs = prevAP.AccountIDs - } - if err := apierSv1.DataManager.RemoveActionPlan(attr.ID, utils.NonTransactional); err != nil { - return 0, err - } - for acntID := range prevAccountIDs { - if err := apierSv1.DataManager.RemAccountActionPlans(acntID, []string{attr.ID}); err != nil { - return 0, utils.NewErrServerError(err) - } - } - if len(prevAccountIDs) != 0 { - sl := prevAccountIDs.Slice() - if err := apierSv1.ConnMgr.Call(apierSv1.Config.ApierCfg().CachesConns, nil, - utils.CacheSv1ReloadCache, utils.AttrReloadCacheWithAPIOpts{ - ArgsCache: map[string][]string{utils.AccountActionPlanIDs: sl}, - }, reply); err != nil { - return 0, err - } - } - return 0, nil - }, config.CgrConfig().GeneralCfg().LockingTimeout, utils.ActionPlanPrefix); err != nil { - return err - } - *reply = utils.OK - return nil -} - func (apierSv1 *APIerSv1) LoadTariffPlanFromFolder(attrs *utils.AttrLoadTpFromFolder, reply *string) error { // verify if FolderPath is present if len(attrs.FolderPath) == 0 { @@ -831,12 +366,6 @@ func (apierSv1 *APIerSv1) LoadTariffPlanFromFolder(attrs *utils.AttrLoadTpFromFo return nil // Mission complete, no errors } - if attrs.Validate { - if !loader.IsValid() { - return errors.New("invalid data") - } - } - // write data intro Database if err := loader.WriteToDatabase(false, false); err != nil { return utils.NewErrServerError(err) @@ -897,12 +426,6 @@ func (apierSv1 *APIerSv1) RemoveTPFromFolder(attrs *utils.AttrLoadTpFromFolder, return nil // Mission complete, no errors } - if attrs.Validate { - if !loader.IsValid() { - return errors.New("invalid data") - } - } - // remove data from Database if err := loader.RemoveFromDatabase(false, false); err != nil { return utils.NewErrServerError(err) @@ -945,12 +468,6 @@ func (apierSv1 *APIerSv1) RemoveTPFromStorDB(attrs *AttrLoadTpFromStorDb, reply if err := dbReader.LoadAll(); err != nil { return utils.NewErrServerError(err) } - if attrs.Validate { - if !dbReader.IsValid() { - *reply = utils.OK - return errors.New("invalid data") - } - } if attrs.DryRun { *reply = utils.OK return nil // Mission complete, no errors @@ -1006,35 +523,6 @@ func (arrp *AttrRemoveRatingProfile) GetId() (result string) { return } -func (apierSv1 *APIerSv1) RemoveRatingProfile(attr *AttrRemoveRatingProfile, reply *string) error { - if attr.Tenant == utils.EmptyString { - attr.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - if (attr.Subject != "" && utils.IsSliceMember([]string{attr.Tenant, attr.Category}, "")) || - (attr.Category != "" && attr.Tenant == "") { - return utils.ErrMandatoryIeMissing - } - _, err := guardian.Guardian.Guard(func() (interface{}, error) { - return 0, apierSv1.DataManager.RemoveRatingProfile(attr.GetId(), utils.NonTransactional) - }, config.CgrConfig().GeneralCfg().LockingTimeout, "RemoveRatingProfile") - if err != nil { - *reply = err.Error() - return utils.NewErrServerError(err) - } - if err := apierSv1.ConnMgr.Call(apierSv1.Config.ApierCfg().CachesConns, nil, - utils.CacheSv1ReloadCache, utils.AttrReloadCacheWithAPIOpts{ - ArgsCache: map[string][]string{utils.RatingProfileIDs: {attr.GetId()}}, - }, reply); err != nil { - return err - } - //generate a loadID for CacheActionPlans and store it in database - if err := apierSv1.DataManager.SetLoadIDs(map[string]int64{utils.CacheRatingProfiles: time.Now().UnixNano()}); err != nil { - return utils.APIErrorHandler(err) - } - *reply = utils.OK - return nil -} - func (apierSv1 *APIerSv1) GetLoadHistory(attrs *utils.Paginator, reply *[]*utils.LoadInstance) error { nrItems := -1 offset := 0 @@ -1234,42 +722,6 @@ func (apierSv1 *APIerSv1) ComputeActionPlanIndexes(_ string, reply *string) (err return nil } -// GetActionPlanIDs returns list of ActionPlan IDs registered for a tenant -func (apierSv1 *APIerSv1) GetActionPlanIDs(args *utils.PaginatorWithTenant, attrPrfIDs *[]string) error { - prfx := utils.ActionPlanPrefix - keys, err := apierSv1.DataManager.DataDB().GetKeysForPrefix(utils.ActionPlanPrefix) - if err != nil { - return err - } - if len(keys) == 0 { - return utils.ErrNotFound - } - retIDs := make([]string, len(keys)) - for i, key := range keys { - retIDs[i] = key[len(prfx):] - } - *attrPrfIDs = args.PaginateStringSlice(retIDs) - return nil -} - -// GetRatingPlanIDs returns list of RatingPlan IDs registered for a tenant -func (apierSv1 *APIerSv1) GetRatingPlanIDs(args *utils.PaginatorWithTenant, attrPrfIDs *[]string) error { - prfx := utils.RatingPlanPrefix - keys, err := apierSv1.DataManager.DataDB().GetKeysForPrefix(utils.RatingPlanPrefix) - if err != nil { - return err - } - if len(keys) == 0 { - return utils.ErrNotFound - } - retIDs := make([]string, len(keys)) - for i, key := range keys { - retIDs[i] = key[len(prfx):] - } - *attrPrfIDs = args.PaginateStringSlice(retIDs) - return nil -} - // ListenAndServe listen for storbd reload func (apierSv1 *APIerSv1) ListenAndServe(stopChan chan struct{}) { utils.Logger.Info(fmt.Sprintf("<%s> starting <%s> subsystem", utils.CoreS, utils.ApierS)) @@ -1283,8 +735,6 @@ func (apierSv1 *APIerSv1) ListenAndServe(stopChan chan struct{}) { } apierSv1.CdrDb = stordb apierSv1.StorDb = stordb - case resp := <-apierSv1.ResponderChan: - apierSv1.Responder = resp } } } diff --git a/apier/v1/apier_it_test.go b/apier/v1/apier_it_test.go index 3867dee71..37984fb31 100644 --- a/apier/v1/apier_it_test.go +++ b/apier/v1/apier_it_test.go @@ -73,50 +73,17 @@ var ( testApierRpcConn, testApierTPTiming, testApierTPDestination, - testApierTPRate, - testApierTPDestinationRate, - testApierTPRatingPlan, - testApierTPRatingProfile, testApierTPActions, - testApierTPActionPlan, - testApierTPActionTriggers, - testApierTPAccountActions, - testApierLoadRatingPlan, - testApierLoadRatingProfile, - testApierLoadRatingProfileWithoutTenant, - testApierLoadAccountActions, - testApierReloadScheduler, - testApierSetRatingProfile, + testApierSetRatingProfileWithoutTenant, testApierRemoveRatingProfilesWithoutTenant, - testAPIerSv1GetRatingProfile, - testAPIerSv1GetRatingProfileWithoutTenant, - testAPIerSv1GetRatingProfileIDsWithoutTenant, testApierReloadCache, - testApierGetActionTrigger, testApierGetDestination, - testApierGetRatingPlan, - testApierRemoveRatingPlan, - testApierAddBalance, testApierExecuteAction, testApierExecuteActionWithoutTenant, testApierSetActions, testApierGetActions, testApierSetActionPlan, - testApierAddTriggeredAction, - testApierGetAccountActionTriggers, - testApierAddTriggeredAction2, - testApierGetAccountActionTriggers2, - testApierSetAccountActionTriggers, - testApierRemAccountActionTriggers, - testApierSetAccount, - testApierGetAccountActionPlan, - testApierGetAccountActionPlanWithoutTenant, - testApierITGetScheduledActionsForAccount, - testApierRemUniqueIDActionTiming, - testApierRemUniqueIDActionTimingWithoutTenant, - testApierGetAccount, - testApierTriggersExecute, testApierResetDataBeforeLoadFromFolder, testApierLoadTariffPlanFromFolder, testApierComputeReverse, @@ -340,222 +307,6 @@ func testApierTPDestination(t *testing.T) { } } -// Test here TPRateRALs APIs -func testApierTPRate(t *testing.T) { - var reply string - rt := &utils.TPRateRALs{TPid: utils.TestSQL, ID: "RT_FS_USERS", RateSlots: []*utils.RateSlot{ - {ConnectFee: 0, Rate: 0, RateUnit: "60s", RateIncrement: "60s", GroupIntervalStart: "0s"}, - }} - rt2 := new(utils.TPRateRALs) - *rt2 = *rt - rt2.ID = "RT_FS_USERS2" - for _, r := range []*utils.TPRateRALs{rt, rt2} { - if err := rater.Call(utils.APIerSv1SetTPRate, r, &reply); err != nil { - t.Error("Got error on APIerSv1.SetTPRate: ", err.Error()) - } else if reply != utils.OK { - t.Error("Unexpected reply received when calling APIerSv1.SetTPRate: ", reply) - } - } - // Check second set - if err := rater.Call(utils.APIerSv1SetTPRate, rt2, &reply); err != nil { - t.Error("Got error on second APIerSv1.SetTPRate: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.SetTPRate got reply: ", reply) - } - // Check missing params - if err := rater.Call(utils.APIerSv1SetTPRate, new(utils.TPRateRALs), &reply); err == nil { - t.Error("Calling APIerSv1.SetTPDestination, expected error, received: ", reply) - } else if err.Error() != "MANDATORY_IE_MISSING: [TPid ID RateSlots]" { - t.Error("Calling APIerSv1.SetTPRate got unexpected error: ", err.Error()) - } - // Test get - var rplyRt2 *utils.TPRateRALs - if err := rater.Call(utils.APIerSv1GetTPRate, &AttrGetTPRate{rt2.TPid, rt2.ID}, &rplyRt2); err != nil { - t.Error("Calling APIerSv1.GetTPRate, got error: ", err.Error()) - } else if !reflect.DeepEqual(rt2, rplyRt2) { - t.Errorf("Calling APIerSv1.GetTPRate expected: %+v, received: %+v", rt2, rplyRt2) - } - // Test remove - if err := rater.Call(utils.APIerSv1RemoveTPRate, &AttrGetTPRate{rt2.TPid, rt2.ID}, &reply); err != nil { - t.Error("Calling APIerSv1.RemoveTPRate, got error: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.RemoveTPRate received: ", reply) - } - // Test getIds - var rplyRtIds []string - expectedRtIds := []string{"RT_FS_USERS"} - if err := rater.Call(utils.APIerSv1GetTPRateIds, &AttrGetTPRateIds{rt.TPid, utils.PaginatorWithSearch{}}, &rplyRtIds); err != nil { - t.Error("Calling APIerSv1.GetTPRateIds, got error: ", err.Error()) - } else if !reflect.DeepEqual(expectedRtIds, rplyRtIds) { - t.Errorf("Calling APIerSv1.GetTPDestinationIDs expected: %v, received: %v", expectedRtIds, rplyRtIds) - } -} - -// Test here TPDestinationRate APIs -func testApierTPDestinationRate(t *testing.T) { - var reply string - dr := &utils.TPDestinationRate{TPid: utils.TestSQL, ID: "DR_FREESWITCH_USERS", DestinationRates: []*utils.DestinationRate{ - {DestinationId: "FS_USERS", RateId: "RT_FS_USERS", RoundingMethod: "*up", RoundingDecimals: 2}, - }} - drDe := &utils.TPDestinationRate{TPid: utils.TestSQL, ID: "DR_FREESWITCH_USERS", DestinationRates: []*utils.DestinationRate{ - {DestinationId: "GERMANY_MOBILE", RateId: "RT_FS_USERS", RoundingMethod: "*up", RoundingDecimals: 2}, - }} - dr2 := new(utils.TPDestinationRate) - *dr2 = *dr - dr2.ID = utils.TestSQL - for _, d := range []*utils.TPDestinationRate{dr, dr2, drDe} { - if err := rater.Call(utils.APIerSv1SetTPDestinationRate, d, &reply); err != nil { - t.Error("Got error on APIerSv1.SetTPDestinationRate: ", err.Error()) - } else if reply != utils.OK { - t.Error("Unexpected reply received when calling APIerSv1.SetTPDestinationRate: ", reply) - } - } - // Check second set - if err := rater.Call(utils.APIerSv1SetTPDestinationRate, dr2, &reply); err != nil { - t.Error("Got error on second APIerSv1.SetTPDestinationRate: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.SetTPDestinationRate got reply: ", reply) - } - // Check missing params - if err := rater.Call(utils.APIerSv1SetTPDestinationRate, new(utils.TPDestinationRate), &reply); err == nil { - t.Error("Calling APIerSv1.SetTPDestination, expected error, received: ", reply) - } else if err.Error() != "MANDATORY_IE_MISSING: [TPid ID DestinationRates]" { - t.Error("Calling APIerSv1.SetTPDestinationRate got unexpected error: ", err.Error()) - } - // Test get - var rplyDr2 *utils.TPDestinationRate - if err := rater.Call(utils.APIerSv1GetTPDestinationRate, &AttrGetTPDestinationRate{dr2.TPid, dr2.ID, utils.Paginator{}}, &rplyDr2); err != nil { - t.Error("Calling APIerSv1.GetTPDestinationRate, got error: ", err.Error()) - } else if !reflect.DeepEqual(dr2, rplyDr2) { - t.Errorf("Calling APIerSv1.GetTPDestinationRate expected: %v, received: %v", dr2, rplyDr2) - } - // Test remove - if err := rater.Call(utils.APIerSv1RemoveTPDestinationRate, &AttrGetTPDestinationRate{dr2.TPid, dr2.ID, utils.Paginator{}}, &reply); err != nil { - t.Error("Calling APIerSv1.RemoveTPRate, got error: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.RemoveTPRate received: ", reply) - } - // Test getIds - var rplyDrIds []string - expectedDrIds := []string{"DR_FREESWITCH_USERS"} - if err := rater.Call(utils.APIerSv1GetTPDestinationRateIds, &AttrTPDestinationRateIds{dr.TPid, utils.PaginatorWithSearch{}}, &rplyDrIds); err != nil { - t.Error("Calling APIerSv1.GetTPDestinationRateIds, got error: ", err.Error()) - } else if !reflect.DeepEqual(expectedDrIds, rplyDrIds) { - t.Errorf("Calling APIerSv1.GetTPDestinationRateIds expected: %v, received: %v", expectedDrIds, rplyDrIds) - } -} - -// Test here TPRatingPlan APIs -func testApierTPRatingPlan(t *testing.T) { - var reply string - rp := &utils.TPRatingPlan{TPid: utils.TestSQL, ID: "RETAIL1", RatingPlanBindings: []*utils.TPRatingPlanBinding{ - {DestinationRatesId: "DR_FREESWITCH_USERS", TimingId: "ALWAYS", Weight: 10}, - }} - rpTst := new(utils.TPRatingPlan) - *rpTst = *rp - rpTst.ID = utils.TestSQL - for _, rpl := range []*utils.TPRatingPlan{rp, rpTst} { - if err := rater.Call(utils.APIerSv1SetTPRatingPlan, rpl, &reply); err != nil { - t.Error("Got error on APIerSv1.SetTPRatingPlan: ", err.Error()) - } else if reply != utils.OK { - t.Error("Unexpected reply received when calling APIerSv1.SetTPRatingPlan: ", reply) - } - } - // Check second set - if err := rater.Call(utils.APIerSv1SetTPRatingPlan, rpTst, &reply); err != nil { - t.Error("Got error on second APIerSv1.SetTPRatingPlan: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.SetTPRatingPlan got reply: ", reply) - } - // Check missing params - if err := rater.Call(utils.APIerSv1SetTPRatingPlan, new(utils.TPRatingPlan), &reply); err == nil { - t.Error("Calling APIerSv1.SetTPRatingPlan, expected error, received: ", reply) - } else if err.Error() != "MANDATORY_IE_MISSING: [TPid ID RatingPlanBindings]" { - t.Error("Calling APIerSv1.SetTPRatingPlan got unexpected error: ", err.Error()) - } - // Test get - var rplyRpTst *utils.TPRatingPlan - if err := rater.Call(utils.APIerSv1GetTPRatingPlan, &AttrGetTPRatingPlan{TPid: rpTst.TPid, ID: rpTst.ID}, &rplyRpTst); err != nil { - t.Error("Calling APIerSv1.GetTPRatingPlan, got error: ", err.Error()) - } else if !reflect.DeepEqual(rpTst, rplyRpTst) { - t.Errorf("Calling APIerSv1.GetTPRatingPlan expected: %v, received: %v", rpTst, rplyRpTst) - } - // Test remove - if err := rater.Call(utils.APIerSv1RemoveTPRatingPlan, &AttrGetTPRatingPlan{TPid: rpTst.TPid, ID: rpTst.ID}, &reply); err != nil { - t.Error("Calling APIerSv1.RemoveTPRatingPlan, got error: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.RemoveTPRatingPlan received: ", reply) - } - // Test getIds - var rplyRpIds []string - expectedRpIds := []string{"RETAIL1"} - if err := rater.Call(utils.APIerSv1GetTPRatingPlanIds, &AttrGetTPRatingPlanIds{rp.TPid, utils.PaginatorWithSearch{}}, &rplyRpIds); err != nil { - t.Error("Calling APIerSv1.GetTPRatingPlanIds, got error: ", err.Error()) - } else if !reflect.DeepEqual(expectedRpIds, rplyRpIds) { - t.Errorf("Calling APIerSv1.GetTPRatingPlanIds expected: %v, received: %v", expectedRpIds, rplyRpIds) - } -} - -// Test here TPRatingPlan APIs -func testApierTPRatingProfile(t *testing.T) { - var reply string - rpf := &utils.TPRatingProfile{ - TPid: utils.TestSQL, - LoadId: utils.TestSQL, - Tenant: "cgrates.org", - Category: "call", - Subject: utils.MetaAny, - RatingPlanActivations: []*utils.TPRatingActivation{{ - ActivationTime: "2012-01-01T00:00:00Z", - RatingPlanId: "RETAIL1", - FallbackSubjects: utils.EmptyString, - }}, - } - rpfTst := new(utils.TPRatingProfile) - *rpfTst = *rpf - rpfTst.Subject = utils.TestSQL - for _, rp := range []*utils.TPRatingProfile{rpf, rpfTst} { - if err := rater.Call(utils.APIerSv1SetTPRatingProfile, rp, &reply); err != nil { - t.Error("Got error on APIerSv1.SetTPRatingProfile: ", err.Error()) - } else if reply != utils.OK { - t.Error("Unexpected reply received when calling APIerSv1.SetTPRatingProfile: ", reply) - } - } - // Check second set - if err := rater.Call(utils.APIerSv1SetTPRatingProfile, rpfTst, &reply); err != nil { - t.Error("Got error on second APIerSv1.SetTPRatingProfile: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.SetTPRatingProfile got reply: ", reply) - } - // Check missing params - if err := rater.Call(utils.APIerSv1SetTPRatingProfile, new(utils.TPRatingProfile), &reply); err == nil { - t.Error("Calling APIerSv1.SetTPRatingProfile, expected error, received: ", reply) - } else if err.Error() != "MANDATORY_IE_MISSING: [TPid LoadId Category Subject RatingPlanActivations]" { - t.Error("Calling APIerSv1.SetTPRatingProfile got unexpected error: ", err.Error()) - } - // Test get - var rplyRpf *utils.TPRatingProfile - if err := rater.Call(utils.APIerSv1GetTPRatingProfile, &AttrGetTPRatingProfile{TPid: rpfTst.TPid, RatingProfileID: utils.ConcatenatedKey(rpfTst.LoadId, rpfTst.Tenant, rpfTst.Category, rpfTst.Subject)}, &rplyRpf); err != nil { - t.Error("Calling APIerSv1.GetTPRatingProfiles, got error: ", err.Error()) - } else if !reflect.DeepEqual(rpfTst, rplyRpf) { - t.Errorf("Calling APIerSv1.GetTPRatingProfiles expected: %v, received: %v", rpfTst, rplyRpf) - } - // Test remove - if err := rater.Call(utils.APIerSv1RemoveTPRatingProfile, &AttrGetTPRatingProfile{TPid: rpfTst.TPid, RatingProfileID: utils.ConcatenatedKey(rpfTst.LoadId, rpfTst.Tenant, rpfTst.Category, rpfTst.Subject)}, &reply); err != nil { - t.Error("Calling APIerSv1.RemoveTPRatingProfile, got error: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.RemoveTPRatingProfile received: ", reply) - } - // Test getLoadIds - var rplyRpIds []string - expectedRpIds := []string{utils.TestSQL} - if err := rater.Call(utils.APIerSv1GetTPRatingProfileLoadIds, &utils.AttrTPRatingProfileIds{TPid: rpf.TPid}, &rplyRpIds); err != nil { - t.Error("Calling APIerSv1.GetTPRatingProfileLoadIds, got error: ", err.Error()) - } else if !reflect.DeepEqual(expectedRpIds, rplyRpIds) { - t.Errorf("Calling APIerSv1.GetTPRatingProfileLoadIds expected: %v, received: %v", expectedRpIds, rplyRpIds) - } -} - func testApierTPActions(t *testing.T) { var reply string act := &utils.TPActions{TPid: utils.TestSQL, @@ -618,450 +369,6 @@ func testApierTPActions(t *testing.T) { } } -func testApierTPActionPlan(t *testing.T) { - var reply string - at := &utils.TPActionPlan{TPid: utils.TestSQL, ID: "PREPAID_10", ActionPlan: []*utils.TPActionTiming{ - {ActionsId: "PREPAID_10", TimingId: "ASAP", Weight: 10}, - }} - atTst := new(utils.TPActionPlan) - *atTst = *at - atTst.ID = utils.TestSQL - for _, act := range []*utils.TPActionPlan{at, atTst} { - if err := rater.Call(utils.APIerSv1SetTPActionPlan, act, &reply); err != nil { - t.Error("Got error on APIerSv1.SetTPActionPlan: ", err.Error()) - } else if reply != utils.OK { - t.Error("Unexpected reply received when calling APIerSv1.SetTPActionPlan: ", reply) - } - } - // Check second set - if err := rater.Call(utils.APIerSv1SetTPActionPlan, atTst, &reply); err != nil { - t.Error("Got error on second APIerSv1.SetTPActionPlan: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.SetTPActionPlan got reply: ", reply) - } - // Check missing params - if err := rater.Call(utils.APIerSv1SetTPActionPlan, new(utils.TPActionPlan), &reply); err == nil { - t.Error("Calling APIerSv1.SetTPActionPlan, expected error, received: ", reply) - } else if err.Error() != "MANDATORY_IE_MISSING: [TPid ID ActionPlan]" { - t.Error("Calling APIerSv1.SetTPActionPlan got unexpected error: ", err.Error()) - } - // Test get - var rplyActs *utils.TPActionPlan - if err := rater.Call(utils.APIerSv1GetTPActionPlan, &AttrGetTPActionPlan{TPid: atTst.TPid, ID: atTst.ID}, &rplyActs); err != nil { - t.Error("Calling APIerSv1.GetTPActionPlan, got error: ", err.Error()) - } else if !reflect.DeepEqual(atTst, rplyActs) { - t.Errorf("Calling APIerSv1.GetTPActionPlan expected: %v, received: %v", atTst, rplyActs) - } - // Test remove - if err := rater.Call(utils.APIerSv1RemoveTPActionPlan, &AttrGetTPActionPlan{TPid: atTst.TPid, ID: atTst.ID}, &reply); err != nil { - t.Error("Calling APIerSv1.RemoveTPActionPlan, got error: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.RemoveTPActionPlan received: ", reply) - } - // Test getIds - var rplyIds []string - expectedIds := []string{"PREPAID_10"} - if err := rater.Call(utils.APIerSv1GetTPActionPlanIds, &AttrGetTPActionPlanIds{TPid: atTst.TPid}, &rplyIds); err != nil { - t.Error("Calling APIerSv1.GetTPActionPlanIds, got error: ", err.Error()) - } else if !reflect.DeepEqual(expectedIds, rplyIds) { - t.Errorf("Calling APIerSv1.GetTPActionPlanIds expected: %v, received: %v", expectedIds, rplyIds) - } -} - -func testApierTPActionTriggers(t *testing.T) { - var reply string - at := &utils.TPActionTriggers{ - TPid: utils.TestSQL, - ID: "STANDARD_TRIGGERS", - ActionTriggers: []*utils.TPActionTrigger{{ - Id: "STANDARD_TRIGGERS", - UniqueID: "MYFIRSTTRIGGER", - BalanceType: utils.MetaMonetary, - ThresholdType: "*min_balance", - ThresholdValue: 2, - ActionsId: "LOG_BALANCE", - Weight: 10, - }}, - } - atTst := new(utils.TPActionTriggers) - *atTst = *at - atTst.ID = utils.TestSQL - atTst.ActionTriggers[0].Id = utils.TestSQL - for _, act := range []*utils.TPActionTriggers{at, atTst} { - if err := rater.Call(utils.APIerSv1SetTPActionTriggers, act, &reply); err != nil { - t.Error("Got error on APIerSv1.SetTPActionTriggers: ", err.Error()) - } else if reply != utils.OK { - t.Error("Unexpected reply received when calling APIerSv1.SetTPActionTriggers: ", reply) - } - } - // Check second set - if err := rater.Call(utils.APIerSv1SetTPActionTriggers, atTst, &reply); err != nil { - t.Error("Got error on second APIerSv1.SetTPActionTriggers: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.SetTPActionTriggers got reply: ", reply) - } - // Check missing params - if err := rater.Call(utils.APIerSv1SetTPActionTriggers, new(utils.TPActionTriggers), &reply); err == nil { - t.Error("Calling APIerSv1.SetTPActionTriggers, expected error, received: ", reply) - } else if err.Error() != "MANDATORY_IE_MISSING: [TPid ID]" { - t.Error("Calling APIerSv1.SetTPActionTriggers got unexpected error: ", err.Error()) - } - // Test get - var rplyActs *utils.TPActionTriggers - if err := rater.Call(utils.APIerSv1GetTPActionTriggers, &AttrGetTPActionTriggers{TPid: atTst.TPid, ID: atTst.ID}, &rplyActs); err != nil { - t.Errorf("Calling APIerSv1.GetTPActionTriggers %s, got error: %s", atTst.ID, err.Error()) - } else if !reflect.DeepEqual(atTst, rplyActs) { - t.Errorf("Calling APIerSv1.GetTPActionTriggers expected: %+v, received: %+v", utils.ToJSON(atTst), utils.ToJSON(rplyActs)) - } - // Test remove - if err := rater.Call(utils.APIerSv1RemoveTPActionTriggers, &AttrGetTPActionTriggers{TPid: atTst.TPid, ID: atTst.ID}, &reply); err != nil { - t.Error("Calling APIerSv1.RemoveTPActionTriggers, got error: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.RemoveTPActionTriggers received: ", reply) - } - // Test getIds - var rplyIds []string - expectedIds := []string{"STANDARD_TRIGGERS"} - if err := rater.Call(utils.APIerSv1GetTPActionTriggerIds, &AttrGetTPActionTriggerIds{TPid: atTst.TPid}, &rplyIds); err != nil { - t.Error("Calling APIerSv1.GetTPActionTriggerIds, got error: ", err.Error()) - } else if !reflect.DeepEqual(expectedIds, rplyIds) { - t.Errorf("Calling APIerSv1.GetTPActionTriggerIds expected: %v, received: %v", expectedIds, rplyIds) - } -} - -// Test here TPAccountActions APIs -func testApierTPAccountActions(t *testing.T) { - var reply string - aa1 := &utils.TPAccountActions{TPid: utils.TestSQL, LoadId: utils.TestSQL, Tenant: "cgrates.org", - Account: "1001", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} - aa2 := &utils.TPAccountActions{TPid: utils.TestSQL, LoadId: utils.TestSQL, Tenant: "cgrates.org", - Account: "1002", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} - aa3 := &utils.TPAccountActions{TPid: utils.TestSQL, LoadId: utils.TestSQL, Tenant: "cgrates.org", - Account: "1003", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} - aa4 := &utils.TPAccountActions{TPid: utils.TestSQL, LoadId: utils.TestSQL, Tenant: "cgrates.org", - Account: "1004", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} - aa5 := &utils.TPAccountActions{TPid: utils.TestSQL, LoadId: utils.TestSQL, Tenant: "cgrates.org", - Account: "1005", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} - aaTst := new(utils.TPAccountActions) - *aaTst = *aa1 - aaTst.Account = utils.TestSQL - for _, aact := range []*utils.TPAccountActions{aa1, aa2, aa3, aa4, aa5, aaTst} { - if err := rater.Call(utils.APIerSv1SetTPAccountActions, aact, &reply); err != nil { - t.Error("Got error on APIerSv1.SetTPAccountActions: ", err.Error()) - } else if reply != utils.OK { - t.Error("Unexpected reply received when calling APIerSv1.SetTPAccountActions: ", reply) - } - } - // Check second set - if err := rater.Call(utils.APIerSv1SetTPAccountActions, aaTst, &reply); err != nil { - t.Error("Got error on second APIerSv1.SetTPAccountActions: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.SetTPAccountActions got reply: ", reply) - } - // Check missing params - if err := rater.Call(utils.APIerSv1SetTPAccountActions, new(utils.TPAccountActions), &reply); err == nil { - t.Error("Calling APIerSv1.SetTPAccountActions, expected error, received: ", reply) - } else if err.Error() != "MANDATORY_IE_MISSING: [TPid LoadId Account ActionPlanId]" { - t.Error("Calling APIerSv1.SetTPAccountActions got unexpected error: ", err.Error()) - } - // Test get - var rplyaa *utils.TPAccountActions - if err := rater.Call(utils.APIerSv1GetTPAccountActions, &AttrGetTPAccountActions{TPid: aaTst.TPid, AccountActionsId: aaTst.GetId()}, &rplyaa); err != nil { - t.Error("Calling APIerSv1.GetTPAccountActions, got error: ", err.Error()) - } else if !reflect.DeepEqual(aaTst, rplyaa) { - t.Errorf("Calling APIerSv1.GetTPAccountActions expected: %v, received: %v", aaTst, rplyaa) - } - // Test remove - if err := rater.Call(utils.APIerSv1RemoveTPAccountActions, &AttrGetTPAccountActions{TPid: aaTst.TPid, AccountActionsId: aaTst.GetId()}, &reply); err != nil { - t.Error("Calling APIerSv1.RemoveTPAccountActions, got error: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.RemoveTPAccountActions received: ", reply) - } - // Test getLoadIds - var rplyRpIds []string - expectedRpIds := []string{utils.TestSQL} - if err := rater.Call(utils.APIerSv1GetTPAccountActionLoadIds, &AttrGetTPAccountActionIds{TPid: aaTst.TPid}, &rplyRpIds); err != nil { - t.Error("Calling APIerSv1.GetTPAccountActionLoadIds, got error: ", err.Error()) - } else if !reflect.DeepEqual(expectedRpIds, rplyRpIds) { - t.Errorf("Calling APIerSv1.GetTPAccountActionLoadIds expected: %v, received: %v", expectedRpIds, rplyRpIds) - } -} - -// Test here LoadRatingPlan -func testApierLoadRatingPlan(t *testing.T) { - var reply string - if err := rater.Call(utils.APIerSv1LoadRatingPlan, &AttrLoadRatingPlan{TPid: utils.TestSQL, RatingPlanId: "RETAIL1"}, &reply); err != nil { - t.Error("Got error on APIerSv1.LoadRatingPlan: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.LoadRatingPlan got reply: ", reply) - } -} - -// Test here LoadRatingProfile -func testApierLoadRatingProfile(t *testing.T) { - var reply string - rpf := &utils.TPRatingProfile{ - TPid: utils.TestSQL, LoadId: utils.TestSQL, - Tenant: "cgrates.org", Category: "call", Subject: "*any"} - if err := rater.Call(utils.APIerSv1LoadRatingProfile, &rpf, &reply); err != nil { - t.Error("Got error on APIerSv1.LoadRatingProfile: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.LoadRatingProfile got reply: ", reply) - } -} - -func testApierLoadRatingProfileWithoutTenant(t *testing.T) { - var reply string - rpf := &utils.TPRatingProfile{ - TPid: utils.TestSQL, LoadId: utils.TestSQL, - Category: "call", Subject: "*any"} - if err := rater.Call(utils.APIerSv1LoadRatingProfile, &rpf, &reply); err != nil { - t.Error("Got error on APIerSv1.LoadRatingProfile: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.LoadRatingProfile got reply: ", reply) - } -} - -// Test here LoadAccountActions -func testApierLoadAccountActions(t *testing.T) { - var rcvStats map[string]*ltcache.CacheStats - expectedStats := engine.GetDefaultEmptyCacheStats() // Make sure nothing in cache so far - expectedStats[utils.CacheLoadIDs].Items = 4 // we loaded the ratingprofiles - if err := rater.Call(utils.CacheSv1GetCacheStats, new(utils.AttrCacheIDsWithAPIOpts), &rcvStats); err != nil { - t.Error("Got error on CacheSv1.GetCacheStats: ", err.Error()) - } else if !reflect.DeepEqual(expectedStats, rcvStats) { - t.Errorf("Calling CacheSv1.GetCacheStats expected: %+v,\n received: %+v", utils.ToJSON(expectedStats), utils.ToJSON(rcvStats)) - } - var reply string - aa1 := &utils.TPAccountActions{TPid: utils.TestSQL, LoadId: utils.TestSQL, Tenant: "cgrates.org", Account: "1001"} - if err := rater.Call(utils.APIerSv1LoadAccountActions, aa1, &reply); err != nil { - t.Error("Got error on APIerSv1.LoadAccountActions: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.LoadAccountActions got reply: ", reply) - } - time.Sleep(10 * time.Millisecond) - expectedStats[utils.CacheAccountActionPlans].Items = 1 - expectedStats[utils.CacheActionPlans].Items = 1 - expectedStats[utils.CacheActions].Items = 1 - expectedStats[utils.CacheLoadIDs].Items = 8 - expectedStats[utils.CacheRPCConnections].Items = 1 - if err := rater.Call(utils.CacheSv1GetCacheStats, new(utils.AttrCacheIDsWithAPIOpts), &rcvStats); err != nil { - t.Error("Got error on CacheSv1.GetCacheStats: ", err.Error()) - } else if !reflect.DeepEqual(expectedStats, rcvStats) { - t.Errorf("Calling CacheSv1.GetCacheStats expected: %+v, \n received: %+v", utils.ToJSON(expectedStats), utils.ToJSON(rcvStats)) - } -} - -// Test here ReloadScheduler -func testApierReloadScheduler(t *testing.T) { - var reply string - // Simple test that command is executed without errors - if err := rater.Call(utils.SchedulerSv1Reload, utils.StringWithAPIOpts{}, &reply); err != nil { - t.Error("Got error on SchedulerSv1.Reload: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling SchedulerSv1.Reload got reply: ", reply) - } -} - -// Test here SetRatingProfile -func testApierSetRatingProfile(t *testing.T) { - var reply string - rpa := &utils.TPRatingActivation{ActivationTime: "2012-01-01T00:00:00Z", RatingPlanId: "RETAIL1", FallbackSubjects: "dan2"} - rpf := &utils.AttrSetRatingProfile{Tenant: "cgrates.org", Category: "call", - Subject: "dan", RatingPlanActivations: []*utils.TPRatingActivation{rpa}} - if err := rater.Call(utils.APIerSv1SetRatingProfile, &rpf, &reply); err != nil { - t.Error("Got error on APIerSv1.SetRatingProfile: ", err.Error()) - } else if reply != utils.OK { - t.Error("Calling APIerSv1.SetRatingProfile got reply: ", reply) - } - var rcvStats map[string]*ltcache.CacheStats - expectedStats := engine.GetDefaultEmptyCacheStats() - expectedStats[utils.CacheAccountActionPlans].Items = 1 - expectedStats[utils.CacheActionPlans].Items = 1 - expectedStats[utils.CacheActions].Items = 1 - expectedStats[utils.CacheRatingProfiles].Items = 1 - expectedStats[utils.CacheRPCConnections].Items = 1 - expectedStats[utils.CacheLoadIDs].Items = 8 - if err := rater.Call(utils.CacheSv1GetCacheStats, new(utils.AttrCacheIDsWithAPIOpts), &rcvStats); err != nil { - t.Error("Got error on CacheSv1.GetCacheStats: ", err.Error()) - } else if !reflect.DeepEqual(expectedStats, rcvStats) { - t.Errorf("Calling CacheSv1.GetCacheStats expected: %+v, received: %+v", utils.ToJSON(expectedStats), utils.ToJSON(rcvStats)) - } - // Calling the second time should not raise EXISTS - if err := rater.Call(utils.APIerSv1SetRatingProfile, &rpf, &reply); err != nil { - t.Error("Unexpected result on duplication: ", err.Error()) - } - // Make sure rates were loaded for account dan - // Test here ResponderGetCost - tStart, _ := utils.ParseTimeDetectLayout("2013-08-07T17:30:00Z", utils.EmptyString) - tEnd, _ := utils.ParseTimeDetectLayout("2013-08-07T17:31:30Z", utils.EmptyString) - cd := &engine.CallDescriptorWithAPIOpts{ - CallDescriptor: &engine.CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "dan", - Account: "dan", - Destination: "+4917621621391", - DurationIndex: 90, - TimeStart: tStart, - TimeEnd: tEnd, - }, - } - var cc engine.CallCost - // Simple test that command is executed without errors - if err := rater.Call(utils.ResponderGetCost, cd, &cc); err != nil { - t.Error("Got error on Responder.GetCost: ", err.Error()) - } else if cc.Cost != 0 { - t.Errorf("Calling Responder.GetCost got callcost: %v", cc.Cost) - } - expectedStats[utils.CacheRatingPlans].Items = 1 - expectedStats[utils.CacheReverseDestinations].Items = 10 - if err := rater.Call(utils.CacheSv1GetCacheStats, new(utils.AttrCacheIDsWithAPIOpts), &rcvStats); err != nil { - t.Error("Got error on CacheSv1.GetCacheStats: ", err.Error()) - } else if !reflect.DeepEqual(expectedStats, rcvStats) { - t.Errorf("Calling CacheSv1.GetCacheStats expected: %+v, received: %+v", utils.ToJSON(expectedStats), utils.ToJSON(rcvStats)) - } -} - -func testAPIerSv1GetRatingProfile(t *testing.T) { - var rpl engine.RatingProfile - attrGetRatingPlan := &utils.AttrGetRatingProfile{ - Tenant: "cgrates.org", Category: "call", Subject: "dan"} - actTime, err := utils.ParseTimeDetectLayout("2012-01-01T00:00:00Z", utils.EmptyString) - if err != nil { - t.Error(err) - } - expected := engine.RatingProfile{ - Id: "*out:cgrates.org:call:dan", - RatingPlanActivations: engine.RatingPlanActivations{ - { - ActivationTime: actTime, - RatingPlanId: "RETAIL1", - FallbackKeys: []string{"*out:cgrates.org:call:dan2"}, - }, - { - ActivationTime: actTime, - RatingPlanId: "RETAIL1", - FallbackKeys: []string{"*out:cgrates.org:call:dan2"}, - }, - }, - } - if err := rater.Call(utils.APIerSv1GetRatingProfile, attrGetRatingPlan, &rpl); err != nil { - t.Errorf("Got error on APIerSv1.GetRatingProfile: %+v", err) - } else if !reflect.DeepEqual(expected, rpl) { - t.Errorf("Calling APIerSv1.GetRatingProfile expected: %+v, received: %+v", utils.ToJSON(expected), utils.ToJSON(rpl)) - } - attrGetRatingPlan.Subject = utils.EmptyString - if err := rater.Call(utils.APIerSv1GetRatingProfile, attrGetRatingPlan, &rpl); err == nil { - t.Errorf("Expected error on APIerSv1.GetRatingProfile, received : %+v", rpl) - } - attrGetRatingPlan.Subject = "dan" - attrGetRatingPlan.Tenant = "other_tenant" - if err := rater.Call(utils.APIerSv1GetRatingProfile, attrGetRatingPlan, &rpl); err.Error() != utils.ErrNotFound.Error() { - t.Errorf("Expected error on APIerSv1.GetRatingProfile, received : %+v", err) - } - - expectedIds := []string{"call:dan", "call:*any"} - var result []string - if err := rater.Call(utils.APIerSv1GetRatingProfileIDs, &utils.PaginatorWithTenant{Tenant: "cgrates.org"}, &result); err != nil { - t.Error(err) - } else if len(expectedIds) != len(result) { - t.Errorf("Expecting : %+v, received: %+v", expected, result) - } -} - -func testAPIerSv1GetRatingProfileIDsWithoutTenant(t *testing.T) { - expectedIds := []string{"call:dan", "call:*any"} - var result []string - if err := rater.Call(utils.APIerSv1GetRatingProfileIDs, &utils.PaginatorWithTenant{}, &result); err != nil { - t.Error(err) - } else { - sort.Strings(expectedIds) - sort.Strings(result) - if !reflect.DeepEqual(expectedIds, result) { - t.Errorf("Expected %+v, received %+v", expectedIds, result) - } - } -} - -func testAPIerSv1GetRatingProfileWithoutTenant(t *testing.T) { - var rpl engine.RatingProfile - attrGetRatingPlan := &utils.AttrGetRatingProfile{ - Category: "call", Subject: "dan"} - actTime, err := utils.ParseTimeDetectLayout("2012-01-01T00:00:00Z", utils.EmptyString) - if err != nil { - t.Error(err) - } - expected := engine.RatingProfile{ - Id: "*out:cgrates.org:call:dan", - RatingPlanActivations: engine.RatingPlanActivations{ - { - ActivationTime: actTime, - RatingPlanId: "RETAIL1", - FallbackKeys: []string{"*out:cgrates.org:call:dan2"}, - }, - { - ActivationTime: actTime, - RatingPlanId: "RETAIL1", - FallbackKeys: []string{"*out:cgrates.org:call:dan2"}, - }, - }, - } - if err := rater.Call(utils.APIerSv1GetRatingProfile, &attrGetRatingPlan, &rpl); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rpl) { - t.Errorf("Calling APIerSv1.GetRatingProfile expected: %+v \n, received: %+v", utils.ToJSON(expected), utils.ToJSON(rpl)) - } -} - -func testApierGetActionTrigger(t *testing.T) { - //nothing to get from database - var atrs *engine.ActionTriggers - if err := rater.Call(utils.APIerSv1GetActionTriggers, - &AttrGetActionTriggers{GroupIDs: []string{"TEST_ID1"}}, &atrs); err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } - - //set an ActionTrigger in database - var reply string - if err := rater.Call(utils.APIerSv1SetActionTrigger, - AttrSetActionTrigger{ - GroupID: "TEST_ID1", - UniqueID: "TEST_ID2", - }, &reply); err != nil { - t.Error(err) - } - - //get from database and compare - newActTrg := &engine.ActionTriggers{ - { - ID: "TEST_ID1", - UniqueID: "TEST_ID2", - Balance: &engine.BalanceFilter{}, - }, - } - if err := rater.Call(utils.APIerSv1GetActionTriggers, - &AttrGetActionTriggers{GroupIDs: []string{"TEST_ID1"}}, &atrs); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(newActTrg, atrs) { - t.Errorf("Expected %+v \n, received %+v", utils.ToJSON(newActTrg), utils.ToJSON(atrs)) - } - - //remove the ActionTrigger from dataBase - if err := rater.Call(utils.APIerSv1RemoveActionTrigger, - &AttrRemoveActionTrigger{GroupID: "TEST_ID1"}, &reply); err != nil { - t.Error(err) - } else if reply != utils.OK { - t.Errorf("Unexpected result") - } - - //nothing to get from dataBase - if err := rater.Call(utils.APIerSv1GetActionTriggers, - &AttrGetActionTriggers{GroupIDs: []string{"TEST_ID1"}}, &atrs); err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - // Test here ReloadCache func testApierReloadCache(t *testing.T) { var reply string @@ -1074,11 +381,7 @@ func testApierReloadCache(t *testing.T) { } var rcvStats map[string]*ltcache.CacheStats expectedStats := engine.GetDefaultEmptyCacheStats() - expectedStats[utils.CacheAccountActionPlans].Items = 1 - expectedStats[utils.CacheActionPlans].Items = 1 expectedStats[utils.CacheActions].Items = 1 - expectedStats[utils.CacheRatingProfiles].Items = 3 - expectedStats[utils.CacheRatingPlans].Items = 1 expectedStats[utils.CacheReverseDestinations].Items = 10 expectedStats[utils.CacheLoadIDs].Items = 8 expectedStats[utils.CacheRPCConnections].Items = 1 @@ -1101,99 +404,6 @@ func testApierGetDestination(t *testing.T) { } } -// Test here GetRatingPlan -func testApierGetRatingPlan(t *testing.T) { - reply := new(engine.RatingPlan) - rplnId := "RETAIL1" - if err := rater.Call(utils.APIerSv1GetRatingPlan, &rplnId, reply); err != nil { - t.Error("Got error on APIerSv1.GetRatingPlan: ", err.Error()) - } - // Check parts of info received since a full one is not possible due to unique map keys inside reply - if reply.Id != rplnId { - t.Error("Unexpected id received", reply.Id) - } - if len(reply.Timings) != 1 || len(reply.Ratings) != 1 { - t.Error("Unexpected number of items received") - } - riRate := &engine.RIRate{ConnectFee: 0, RoundingMethod: "*up", RoundingDecimals: 2, Rates: []*engine.RGRate{ - {GroupIntervalStart: 0, Value: 0, RateIncrement: 60 * time.Second, RateUnit: 60 * time.Second}, - }} - for _, rating := range reply.Ratings { - riRateJson, _ := json.Marshal(rating) - if !reflect.DeepEqual(rating, riRate) { - t.Errorf("Unexpected riRate received: %s", riRateJson) - // {"Id":"RT_FS_USERS","ConnectFee":0,"Rates":[{"GroupIntervalStart":0,"Value":0,"RateIncrement":60000000000,"RateUnit":60000000000}],"RoundingMethod":"*up","RoundingDecimals":0} - } - } -} - -func testApierRemoveRatingPlan(t *testing.T) { - rplnId := "RETAIL1" - var reply string - - err := rater.Call(utils.APIerSv1RemoveRatingPlan, &rplnId, &reply) - if err != nil { - t.Error(err) - } - if reply != utils.OK { - t.Errorf("Expected %s, received %s", utils.OK, reply) - } - //get rating plan (the one that was removed. should return 'err not found') - var ratingPlan *engine.RatingPlan - err = rater.Call(utils.APIerSv1GetRatingPlan, &rplnId, ratingPlan) - if err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Errorf("Expecting error: %s, received: %v", utils.ErrNotFound, err) - } -} - -// Test here AddBalance -func testApierAddBalance(t *testing.T) { - var reply string - attrs := &AttrAddBalance{Tenant: "cgrates.org", Account: "1001", BalanceType: utils.MetaMonetary, Value: 1.5} - if err := rater.Call(utils.APIerSv1AddBalance, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } - attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan", BalanceType: utils.MetaMonetary, Value: 1.5} - if err := rater.Call(utils.APIerSv1AddBalance, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } - attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan2", BalanceType: utils.MetaMonetary, Value: 1.5} - if err := rater.Call(utils.APIerSv1AddBalance, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } - attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan3", BalanceType: utils.MetaMonetary, Value: 1.5} - if err := rater.Call(utils.APIerSv1AddBalance, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } - attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan3", BalanceType: utils.MetaMonetary, Value: 2.1} - if err := rater.Call(utils.APIerSv1AddBalance, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } - attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan6", BalanceType: utils.MetaMonetary, Value: 2.1} - if err := rater.Call(utils.APIerSv1AddBalance, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } - attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan6", BalanceType: utils.MetaMonetary, Value: 1, Overwrite: true} - if err := rater.Call(utils.APIerSv1AddBalance, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } - -} - // Test here ExecuteAction func testApierExecuteAction(t *testing.T) { var reply string @@ -1273,296 +483,6 @@ func testApierSetActionPlan(t *testing.T) { } } -// Test here AddTriggeredAction -func testApierAddTriggeredAction(t *testing.T) { - var reply string - attrs := &AttrAddBalance{Tenant: "cgrates.org", Account: "dan32", BalanceType: utils.MetaMonetary, Value: 1.5} - if err := rater.Call(utils.APIerSv1AddBalance, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } - // Add balance to a previously known account - attrsAddTrigger := &AttrAddActionTrigger{Tenant: "cgrates.org", Account: "dan32", BalanceType: utils.MetaMonetary, - ThresholdType: "*min_balance", ThresholdValue: 2, BalanceDestinationIds: utils.MetaAny, Weight: 10, ActionsId: "WARN_VIA_HTTP"} - if err := rater.Call(utils.APIerSv1AddTriggeredAction, attrsAddTrigger, &reply); err != nil { - t.Error("Got error on APIerSv1.AddTriggeredAction: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddTriggeredAction received: %s", reply) - } - reply2 := utils.EmptyString - attrs2 := new(AttrAddActionTrigger) - *attrs2 = *attrsAddTrigger - attrs2.Account = "dan10" // Does not exist so it should error when adding triggers on it - // Add trigger to an account which does n exist - if err := rater.Call(utils.APIerSv1AddTriggeredAction, attrs2, &reply2); err == nil { - t.Error("Expecting error on APIerSv1.AddTriggeredAction.", err, reply2) - } -} - -// Test here GetAccountActionTriggers -func testApierGetAccountActionTriggers(t *testing.T) { - var reply engine.ActionTriggers - req := utils.TenantAccount{Tenant: "cgrates.org", Account: "dan32"} - if err := rater.Call(utils.APIerSv1GetAccountActionTriggers, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionTimings: ", err.Error()) - } else if len(reply) != 1 || reply[0].ActionsID != "WARN_VIA_HTTP" { - t.Errorf("Unexpected action triggers received %v", reply) - } -} - -func testApierAddTriggeredAction2(t *testing.T) { - var reply string - // Add balance to a previously known account - attrs := &AttrAddAccountActionTriggers{ActionTriggerIDs: []string{"STANDARD_TRIGGERS"}, Tenant: "cgrates.org", Account: "dan2"} - if err := rater.Call(utils.APIerSv1AddAccountActionTriggers, &attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.AddAccountActionTriggers: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddAccountActionTriggers received: %s", reply) - } - reply2 := utils.EmptyString - attrs2 := new(AttrAddAccountActionTriggers) - *attrs2 = *attrs - attrs2.Account = "dan10" // Does not exist so it should error when adding triggers on it - // Add trigger to an account which does n exist - if err := rater.Call(utils.APIerSv1AddAccountActionTriggers, &attrs2, &reply2); err == nil || reply2 == utils.OK { - t.Error("Expecting error on APIerSv1.AddAccountActionTriggers.", err, reply2) - } -} - -// Test here GetAccountActionTriggers -func testApierGetAccountActionTriggers2(t *testing.T) { - var reply engine.ActionTriggers - req := utils.TenantAccount{Tenant: "cgrates.org", Account: "dan2"} - if err := rater.Call(utils.APIerSv1GetAccountActionTriggers, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionTimings: ", err.Error()) - } else if len(reply) != 1 || reply[0].ActionsID != "LOG_BALANCE" { - t.Errorf("Unexpected action triggers received %v", reply) - } -} - -// Test here SetAccountActionTriggers -func testApierSetAccountActionTriggers(t *testing.T) { - // Test first get so we can steal the id which we need to remove - var reply engine.ActionTriggers - req := utils.TenantAccount{Tenant: "cgrates.org", Account: "dan2"} - if err := rater.Call(utils.APIerSv1GetAccountActionTriggers, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionTimings: ", err.Error()) - } else if len(reply) != 1 || reply[0].ActionsID != "LOG_BALANCE" { - for _, atr := range reply { - t.Logf("ATR: %+v", atr) - } - t.Errorf("Unexpected action triggers received %v", reply) - } - var setReply string - setReq := AttrSetAccountActionTriggers{ - Tenant: "cgrates.org", - Account: "dan2", - AttrSetActionTrigger: AttrSetActionTrigger{ - UniqueID: reply[0].UniqueID, - ActionTrigger: map[string]interface{}{ - utils.ActivationDate: "2016-02-05T18:00:00Z", - }, - }, - } - if err := rater.Call(utils.APIerSv1ResetAccountActionTriggers, setReq, &setReply); err != nil { - t.Error("Got error on APIerSv1.ResetActionTiming: ", err.Error()) - } else if setReply != utils.OK { - t.Error("Unexpected answer received", setReply) - } - if err := rater.Call(utils.APIerSv1SetAccountActionTriggers, setReq, &setReply); err != nil { - t.Error("Got error on APIerSv1.RemoveActionTiming: ", err.Error()) - } else if setReply != utils.OK { - t.Error("Unexpected answer received", setReply) - } - if err := rater.Call(utils.APIerSv1GetAccountActionTriggers, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionTriggers: ", err.Error()) - } else if len(reply) != 1 || reply[0].ActivationDate != time.Date(2016, 2, 5, 18, 0, 0, 0, time.UTC) { - t.Errorf("Unexpected action triggers received %+v", reply[0]) - } -} - -// Test here RemAccountActionTriggers -func testApierRemAccountActionTriggers(t *testing.T) { - // Test first get so we can steal the id which we need to remove - var reply engine.ActionTriggers - req := utils.TenantAccount{Tenant: "cgrates.org", Account: "dan2"} - if err := rater.Call(utils.APIerSv1GetAccountActionTriggers, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionTimings: ", err.Error()) - } else if len(reply) != 1 || reply[0].ActionsID != "LOG_BALANCE" { - for _, atr := range reply { - t.Logf("ATR: %+v", atr) - } - t.Errorf("Unexpected action triggers received %v", reply) - } - var rmReply string - rmReq := AttrRemoveAccountActionTriggers{Tenant: "cgrates.org", Account: "dan2", UniqueID: reply[0].UniqueID} - if err := rater.Call(utils.APIerSv1ResetAccountActionTriggers, rmReq, &rmReply); err != nil { - t.Error("Got error on APIerSv1.ResetActionTiming: ", err.Error()) - } else if rmReply != utils.OK { - t.Error("Unexpected answer received", rmReply) - } - if err := rater.Call(utils.APIerSv1RemoveAccountActionTriggers, rmReq, &rmReply); err != nil { - t.Error("Got error on APIerSv1.RemoveActionTiming: ", err.Error()) - } else if rmReply != utils.OK { - t.Error("Unexpected answer received", rmReply) - } - if err := rater.Call(utils.APIerSv1GetAccountActionTriggers, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionTriggers: ", err.Error()) - } else if len(reply) != 0 { - t.Errorf("Unexpected action triggers received %+v", reply[0]) - } -} - -// Test here SetAccount -func testApierSetAccount(t *testing.T) { - var reply string - attrs := &utils.AttrSetAccount{Tenant: "cgrates.org", Account: "dan7", ActionPlanID: "ATMS_1", ReloadScheduler: true} - if err := rater.Call(utils.APIerSv1SetAccount, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.SetAccount: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.SetAccount received: %s", reply) - } - reply2 := utils.EmptyString - attrs2 := new(utils.AttrSetAccount) - *attrs2 = *attrs - attrs2.ActionPlanID = "DUMMY_DATA" // Does not exist so it should error when adding triggers on it - // Add account with actions timing which does not exist - if err := rater.Call(utils.APIerSv1SetAccount, attrs2, &reply2); err == nil || reply2 == utils.OK { // OK is not welcomed - t.Error("Expecting error on APIerSv1.SetAccount.", err, reply2) - } -} - -// Test here GetAccountActionTimings -func testApierGetAccountActionPlan(t *testing.T) { - var reply []*AccountActionTiming - req := utils.TenantAccount{Tenant: "cgrates.org", Account: "dan7"} - if err := rater.Call(utils.APIerSv1GetAccountActionPlan, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionPlan: ", err.Error()) - } else if len(reply) != 1 { - t.Error("Unexpected action plan received: ", utils.ToJSON(reply)) - } else { - if reply[0].ActionPlanId != "ATMS_1" { - t.Errorf("Unexpected ActionoveAccountPlanId received") - } - } -} - -func testApierGetAccountActionPlanWithoutTenant(t *testing.T) { - var reply []*AccountActionTiming - req := utils.TenantAccount{Account: "dan7"} - if err := rater.Call(utils.APIerSv1GetAccountActionPlan, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionPlan: ", err.Error()) - } else if len(reply) != 1 { - t.Error("Unexpected action plan received: ", utils.ToJSON(reply)) - } else { - if reply[0].ActionPlanId != "ATMS_1" { - t.Errorf("Unexpected ActionoveAccountPlanId received") - } - } -} - -// Make sure we have scheduled actions -func testApierITGetScheduledActionsForAccount(t *testing.T) { - var rply []*scheduler.ScheduledAction - if err := rater.Call(utils.APIerSv1GetScheduledActions, - scheduler.ArgsGetScheduledActions{ - Tenant: utils.StringPointer("cgrates.org"), - Account: utils.StringPointer("dan7")}, &rply); err != nil { - t.Error("Unexpected error: ", err) - } else if len(rply) == 0 { - t.Errorf("ScheduledActions: %+v", rply) - } -} - -// Test here RemoveActionTiming -func testApierRemUniqueIDActionTiming(t *testing.T) { - var rmReply string - rmReq := AttrRemoveActionTiming{ActionPlanId: "ATMS_1", Tenant: "cgrates.org", Account: "dan4"} - if err := rater.Call(utils.APIerSv1RemoveActionTiming, &rmReq, &rmReply); err != nil { - t.Error("Got error on APIerSv1.RemoveActionTiming: ", err.Error()) - } else if rmReply != utils.OK { - t.Error("Unexpected answer received", rmReply) - } - var reply []*AccountActionTiming - req := utils.TenantAccount{Tenant: "cgrates.org", Account: "dan4"} - if err := rater.Call(utils.APIerSv1GetAccountActionPlan, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionPlan: ", err.Error()) - } else if len(reply) != 0 { - t.Error("Action timings was not removed") - } -} - -func testApierRemUniqueIDActionTimingWithoutTenant(t *testing.T) { - var rmReply string - rmReq := AttrRemoveActionTiming{ActionPlanId: "ATMS_1", Account: "dan4"} - if err := rater.Call(utils.APIerSv1RemoveActionTiming, &rmReq, &rmReply); err != nil { - t.Error("Got error on APIerSv1.RemoveActionTiming: ", err.Error()) - } else if rmReply != utils.OK { - t.Error("Unexpected answer received", rmReply) - } - var reply []*AccountActionTiming - req := utils.TenantAccount{Account: "dan4"} - if err := rater.Call(utils.APIerSv1GetAccountActionPlan, &req, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccountActionPlan: ", err.Error()) - } else if len(reply) != 0 { - t.Error("Action timings was not removed") - } -} - -// Test here GetAccount -func testApierGetAccount(t *testing.T) { - var reply *engine.Account - attrs := &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "1001"} - if err := rater.Call(utils.APIerSv2GetAccount, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccount: ", err.Error()) - } else if reply.BalanceMap[utils.MetaMonetary].GetTotalValue() != 11.5 { // We expect 11.5 since we have added in the previous test 1.5 - t.Errorf("Calling APIerSv1.GetBalance expected: 11.5, received: %f", reply.BalanceMap[utils.MetaMonetary].GetTotalValue()) - } - attrs = &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "dan"} - if err := rater.Call(utils.APIerSv2GetAccount, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccount: ", err.Error()) - } else if reply.BalanceMap[utils.MetaMonetary].GetTotalValue() != 1.5 { - t.Errorf("Calling APIerSv1.GetAccount expected: 1.5, received: %f", reply.BalanceMap[utils.MetaMonetary].GetTotalValue()) - } - // The one we have topped up though executeAction - attrs = &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "dan2"} - if err := rater.Call(utils.APIerSv2GetAccount, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccount: ", err.Error()) - } else if reply.BalanceMap[utils.MetaMonetary].GetTotalValue() != 11.5 { - t.Errorf("Calling APIerSv1.GetAccount expected: 10, received: %f", reply.BalanceMap[utils.MetaMonetary].GetTotalValue()) - } - attrs = &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "dan3"} - if err := rater.Call(utils.APIerSv2GetAccount, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccount: ", err.Error()) - } else if reply.BalanceMap[utils.MetaMonetary].GetTotalValue() != 3.6 { - t.Errorf("Calling APIerSv1.GetAccount expected: 3.6, received: %f", reply.BalanceMap[utils.MetaMonetary].GetTotalValue()) - } - attrs = &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "dan6"} - if err := rater.Call(utils.APIerSv2GetAccount, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.GetAccount: ", err.Error()) - } else if reply.BalanceMap[utils.MetaMonetary].GetTotalValue() != 1 { - t.Errorf("Calling APIerSv1.GetAccount expected: 1, received: %f", reply.BalanceMap[utils.MetaMonetary].GetTotalValue()) - } -} - -// Start with initial balance, top-up to test max_balance -func testApierTriggersExecute(t *testing.T) { - var reply string - attrs := &utils.AttrSetAccount{Tenant: "cgrates.org", Account: "dan8", ReloadScheduler: true} - if err := rater.Call(utils.APIerSv1SetAccount, attrs, &reply); err != nil { - t.Error("Got error on APIerSv1.SetAccount: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.SetAccount received: %s", reply) - } - attrAddBlnc := &AttrAddBalance{Tenant: "cgrates.org", Account: "1008", BalanceType: utils.MetaMonetary, Value: 2} - if err := rater.Call(utils.APIerSv1AddBalance, attrAddBlnc, &reply); err != nil { - t.Error("Got error on APIerSv1.AddBalance: ", err.Error()) - } else if reply != utils.OK { - t.Errorf("Calling APIerSv1.AddBalance received: %s", reply) - } -} - // Start fresh before loading from folder func testApierResetDataBeforeLoadFromFolder(t *testing.T) { testApierInitDataDb(t) diff --git a/apier/v1/auth.go b/apier/v1/auth.go deleted file mode 100644 index c2d4a86ee..000000000 --- a/apier/v1/auth.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "strconv" - "time" - - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -// Returns MaxUsage (for calls in seconds), -1 for no limit -func (apierSv1 *APIerSv1) GetMaxUsage(usageRecord *engine.UsageRecordWithAPIOpts, maxUsage *int64) error { - if apierSv1.Responder == nil { - return utils.NewErrNotConnected(utils.RALService) - } - if usageRecord.ToR == utils.EmptyString { - usageRecord.ToR = utils.MetaVoice - } - if usageRecord.RequestType == utils.EmptyString { - usageRecord.RequestType = apierSv1.Config.GeneralCfg().DefaultReqType - } - if usageRecord.Tenant == utils.EmptyString { - usageRecord.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - if usageRecord.Category == utils.EmptyString { - usageRecord.Category = apierSv1.Config.GeneralCfg().DefaultCategory - } - if usageRecord.Subject == utils.EmptyString { - usageRecord.Subject = usageRecord.Account - } - if usageRecord.SetupTime == utils.EmptyString { - usageRecord.SetupTime = utils.MetaNow - } - if usageRecord.Usage == utils.EmptyString { - usageRecord.Usage = strconv.FormatFloat( - float64(apierSv1.Config.SessionSCfg().GetDefaultUsage(usageRecord.ToR)), 'f', -1, 64) - } - cd, err := usageRecord.AsCallDescriptor(apierSv1.Config.GeneralCfg().DefaultTimezone, false) - if err != nil { - return utils.NewErrServerError(err) - } - var maxDur time.Duration - if err := apierSv1.Responder.GetMaxSessionTime(&engine.CallDescriptorWithAPIOpts{ - CallDescriptor: cd, - APIOpts: usageRecord.APIOpts, - }, &maxDur); err != nil { - return err - } - if maxDur == time.Duration(-1) { - *maxUsage = -1 - return nil - } - *maxUsage = maxDur.Nanoseconds() - return nil -} diff --git a/apier/v1/costs.go b/apier/v1/costs.go deleted file mode 100644 index 426e6b980..000000000 --- a/apier/v1/costs.go +++ /dev/null @@ -1,114 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "time" - - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -type AttrGetCost struct { - Tenant string - Category string - Subject string - AnswerTime string - Destination string - Usage string - APIOpts map[string]interface{} -} - -func (apierSv1 *APIerSv1) GetCost(attrs *AttrGetCost, ec *engine.EventCost) error { - if apierSv1.Responder == nil { - return utils.NewErrNotConnected(utils.RALService) - } - usage, err := utils.ParseDurationWithNanosecs(attrs.Usage) - if err != nil { - return err - } - aTime, err := utils.ParseTimeDetectLayout(attrs.AnswerTime, - apierSv1.Config.GeneralCfg().DefaultTimezone) - if err != nil { - return err - } - - cd := &engine.CallDescriptor{ - Category: attrs.Category, - Tenant: utils.FirstNonEmpty(attrs.Tenant, apierSv1.Config.GeneralCfg().DefaultTenant), - Subject: attrs.Subject, - Destination: attrs.Destination, - TimeStart: aTime, - TimeEnd: aTime.Add(usage), - DurationIndex: usage, - } - var cc engine.CallCost - if err := apierSv1.Responder.GetCost( - &engine.CallDescriptorWithAPIOpts{ - CallDescriptor: cd, - APIOpts: attrs.APIOpts, - }, &cc); err != nil { - return utils.NewErrServerError(err) - } - *ec = *engine.NewEventCostFromCallCost(&cc, "", "") - ec.Compute() - return nil -} - -type AttrGetDataCost struct { - Tenant string - Category string - Subject string - AnswerTime string - Usage time.Duration // the call duration so far (till TimeEnd) - Opts map[string]interface{} -} - -func (apierSv1 *APIerSv1) GetDataCost(attrs *AttrGetDataCost, reply *engine.DataCost) error { - if apierSv1.Responder == nil { - return utils.NewErrNotConnected(utils.RALService) - } - aTime, err := utils.ParseTimeDetectLayout(attrs.AnswerTime, - apierSv1.Config.GeneralCfg().DefaultTimezone) - if err != nil { - return err - } - cd := &engine.CallDescriptor{ - Category: attrs.Category, - Tenant: utils.FirstNonEmpty(attrs.Tenant, apierSv1.Config.GeneralCfg().DefaultTenant), - Subject: attrs.Subject, - TimeStart: aTime, - TimeEnd: aTime.Add(attrs.Usage), - DurationIndex: attrs.Usage, - ToR: utils.MetaData, - } - var cc engine.CallCost - if err := apierSv1.Responder.GetCost(&engine.CallDescriptorWithAPIOpts{ - CallDescriptor: cd, - APIOpts: attrs.Opts, - }, &cc); err != nil { - return utils.NewErrServerError(err) - } - if dc, err := cc.ToDataCost(); err != nil { - return utils.NewErrServerError(err) - } else if dc != nil { - *reply = *dc - } - return nil -} diff --git a/apier/v1/costs_it_test.go b/apier/v1/costs_it_test.go deleted file mode 100644 index 420bf793c..000000000 --- a/apier/v1/costs_it_test.go +++ /dev/null @@ -1,133 +0,0 @@ -// +build integration - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "path" - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - costCfgPath string - costCfg *config.CGRConfig - costRPC *rpc.Client - costConfigDIR string //run tests for specific configuration - - sTestsCost = []func(t *testing.T){ - testCostInitCfg, - testCostInitDataDb, - testCostResetStorDb, - testCostStartEngine, - testCostRPCConn, - testCostLoadFromFolder, - testCostGetCost, - testCostKillEngine, - } -) - -//Test start here -func TestCostIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - costConfigDIR = "tutinternal" - case utils.MetaMySQL: - costConfigDIR = "tutmysql" - case utils.MetaMongo: - costConfigDIR = "tutmongo" - case utils.MetaPostgres: - t.SkipNow() - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsCost { - t.Run(costConfigDIR, stest) - } -} - -func testCostInitCfg(t *testing.T) { - var err error - costCfgPath = path.Join(*dataDir, "conf", "samples", costConfigDIR) - costCfg, err = config.NewCGRConfigFromPath(costCfgPath) - if err != nil { - t.Error(err) - } -} - -func testCostInitDataDb(t *testing.T) { - if err := engine.InitDataDb(costCfg); err != nil { - t.Fatal(err) - } -} - -// Wipe out the cdr database -func testCostResetStorDb(t *testing.T) { - if err := engine.InitStorDb(costCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testCostStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(costCfgPath, *waitRater); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testCostRPCConn(t *testing.T) { - var err error - costRPC, err = newRPCClient(costCfg.ListenCfg()) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testCostLoadFromFolder(t *testing.T) { - var reply string - attrs := &utils.AttrLoadTpFromFolder{FolderPath: path.Join(*dataDir, "tariffplans", "tutorial")} - if err := costRPC.Call(utils.APIerSv1LoadTariffPlanFromFolder, attrs, &reply); err != nil { - t.Error(err) - } - time.Sleep(100 * time.Millisecond) -} - -func testCostGetCost(t *testing.T) { - attrs := AttrGetCost{Category: "call", Tenant: "cgrates.org", - Subject: "1001", AnswerTime: "*now", Destination: "1002", Usage: "120000000000"} //120s ( 2m) - var rply *engine.EventCost - if err := costRPC.Call(utils.APIerSv1GetCost, &attrs, &rply); err != nil { - t.Error("Unexpected nil error received: ", err.Error()) - } else if *rply.Cost != 0.700200 { // expect to get 0.7 (0.4 connect fee 0.2 first minute 0.1 each minute after) - t.Errorf("Unexpected cost received: %f", *rply.Cost) - } -} - -func testCostKillEngine(t *testing.T) { - if err := engine.KillEngine(*waitRater); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/debit.go b/apier/v1/debit.go deleted file mode 100644 index 651294bc4..000000000 --- a/apier/v1/debit.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -// DebitUsage will debit the balance for the usage cost, allowing the -// account to go negative if the cost calculated is greater than the balance -func (apierSv1 *APIerSv1) DebitUsage(usageRecord *engine.UsageRecordWithAPIOpts, reply *string) error { - return apierSv1.DebitUsageWithOptions(&AttrDebitUsageWithOptions{ - UsageRecord: usageRecord, - AllowNegativeAccount: true, - }, reply) -} - -// AttrDebitUsageWithOptions represents the DebitUsage request -type AttrDebitUsageWithOptions struct { - UsageRecord *engine.UsageRecordWithAPIOpts - AllowNegativeAccount bool // allow account to go negative during debit -} - -// DebitUsageWithOptions will debit the account based on the usage cost with -// additional options to control if the balance can go negative -func (apierSv1 *APIerSv1) DebitUsageWithOptions(args *AttrDebitUsageWithOptions, reply *string) error { - if apierSv1.Responder == nil { - return utils.NewErrNotConnected(utils.RALService) - } - usageRecord := args.UsageRecord.UsageRecord - if missing := utils.MissingStructFields(usageRecord, []string{"Account", "Destination", "Usage"}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - - // Set values for optional parameters - if usageRecord.ToR == "" { - usageRecord.ToR = utils.MetaVoice - } - if usageRecord.RequestType == "" { - usageRecord.RequestType = apierSv1.Config.GeneralCfg().DefaultReqType - } - if usageRecord.Tenant == "" { - usageRecord.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - if usageRecord.Category == "" { - usageRecord.Category = apierSv1.Config.GeneralCfg().DefaultCategory - } - if usageRecord.Subject == "" { - usageRecord.Subject = usageRecord.Account - } - if usageRecord.AnswerTime == "" { - usageRecord.AnswerTime = utils.MetaNow - } - - // Get the call descriptor from the usage record - cd, err := usageRecord.AsCallDescriptor(apierSv1.Config.GeneralCfg().DefaultTimezone, - !args.AllowNegativeAccount) - if err != nil { - return utils.NewErrServerError(err) - } - - // Calculate the cost for usage and debit the account - var cc engine.CallCost - if err := apierSv1.Responder.Debit(&engine.CallDescriptorWithAPIOpts{ - CallDescriptor: cd, - APIOpts: args.UsageRecord.APIOpts, - }, &cc); err != nil { - return utils.NewErrServerError(err) - } - - *reply = utils.OK - return nil -} diff --git a/apier/v1/debit_test.go b/apier/v1/debit_test.go deleted file mode 100644 index aadcdd38b..000000000 --- a/apier/v1/debit_test.go +++ /dev/null @@ -1,165 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - apierDebit *APIerSv1 - apierDebitStorage *engine.InternalDB - responder *engine.Responder - dm *engine.DataManager -) - -func init() { - cfg := config.NewDefaultCGRConfig() - config.SetCgrConfig(cfg) - apierDebitStorage = engine.NewInternalDB(nil, nil, true) - - responder := &engine.Responder{MaxComputedUsage: cfg.RalsCfg().MaxComputedUsage} - dm = engine.NewDataManager(apierDebitStorage, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dm) - apierDebit = &APIerSv1{ - DataManager: dm, - Config: cfg, - Responder: responder, - } -} - -func TestDebitUsageWithOptionsSetConfig(t *testing.T) { - cfg := config.NewDefaultCGRConfig() - config.SetCgrConfig(cfg) - apierDebitStorage = engine.NewInternalDB(nil, nil, true) - responder := &engine.Responder{MaxComputedUsage: cfg.RalsCfg().MaxComputedUsage} - dm = engine.NewDataManager(apierDebitStorage, cfg.CacheCfg(), nil) - engine.SetDataStorage(dm) - apierDebit = &APIerSv1{ - DataManager: dm, - Config: cfg, - Responder: responder, - } -} - -func TestDebitUsageWithOptions(t *testing.T) { - cgrTenant := "cgrates.org" - b10 := &engine.Balance{Value: 10, Weight: 10} - cgrAcnt1 := &engine.Account{ - ID: utils.ConcatenatedKey(cgrTenant, "account1"), - BalanceMap: map[string]engine.Balances{ - utils.MetaMonetary: {b10}, - }, - } - if err := apierDebitStorage.SetAccountDrv(cgrAcnt1); err != nil { - t.Error(err) - } - - dstDe := &engine.Destination{Id: "*any", Prefixes: []string{"*any"}} - if err := apierDebitStorage.SetDestinationDrv(dstDe, utils.NonTransactional); err != nil { - t.Error(err) - } - if err := apierDebitStorage.SetReverseDestinationDrv(dstDe.Id, dstDe.Prefixes, utils.NonTransactional); err != nil { - t.Error(err) - } - rp1 := &engine.RatingPlan{ - Id: "RP1", - Timings: map[string]*engine.RITiming{ - "30eab300": { - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{}, - StartTime: "00:00:00", - }, - }, - Ratings: map[string]*engine.RIRate{ - "b457f86d": { - ConnectFee: 0, - Rates: []*engine.RGRate{ - { - GroupIntervalStart: 0, - Value: 0.03, - RateIncrement: time.Second, - RateUnit: time.Second, - }, - }, - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - }, - DestinationRates: map[string]engine.RPRateList{ - dstDe.Id: []*engine.RPRate{ - { - Timing: "30eab300", - Rating: "b457f86d", - Weight: 10, - }, - }, - }, - } - if err := dm.SetRatingPlan(rp1, utils.NonTransactional); err != nil { - t.Error(err) - } - - rpfl := &engine.RatingProfile{Id: "*out:cgrates.org:call:account1", - RatingPlanActivations: engine.RatingPlanActivations{&engine.RatingPlanActivation{ - ActivationTime: time.Date(2001, 1, 1, 8, 0, 0, 0, time.UTC), - RatingPlanId: rp1.Id, - FallbackKeys: []string{}, - }}, - } - if err := dm.SetRatingProfile(rpfl, utils.NonTransactional); err != nil { - t.Error(err) - } - - usageRecord := &engine.UsageRecord{ - Tenant: cgrTenant, - Account: "account1", - Destination: "*any", - Usage: "1", - ToR: utils.MetaMonetary, - Category: "call", - SetupTime: time.Date(2013, 11, 7, 7, 42, 20, 0, time.UTC).String(), - AnswerTime: time.Date(2013, 11, 7, 7, 42, 20, 0, time.UTC).String(), - } - - var reply string - if err := apierDebit.DebitUsageWithOptions(&AttrDebitUsageWithOptions{ - UsageRecord: &engine.UsageRecordWithAPIOpts{UsageRecord: usageRecord}, - AllowNegativeAccount: false}, &reply); err != nil { - t.Error(err) - } - - // Reload the account and verify that the usage of $1 was removed from the monetary balance - resolvedAccount, err := apierDebitStorage.GetAccountDrv(cgrAcnt1.ID) - if err != nil { - t.Error(err) - } - eAcntVal := 9.0 - if resolvedAccount.BalanceMap[utils.MetaMonetary].GetTotalValue() != eAcntVal { - t.Errorf("Expected: %f, received: %f", eAcntVal, - resolvedAccount.BalanceMap[utils.MetaMonetary].GetTotalValue()) - } -} diff --git a/apier/v1/dispatcher.go b/apier/v1/dispatcher.go index 1696c8eb1..67606424b 100755 --- a/apier/v1/dispatcher.go +++ b/apier/v1/dispatcher.go @@ -539,48 +539,6 @@ func (dS *DispatcherSessionSv1) STIRIdentity(args *sessions.V1STIRIdentityArgs, return dS.dS.SessionSv1STIRIdentity(args, reply) } -func NewDispatcherResponder(dps *dispatchers.DispatcherService) *DispatcherResponder { - return &DispatcherResponder{dS: dps} -} - -// Exports RPC from RLs -type DispatcherResponder struct { - dS *dispatchers.DispatcherService -} - -func (dS *DispatcherResponder) GetCost(args *engine.CallDescriptorWithAPIOpts, reply *engine.CallCost) error { - return dS.dS.ResponderGetCost(args, reply) -} - -func (dS *DispatcherResponder) Debit(args *engine.CallDescriptorWithAPIOpts, reply *engine.CallCost) error { - return dS.dS.ResponderDebit(args, reply) -} - -func (dS *DispatcherResponder) MaxDebit(args *engine.CallDescriptorWithAPIOpts, reply *engine.CallCost) error { - return dS.dS.ResponderMaxDebit(args, reply) -} - -func (dS *DispatcherResponder) RefundIncrements(args *engine.CallDescriptorWithAPIOpts, reply *engine.Account) error { - return dS.dS.ResponderRefundIncrements(args, reply) -} - -func (dS *DispatcherResponder) RefundRounding(args *engine.CallDescriptorWithAPIOpts, reply *float64) error { - return dS.dS.ResponderRefundRounding(args, reply) -} - -func (dS *DispatcherResponder) GetMaxSessionTime(args *engine.CallDescriptorWithAPIOpts, reply *time.Duration) error { - return dS.dS.ResponderGetMaxSessionTime(args, reply) -} - -func (dS *DispatcherResponder) Shutdown(args *utils.TenantWithAPIOpts, reply *string) error { - return dS.dS.ResponderShutdown(args, reply) -} - -// Ping used to detreminate if component is active -func (dS *DispatcherResponder) Ping(args *utils.CGREvent, reply *string) error { - return dS.dS.ResponderPing(args, reply) -} - func NewDispatcherCacheSv1(dps *dispatchers.DispatcherService) *DispatcherCacheSv1 { return &DispatcherCacheSv1{dS: dps} } @@ -704,35 +662,6 @@ func (dS *DispatcherGuardianSv1) Ping(args *utils.CGREvent, reply *string) error return dS.dS.GuardianSv1Ping(args, reply) } -func NewDispatcherSchedulerSv1(dps *dispatchers.DispatcherService) *DispatcherSchedulerSv1 { - return &DispatcherSchedulerSv1{dS: dps} -} - -// Exports RPC from SchedulerSv1 -type DispatcherSchedulerSv1 struct { - dS *dispatchers.DispatcherService -} - -// Reload reloads scheduler instructions -func (dS *DispatcherSchedulerSv1) Reload(attr *utils.CGREvent, reply *string) (err error) { - return dS.dS.SchedulerSv1Reload(attr, reply) -} - -// Ping used to detreminate if component is active -func (dS *DispatcherSchedulerSv1) Ping(args *utils.CGREvent, reply *string) error { - return dS.dS.SchedulerSv1Ping(args, reply) -} - -// ExecuteActions execute an actionPlan or multiple actionsPlans between a time interval -func (dS *DispatcherSchedulerSv1) ExecuteActions(args *utils.AttrsExecuteActions, reply *string) error { - return dS.dS.SchedulerSv1ExecuteActions(args, reply) -} - -// ExecuteActionPlans execute multiple actionPlans one by one -func (dS *DispatcherSchedulerSv1) ExecuteActionPlans(args *utils.AttrsExecuteActionPlans, reply *string) (err error) { - return dS.dS.SchedulerSv1ExecuteActionPlans(args, reply) -} - func NewDispatcherSv1(dS *dispatchers.DispatcherService) *DispatcherSv1 { return &DispatcherSv1{dS: dS} } @@ -873,24 +802,6 @@ func (dS *DispatcherCoreSv1) Sleep(arg *utils.DurationArgs, reply *string) error return dS.dS.CoreSv1Sleep(arg, reply) } -func NewDispatcherRALsV1(dps *dispatchers.DispatcherService) *DispatcherRALsV1 { - return &DispatcherRALsV1{dS: dps} -} - -// Exports RPC from RLs -type DispatcherRALsV1 struct { - dS *dispatchers.DispatcherService -} - -func (dS *DispatcherRALsV1) GetRatingPlansCost(args *utils.RatingPlanCostArg, reply *dispatchers.RatingPlanCost) error { - return dS.dS.RALsV1GetRatingPlansCost(args, reply) -} - -// Ping used to detreminate if component is active -func (dS *DispatcherRALsV1) Ping(args *utils.CGREvent, reply *string) error { - return dS.dS.RALsV1Ping(args, reply) -} - type DispatcherReplicatorSv1 struct { dS *dispatchers.DispatcherService } @@ -904,11 +815,6 @@ func (dS *DispatcherReplicatorSv1) Ping(args *utils.CGREvent, reply *string) err return dS.dS.ReplicatorSv1Ping(args, reply) } -// GetAccount -func (dS *DispatcherReplicatorSv1) GetAccount(args *utils.StringWithAPIOpts, reply *engine.Account) error { - return dS.dS.ReplicatorSv1GetAccount(args, reply) -} - // GetDestination func (dS *DispatcherReplicatorSv1) GetDestination(key *utils.StringWithAPIOpts, reply *engine.Destination) error { return dS.dS.ReplicatorSv1GetDestination(key, reply) @@ -959,46 +865,6 @@ func (dS *DispatcherReplicatorSv1) GetResourceProfile(tntID *utils.TenantIDWithA return dS.dS.ReplicatorSv1GetResourceProfile(tntID, reply) } -// GetActionTriggers -func (dS *DispatcherReplicatorSv1) GetActionTriggers(id *utils.StringWithAPIOpts, reply *engine.ActionTriggers) error { - return dS.dS.ReplicatorSv1GetActionTriggers(id, reply) -} - -// GetSharedGroup -func (dS *DispatcherReplicatorSv1) GetSharedGroup(id *utils.StringWithAPIOpts, reply *engine.SharedGroup) error { - return dS.dS.ReplicatorSv1GetSharedGroup(id, reply) -} - -// GetActions -func (dS *DispatcherReplicatorSv1) GetActions(id *utils.StringWithAPIOpts, reply *engine.Actions) error { - return dS.dS.ReplicatorSv1GetActions(id, reply) -} - -// GetActionPlan -func (dS *DispatcherReplicatorSv1) GetActionPlan(id *utils.StringWithAPIOpts, reply *engine.ActionPlan) error { - return dS.dS.ReplicatorSv1GetActionPlan(id, reply) -} - -// GetAllActionPlans -func (dS *DispatcherReplicatorSv1) GetAllActionPlans(args *utils.StringWithAPIOpts, reply *map[string]*engine.ActionPlan) error { - return dS.dS.ReplicatorSv1GetAllActionPlans(args, reply) -} - -// GetAccountActionPlans -func (dS *DispatcherReplicatorSv1) GetAccountActionPlans(id *utils.StringWithAPIOpts, reply *[]string) error { - return dS.dS.ReplicatorSv1GetAccountActionPlans(id, reply) -} - -// GetRatingPlan -func (dS *DispatcherReplicatorSv1) GetRatingPlan(id *utils.StringWithAPIOpts, reply *engine.RatingPlan) error { - return dS.dS.ReplicatorSv1GetRatingPlan(id, reply) -} - -// GetRatingProfile -func (dS *DispatcherReplicatorSv1) GetRatingProfile(id *utils.StringWithAPIOpts, reply *engine.RatingProfile) error { - return dS.dS.ReplicatorSv1GetRatingProfile(id, reply) -} - // GetRouteProfile func (dS *DispatcherReplicatorSv1) GetRouteProfile(tntID *utils.TenantIDWithAPIOpts, reply *engine.RouteProfile) error { return dS.dS.ReplicatorSv1GetRouteProfile(tntID, reply) @@ -1051,11 +917,6 @@ func (dS *DispatcherReplicatorSv1) SetDestination(args *engine.DestinationWithAP return dS.dS.ReplicatorSv1SetDestination(args, reply) } -// SetAccount -func (dS *DispatcherReplicatorSv1) SetAccount(args *engine.AccountWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1SetAccount(args, reply) -} - // SetReverseDestination func (dS *DispatcherReplicatorSv1) SetReverseDestination(args *engine.DestinationWithAPIOpts, reply *string) error { return dS.dS.ReplicatorSv1SetReverseDestination(args, reply) @@ -1091,31 +952,11 @@ func (dS *DispatcherReplicatorSv1) SetResourceProfile(args *engine.ResourceProfi return dS.dS.ReplicatorSv1SetResourceProfile(args, reply) } -// SetActionTriggers -func (dS *DispatcherReplicatorSv1) SetActionTriggers(args *engine.SetActionTriggersArgWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1SetActionTriggers(args, reply) -} - -// SetSharedGroup -func (dS *DispatcherReplicatorSv1) SetSharedGroup(args *engine.SharedGroupWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1SetSharedGroup(args, reply) -} - // SetActions func (dS *DispatcherReplicatorSv1) SetActions(args *engine.SetActionsArgsWithAPIOpts, reply *string) error { return dS.dS.ReplicatorSv1SetActions(args, reply) } -// SetRatingPlan -func (dS *DispatcherReplicatorSv1) SetRatingPlan(args *engine.RatingPlanWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1SetRatingPlan(args, reply) -} - -// SetRatingProfile -func (dS *DispatcherReplicatorSv1) SetRatingProfile(args *engine.RatingProfileWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1SetRatingProfile(args, reply) -} - // SetRouteProfile func (dS *DispatcherReplicatorSv1) SetRouteProfile(args *engine.RouteProfileWithAPIOpts, reply *string) error { return dS.dS.ReplicatorSv1SetRouteProfile(args, reply) @@ -1141,16 +982,6 @@ func (dS *DispatcherReplicatorSv1) SetRateProfile(args *utils.RateProfileWithAPI return dS.dS.ReplicatorSv1SetRateProfile(args, reply) } -// SetActionPlan -func (dS *DispatcherReplicatorSv1) SetActionPlan(args *engine.SetActionPlanArgWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1SetActionPlan(args, reply) -} - -// SetAccountActionPlans -func (dS *DispatcherReplicatorSv1) SetAccountActionPlans(args *engine.SetAccountActionPlansArgWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1SetAccountActionPlans(args, reply) -} - // SetDispatcherHost func (dS *DispatcherReplicatorSv1) SetDispatcherHost(args *engine.DispatcherHostWithAPIOpts, reply *string) error { return dS.dS.ReplicatorSv1SetDispatcherHost(args, reply) @@ -1171,11 +1002,6 @@ func (dS *DispatcherReplicatorSv1) RemoveDestination(args *utils.StringWithAPIOp return dS.dS.ReplicatorSv1RemoveDestination(args, reply) } -// RemoveAccount -func (dS *DispatcherReplicatorSv1) RemoveAccount(args *utils.StringWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1RemoveAccount(args, reply) -} - // RemoveStatQueue func (dS *DispatcherReplicatorSv1) RemoveStatQueue(args *utils.TenantIDWithAPIOpts, reply *string) error { return dS.dS.ReplicatorSv1RemoveStatQueue(args, reply) @@ -1211,41 +1037,6 @@ func (dS *DispatcherReplicatorSv1) RemoveResourceProfile(args *utils.TenantIDWit return dS.dS.ReplicatorSv1RemoveResourceProfile(args, reply) } -// RemoveActionTriggers -func (dS *DispatcherReplicatorSv1) RemoveActionTriggers(args *utils.StringWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1RemoveActionTriggers(args, reply) -} - -// RemoveSharedGroup -func (dS *DispatcherReplicatorSv1) RemoveSharedGroup(args *utils.StringWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1RemoveSharedGroup(args, reply) -} - -// RemoveActions -func (dS *DispatcherReplicatorSv1) RemoveActions(args *utils.StringWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1RemoveActions(args, reply) -} - -// RemoveActionPlan -func (dS *DispatcherReplicatorSv1) RemoveActionPlan(args *utils.StringWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1RemoveActionPlan(args, reply) -} - -// RemAccountActionPlans -func (dS *DispatcherReplicatorSv1) RemAccountActionPlans(args *engine.RemAccountActionPlansArgsWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1RemAccountActionPlans(args, reply) -} - -// RemoveRatingPlan -func (dS *DispatcherReplicatorSv1) RemoveRatingPlan(args *utils.StringWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1RemoveRatingPlan(args, reply) -} - -// RemoveRatingProfile -func (dS *DispatcherReplicatorSv1) RemoveRatingProfile(args *utils.StringWithAPIOpts, reply *string) error { - return dS.dS.ReplicatorSv1RemoveRatingProfile(args, reply) -} - // RemoveRouteProfile func (dS *DispatcherReplicatorSv1) RemoveRouteProfile(args *utils.TenantIDWithAPIOpts, reply *string) error { return dS.dS.ReplicatorSv1RemoveRouteProfile(args, reply) diff --git a/apier/v1/rals.go b/apier/v1/rals.go deleted file mode 100644 index a04bead9d..000000000 --- a/apier/v1/rals.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/dispatchers" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func NewRALsV1() *RALsV1 { - return &RALsV1{} -} - -// Exports RPC from RALs -type RALsV1 struct { -} - -// Call implements rpcclient.ClientConnector interface for internal RPC -func (rsv1 *RALsV1) Call(serviceMethod string, args interface{}, reply interface{}) error { - return utils.APIerRPCCall(rsv1, serviceMethod, args, reply) -} - -// GetRatingPlansCost returns EventCosts matching RatingPlanIDs -func (rsv1 *RALsV1) GetRatingPlansCost(arg *utils.RatingPlanCostArg, reply *dispatchers.RatingPlanCost) error { - if missing := utils.MissingStructFields(arg, []string{utils.RatingPlanIDs, - utils.Destination, utils.SetupTime, utils.Usage}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - //parse SetupTime and Usage - setupTime, err := utils.ParseTimeDetectLayout(arg.SetupTime, - config.CgrConfig().GeneralCfg().DefaultTimezone) - if err != nil { - return err - } - usage, err := utils.ParseDurationWithNanosecs(arg.Usage) - if err != nil { - return err - } - tenant := utils.UUIDSha1Prefix() - category := utils.MetaRatingPlanCost - subject := utils.UUIDSha1Prefix() - cd := &engine.CallDescriptor{ - Category: category, - Tenant: tenant, - Subject: subject, - Destination: arg.Destination, - TimeStart: setupTime, - TimeEnd: setupTime.Add(usage), - DurationIndex: usage, - } - for _, rp := range arg.RatingPlanIDs { // loop through RatingPlans until we find one without errors - rPrfl := &engine.RatingProfile{ - Id: utils.ConcatenatedKey(utils.MetaOut, - tenant, category, subject), - RatingPlanActivations: engine.RatingPlanActivations{ - &engine.RatingPlanActivation{ - ActivationTime: setupTime, - RatingPlanId: rp, - }, - }, - } - // force cache set so it can be picked by calldescriptor for cost calculation - if err := engine.Cache.Set(utils.CacheRatingProfilesTmp, rPrfl.Id, rPrfl, nil, - true, utils.NonTransactional); err != nil { - return err - } - cc, err := cd.GetCost() - if err := engine.Cache.Remove(utils.CacheRatingProfilesTmp, rPrfl.Id, // Remove here so we don't overload memory - true, utils.NonTransactional); err != nil { - return err - } - if err != nil { - // in case we have UnauthorizedDestination - // or NotFound try next RatingPlan - if err != utils.ErrUnauthorizedDestination && - err != utils.ErrNotFound { - return err - } - continue - } - ec := engine.NewEventCostFromCallCost(cc, utils.EmptyString, utils.EmptyString) - ec.Compute() - *reply = dispatchers.RatingPlanCost{ - EventCost: ec, - RatingPlanID: rp, - } - break - } - return nil -} - -func (rsv1 *RALsV1) Ping(ign *utils.CGREvent, reply *string) error { - *reply = utils.Pong - return nil -} diff --git a/apier/v1/replicator.go b/apier/v1/replicator.go index f27247288..fe2ee29ed 100644 --- a/apier/v1/replicator.go +++ b/apier/v1/replicator.go @@ -42,17 +42,6 @@ func (rplSv1 *ReplicatorSv1) Call(serviceMethod string, args interface{}, reply return utils.APIerRPCCall(rplSv1, serviceMethod, args, reply) } -// GetAccount is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetAccount(args *utils.StringWithAPIOpts, reply *engine.Account) error { - engine.UpdateReplicationFilters(utils.AccountPrefix, args.Arg, utils.IfaceAsString(args.APIOpts[utils.RemoteHostOpt])) - rcv, err := rplSv1.dm.GetAccount(args.Arg) - if err != nil { - return err - } - *reply = *rcv - return nil -} - // GetDestination is the remote method coresponding to the dataDb driver method func (rplSv1 *ReplicatorSv1) GetDestination(key *utils.StringWithAPIOpts, reply *engine.Destination) error { engine.UpdateReplicationFilters(utils.DestinationPrefix, key.Arg, utils.IfaceAsString(key.APIOpts[utils.RemoteHostOpt])) @@ -165,96 +154,6 @@ func (rplSv1 *ReplicatorSv1) GetResourceProfile(tntID *utils.TenantIDWithAPIOpts return nil } -// GetActionTriggers is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetActionTriggers(id *utils.StringWithAPIOpts, reply *engine.ActionTriggers) error { - engine.UpdateReplicationFilters(utils.ActionTriggerPrefix, id.Arg, utils.IfaceAsString(id.APIOpts[utils.RemoteHostOpt])) - rcv, err := rplSv1.dm.DataDB().GetActionTriggersDrv(id.Arg) - if err != nil { - return err - } - *reply = rcv - return nil -} - -// GetSharedGroup is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetSharedGroup(id *utils.StringWithAPIOpts, reply *engine.SharedGroup) error { - engine.UpdateReplicationFilters(utils.SharedGroupPrefix, id.Arg, utils.IfaceAsString(id.APIOpts[utils.RemoteHostOpt])) - rcv, err := rplSv1.dm.DataDB().GetSharedGroupDrv(id.Arg) - if err != nil { - return err - } - *reply = *rcv - return nil -} - -// GetActions is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetActions(id *utils.StringWithAPIOpts, reply *engine.Actions) error { - engine.UpdateReplicationFilters(utils.ActionPrefix, id.Arg, utils.IfaceAsString(id.APIOpts[utils.RemoteHostOpt])) - rcv, err := rplSv1.dm.DataDB().GetActionsDrv(id.Arg) - if err != nil { - return err - } - *reply = rcv - return nil -} - -// GetActionPlan is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetActionPlan(id *utils.StringWithAPIOpts, reply *engine.ActionPlan) error { - engine.UpdateReplicationFilters(utils.ActionPlanPrefix, id.Arg, utils.IfaceAsString(id.APIOpts[utils.RemoteHostOpt])) - rcv, err := rplSv1.dm.DataDB().GetActionPlanDrv(id.Arg, true, utils.NonTransactional) - if err != nil { - return err - } - *reply = *rcv - return nil -} - -// GetAllActionPlans is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetAllActionPlans(id *utils.StringWithAPIOpts, reply *map[string]*engine.ActionPlan) error { - rcv, err := rplSv1.dm.DataDB().GetAllActionPlansDrv() - if err != nil { - return err - } - for _, ap := range rcv { - engine.UpdateReplicationFilters(utils.ActionPlanPrefix, ap.Id, utils.IfaceAsString(id.APIOpts[utils.RemoteHostOpt])) - } - *reply = rcv - return nil -} - -// GetAccountActionPlans is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetAccountActionPlans(id *utils.StringWithAPIOpts, reply *[]string) error { - engine.UpdateReplicationFilters(utils.AccountActionPlansPrefix, id.Arg, utils.IfaceAsString(id.APIOpts[utils.RemoteHostOpt])) - rcv, err := rplSv1.dm.DataDB().GetAccountActionPlansDrv(id.Arg, false, utils.NonTransactional) - if err != nil { - return err - } - *reply = rcv - return nil -} - -// GetRatingPlan is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetRatingPlan(id *utils.StringWithAPIOpts, reply *engine.RatingPlan) error { - engine.UpdateReplicationFilters(utils.RatingPlanPrefix, id.Arg, utils.IfaceAsString(id.APIOpts[utils.RemoteHostOpt])) - rcv, err := rplSv1.dm.DataDB().GetRatingPlanDrv(id.Arg) - if err != nil { - return err - } - *reply = *rcv - return nil -} - -// GetRatingProfile is the remote method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) GetRatingProfile(id *utils.StringWithAPIOpts, reply *engine.RatingProfile) error { - engine.UpdateReplicationFilters(utils.RatingProfilePrefix, id.Arg, utils.IfaceAsString(id.APIOpts[utils.RemoteHostOpt])) - rcv, err := rplSv1.dm.DataDB().GetRatingProfileDrv(id.Arg) - if err != nil { - return err - } - *reply = *rcv - return nil -} - // GetRouteProfile is the remote method coresponding to the dataDb driver method func (rplSv1 *ReplicatorSv1) GetRouteProfile(tntID *utils.TenantIDWithAPIOpts, reply *engine.RouteProfile) error { engine.UpdateReplicationFilters(utils.RouteProfilePrefix, tntID.TenantID.TenantID(), utils.IfaceAsString(tntID.APIOpts[utils.RemoteHostOpt])) @@ -365,16 +264,6 @@ func (rplSv1 *ReplicatorSv1) GetIndexes(args *utils.GetIndexesArg, reply *map[st return nil } -// SetAccount is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) SetAccount(acc *engine.AccountWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().SetAccountDrv(acc.Account); err != nil { - return - } - // the account doesn't have cache - *reply = utils.OK - return -} - // SetDestination is the replication method coresponding to the dataDb driver method func (rplSv1 *ReplicatorSv1) SetDestination(dst *engine.DestinationWithAPIOpts, reply *string) (err error) { if err = rplSv1.dm.DataDB().SetDestinationDrv(dst.Destination, utils.NonTransactional); err != nil { @@ -505,71 +394,6 @@ func (rplSv1 *ReplicatorSv1) SetResource(rs *engine.ResourceWithAPIOpts, reply * return } -// SetActionTriggers is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) SetActionTriggers(args *engine.SetActionTriggersArgWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().SetActionTriggersDrv(args.Key, args.Attrs); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(args.APIOpts[utils.CacheOpt]), - args.Tenant, utils.CacheActionTriggers, args.Key, nil, nil, args.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// SetSharedGroup is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) SetSharedGroup(shg *engine.SharedGroupWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().SetSharedGroupDrv(shg.SharedGroup); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(shg.APIOpts[utils.CacheOpt]), - shg.Tenant, utils.CacheSharedGroups, shg.Id, nil, nil, shg.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// SetActions is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) SetActions(args *engine.SetActionsArgsWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().SetActionsDrv(args.Key, args.Acs); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(args.APIOpts[utils.CacheOpt]), - args.Tenant, utils.CacheActions, args.Key, nil, nil, args.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// SetRatingPlan is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) SetRatingPlan(rp *engine.RatingPlanWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().SetRatingPlanDrv(rp.RatingPlan); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(rp.APIOpts[utils.CacheOpt]), - rp.Tenant, utils.CacheRatingPlans, rp.Id, nil, nil, rp.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// SetRatingProfile is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) SetRatingProfile(rp *engine.RatingProfileWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().SetRatingProfileDrv(rp.RatingProfile); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(rp.APIOpts[utils.CacheOpt]), - rp.Tenant, utils.CacheRatingProfiles, rp.Id, nil, nil, rp.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - // SetRouteProfile is the replication method coresponding to the dataDb driver method func (rplSv1 *ReplicatorSv1) SetRouteProfile(sp *engine.RouteProfileWithAPIOpts, reply *string) (err error) { if err = rplSv1.dm.DataDB().SetRouteProfileDrv(sp.RouteProfile); err != nil { @@ -622,32 +446,6 @@ func (rplSv1 *ReplicatorSv1) SetDispatcherProfile(dpp *engine.DispatcherProfileW return } -// SetActionPlan is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) SetActionPlan(args *engine.SetActionPlanArgWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().SetActionPlanDrv(args.Key, args.Ats, args.Overwrite, utils.NonTransactional); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(args.APIOpts[utils.CacheOpt]), - args.Tenant, utils.CacheActionPlans, args.Key, nil, nil, args.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// SetAccountActionPlans is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) SetAccountActionPlans(args *engine.SetAccountActionPlansArgWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().SetAccountActionPlansDrv(args.AcntID, args.AplIDs, args.Overwrite); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(args.APIOpts[utils.CacheOpt]), - args.Tenant, utils.CacheAccountActionPlans, args.AcntID, nil, nil, args.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - // SetDispatcherHost is the replication method coresponding to the dataDb driver method func (rplSv1 *ReplicatorSv1) SetDispatcherHost(dpp *engine.DispatcherHostWithAPIOpts, reply *string) (err error) { if err = rplSv1.dm.DataDB().SetDispatcherHostDrv(dpp.DispatcherHost); err != nil { @@ -760,16 +558,6 @@ func (rplSv1 *ReplicatorSv1) RemoveDestination(id *utils.StringWithAPIOpts, repl return } -// RemoveAccount is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) RemoveAccount(id *utils.StringWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().RemoveAccountDrv(id.Arg); err != nil { - return - } - // the account doesn't have cache - *reply = utils.OK - return -} - // RemoveStatQueue is the replication method coresponding to the dataDb driver method func (rplSv1 *ReplicatorSv1) RemoveStatQueue(args *utils.TenantIDWithAPIOpts, reply *string) (err error) { if err = rplSv1.dm.DataDB().RemStatQueueDrv(args.Tenant, args.ID); err != nil { @@ -861,97 +649,6 @@ func (rplSv1 *ReplicatorSv1) RemoveResourceProfile(args *utils.TenantIDWithAPIOp return } -// RemoveActionTriggers is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) RemoveActionTriggers(id *utils.StringWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().RemoveActionTriggersDrv(id.Arg); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(id.APIOpts[utils.CacheOpt]), - id.Tenant, utils.CacheActionTriggers, id.Arg, nil, nil, id.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// RemoveSharedGroup is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) RemoveSharedGroup(id *utils.StringWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().RemoveSharedGroupDrv(id.Arg); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(id.APIOpts[utils.CacheOpt]), - id.Tenant, utils.CacheSharedGroups, id.Arg, nil, nil, id.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// RemoveActions is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) RemoveActions(id *utils.StringWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().RemoveActionsDrv(id.Arg); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(id.APIOpts[utils.CacheOpt]), - id.Tenant, utils.CacheActions, id.Arg, nil, nil, id.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// RemoveActionPlan is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) RemoveActionPlan(id *utils.StringWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().RemoveActionPlanDrv(id.Arg, utils.NonTransactional); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(id.APIOpts[utils.CacheOpt]), - id.Tenant, utils.CacheActionPlans, id.Arg, nil, nil, id.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// RemAccountActionPlans is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) RemAccountActionPlans(args *engine.RemAccountActionPlansArgsWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().RemAccountActionPlansDrv(args.AcntID, args.ApIDs); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(args.APIOpts[utils.CacheOpt]), - args.Tenant, utils.CacheAccountActionPlans, args.AcntID, nil, nil, args.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// RemoveRatingPlan is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) RemoveRatingPlan(id *utils.StringWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().RemoveRatingPlanDrv(id.Arg); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(id.APIOpts[utils.CacheOpt]), - id.Tenant, utils.CacheRatingPlans, id.Arg, nil, nil, id.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - -// RemoveRatingProfile is the replication method coresponding to the dataDb driver method -func (rplSv1 *ReplicatorSv1) RemoveRatingProfile(id *utils.StringWithAPIOpts, reply *string) (err error) { - if err = rplSv1.dm.DataDB().RemoveRatingProfileDrv(id.Arg); err != nil { - return - } - if err = rplSv1.v1.CallCache(utils.IfaceAsString(id.APIOpts[utils.CacheOpt]), - id.Tenant, utils.CacheRatingProfiles, id.Arg, nil, nil, id.APIOpts); err != nil { - return - } - *reply = utils.OK - return -} - // RemoveRouteProfile is the replication method coresponding to the dataDb driver method func (rplSv1 *ReplicatorSv1) RemoveRouteProfile(args *utils.TenantIDWithAPIOpts, reply *string) (err error) { if err = rplSv1.dm.DataDB().RemoveRouteProfileDrv(args.Tenant, args.ID); err != nil { diff --git a/apier/v1/tpaccountactions.go b/apier/v1/tpaccountactions.go deleted file mode 100644 index e359e65c2..000000000 --- a/apier/v1/tpaccountactions.go +++ /dev/null @@ -1,149 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -// SetTPAccountActions creates a new AccountActions profile within a tariff plan -func (apierSv1 *APIerSv1) SetTPAccountActions(attrs *utils.TPAccountActions, reply *string) error { - if missing := utils.MissingStructFields(attrs, - []string{utils.TPid, utils.LoadId, utils.AccountField, utils.ActionPlanId}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if attrs.Tenant == utils.EmptyString { - attrs.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - if err := apierSv1.StorDb.SetTPAccountActions([]*utils.TPAccountActions{attrs}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -type AttrGetTPAccountActionsByLoadId struct { - TPid string // Tariff plan id - LoadId string // AccountActions id -} - -// GetTPAccountActionsByLoadId queries specific AccountActions profile on tariff plan -func (apierSv1 *APIerSv1) GetTPAccountActionsByLoadId(attrs *utils.TPAccountActions, reply *[]*utils.TPAccountActions) error { - mndtryFlds := []string{utils.TPid, utils.LoadId} - if len(attrs.Account) != 0 { // If account provided as filter, make all related fields mandatory - mndtryFlds = append(mndtryFlds, utils.AccountField) - } - if missing := utils.MissingStructFields(attrs, mndtryFlds); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - if attrs.Tenant == utils.EmptyString { - attrs.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - aas, err := apierSv1.StorDb.GetTPAccountActions(attrs) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = aas - return nil -} - -type AttrGetTPAccountActions struct { - TPid string // Tariff plan id - AccountActionsId string // DerivedCharge id -} - -// GetTPAccountActions queries specific DerivedCharge on tariff plan -func (apierSv1 *APIerSv1) GetTPAccountActions(attrs *AttrGetTPAccountActions, reply *utils.TPAccountActions) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.AccountActionsId}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - filter := &utils.TPAccountActions{TPid: attrs.TPid} - if err := filter.SetAccountActionsId(attrs.AccountActionsId); err != nil { - return err - } - aas, err := apierSv1.StorDb.GetTPAccountActions(filter) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = *aas[0] - return nil -} - -type AttrGetTPAccountActionIds struct { - TPid string // Tariff plan id - utils.PaginatorWithSearch -} - -// GetTPAccountActionLoadIds queries AccountActions identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPAccountActionLoadIds(attrs *AttrGetTPAccountActionIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPAccountActions, - utils.TPDistinctIds{utils.Loadid}, nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// GetTPAccountActionIds queries DerivedCharges identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPAccountActionIds(attrs *AttrGetTPAccountActionIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPAccountActions, - utils.TPDistinctIds{utils.Loadid, utils.TenantCfg, utils.AccountLowerCase}, nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// RemoveTPAccountActions removes specific AccountActions on Tariff plan -func (apierSv1 *APIerSv1) RemoveTPAccountActions(attrs *AttrGetTPAccountActions, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.AccountActionsId}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - aa := engine.AccountActionMdl{Tpid: attrs.TPid} - if err := aa.SetAccountActionId(attrs.AccountActionsId); err != nil { - return err - } - if err := apierSv1.StorDb.RemTpData(utils.TBLTPAccountActions, aa.Tpid, - map[string]string{utils.Loadid: aa.Loadid, utils.TenantCfg: aa.Tenant, utils.AccountLowerCase: aa.Account}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} diff --git a/apier/v1/tpaccountactions_it_test.go b/apier/v1/tpaccountactions_it_test.go deleted file mode 100644 index 21b5a1a6c..000000000 --- a/apier/v1/tpaccountactions_it_test.go +++ /dev/null @@ -1,231 +0,0 @@ -// +build offline - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "net/rpc/jsonrpc" - "path" - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - tpAccActionsCfgPath string - tpAccActionsCfg *config.CGRConfig - tpAccActionsRPC *rpc.Client - tpAccActions *utils.TPAccountActions - tpAccActionsDelay int - tpAccActionsConfigDIR string //run tests for specific configuration - tpAccActionID = "ID:cgrates.org:1001" -) - -var sTestsTPAccActions = []func(t *testing.T){ - testTPAccActionsInitCfg, - testTPAccActionsResetStorDb, - testTPAccActionsStartEngine, - testTPAccActionsRpcConn, - testTPAccActionsGetTPAccActionBeforeSet, - testTPAccActionsSetTPAccAction, - testTPAccActionsGetTPAccActionAfterSet, - testTPAccActionsGetTPAccountActionsByLoadId, - testTPAccActionsGetTPAccountActionLoadIds, - testTPAccActionsGetTPAccountActionIds, - testTPAccActionsUpdateTPAccAction, - testTPAccActionsGetTPAccActionAfterUpdate, - testTPAccActionsRemTPAccAction, - testTPAccActionsGetTPAccActionAfterRemove, - testTPAccActionsKillEngine, -} - -//Test start here -func TestTPAccActionsIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - tpAccActionsConfigDIR = "tutinternal" - case utils.MetaMySQL: - tpAccActionsConfigDIR = "tutmysql" - case utils.MetaMongo: - tpAccActionsConfigDIR = "tutmongo" - case utils.MetaPostgres: - tpAccActionsConfigDIR = "tutpostgres" - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsTPAccActions { - t.Run(tpAccActionsConfigDIR, stest) - } -} - -func testTPAccActionsInitCfg(t *testing.T) { - var err error - tpAccActionsCfgPath = path.Join(*dataDir, "conf", "samples", tpAccActionsConfigDIR) - tpAccActionsCfg, err = config.NewCGRConfigFromPath(tpAccActionsCfgPath) - if err != nil { - t.Error(err) - } - tpAccActionsDelay = 1000 -} - -// Wipe out the cdr database -func testTPAccActionsResetStorDb(t *testing.T) { - if err := engine.InitStorDb(tpAccActionsCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testTPAccActionsStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(tpAccActionsCfgPath, tpAccActionsDelay); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testTPAccActionsRpcConn(t *testing.T) { - var err error - tpAccActionsRPC, err = jsonrpc.Dial(utils.TCP, tpAccActionsCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testTPAccActionsGetTPAccActionBeforeSet(t *testing.T) { - var reply *utils.TPAccountActions - if err := tpAccActionsRPC.Call(utils.APIerSv1GetTPAccountActions, - &AttrGetTPAccountActions{TPid: "TPAcc", AccountActionsId: tpAccActionID}, &reply); err == nil || - err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } - -} - -func testTPAccActionsSetTPAccAction(t *testing.T) { - tpAccActions = &utils.TPAccountActions{ - TPid: "TPAcc", - LoadId: "ID", - Tenant: "cgrates.org", - Account: "1001", - ActionPlanId: "PREPAID_10", - //ActionTriggersId: "STANDARD_TRIGGERS", // ActionTriggersId is optional - AllowNegative: true, - Disabled: false, - } - var result string - if err := tpAccActionsRPC.Call(utils.APIerSv1SetTPAccountActions, tpAccActions, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPAccActionsGetTPAccActionAfterSet(t *testing.T) { - var reply *utils.TPAccountActions - if err := tpAccActionsRPC.Call(utils.APIerSv1GetTPAccountActions, - &AttrGetTPAccountActions{TPid: "TPAcc", AccountActionsId: tpAccActionID}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpAccActions, reply) { - t.Errorf("Expecting : %+v, received: %+v", tpAccActions, reply) - } -} - -func testTPAccActionsGetTPAccountActionsByLoadId(t *testing.T) { - var reply *[]*utils.TPAccountActions - if err := tpAccActionsRPC.Call(utils.APIerSv1GetTPAccountActionsByLoadId, - &utils.TPAccountActions{TPid: "TPAcc", LoadId: "ID"}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpAccActions, (*reply)[0]) { - t.Errorf("Expecting : %+v, received: %+v", tpAccActions, (*reply)[0]) - } -} - -func testTPAccActionsGetTPAccountActionLoadIds(t *testing.T) { - var result []string - expectedTPID := []string{"ID"} - if err := tpAccActionsRPC.Call(utils.APIerSv1GetTPAccountActionLoadIds, - &AttrGetTPAccountActionIds{TPid: "TPAcc"}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expectedTPID, result) { - t.Errorf("Expecting: %+v, received: %+v", expectedTPID, result) - } -} - -func testTPAccActionsGetTPAccountActionIds(t *testing.T) { - var result []string - expectedTPID := []string{"ID:cgrates.org:1001"} - if err := tpAccActionsRPC.Call(utils.APIerSv1GetTPAccountActionIds, - &AttrGetTPAccountActionIds{TPid: "TPAcc"}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expectedTPID, result) { - t.Errorf("Expecting: %+v, received: %+v", expectedTPID, result) - } -} - -func testTPAccActionsUpdateTPAccAction(t *testing.T) { - tpAccActions.ActionPlanId = "PlanOne" - var result string - if err := tpAccActionsRPC.Call(utils.APIerSv1SetTPAccountActions, tpAccActions, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } - -} - -func testTPAccActionsGetTPAccActionAfterUpdate(t *testing.T) { - var reply *utils.TPAccountActions - if err := tpAccActionsRPC.Call(utils.APIerSv1GetTPAccountActions, - &AttrGetTPAccountActions{TPid: "TPAcc", AccountActionsId: tpAccActionID}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpAccActions, reply) { - t.Errorf("Expecting : %+v, received: %+v", tpAccActions, reply) - } - -} - -func testTPAccActionsRemTPAccAction(t *testing.T) { - var resp string - if err := tpAccActionsRPC.Call(utils.APIerSv1RemoveTPAccountActions, - &AttrGetTPAccountActions{TPid: "TPAcc", AccountActionsId: tpAccActionID}, &resp); err != nil { - t.Error(err) - } else if resp != utils.OK { - t.Error("Unexpected reply returned", resp) - } -} - -func testTPAccActionsGetTPAccActionAfterRemove(t *testing.T) { - var reply *utils.TPAccountActions - if err := tpAccActionsRPC.Call(utils.APIerSv1GetTPAccountActions, - &AttrGetTPAccountActions{TPid: "TPAcc", AccountActionsId: tpAccActionID}, &reply); err == nil || - err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPAccActionsKillEngine(t *testing.T) { - if err := engine.KillEngine(tpAccActionsDelay); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/tpactionplans.go b/apier/v1/tpactionplans.go deleted file mode 100644 index dcc34c728..000000000 --- a/apier/v1/tpactionplans.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "fmt" - - "github.com/cgrates/cgrates/utils" -) - -// SetTPActionPlan creates a new ActionTimings profile within a tariff plan -func (apierSv1 *APIerSv1) SetTPActionPlan(attrs *utils.TPActionPlan, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID, utils.ActionPlan}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - for _, at := range attrs.ActionPlan { - requiredFields := []string{utils.ActionsId, utils.TimingId, utils.Weight} - if missing := utils.MissingStructFields(at, requiredFields); len(missing) != 0 { - return fmt.Errorf("%s:Action:%s:%v", utils.ErrMandatoryIeMissing.Error(), at.ActionsId, missing) - } - } - if err := apierSv1.StorDb.SetTPActionPlans([]*utils.TPActionPlan{attrs}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -type AttrGetTPActionPlan struct { - TPid string // Tariff plan id - ID string // ActionPlans id -} - -// GetTPActionPlan queries specific ActionPlan profile on tariff plan -func (apierSv1 *APIerSv1) GetTPActionPlan(attrs *AttrGetTPActionPlan, reply *utils.TPActionPlan) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - aps, err := apierSv1.StorDb.GetTPActionPlans(attrs.TPid, attrs.ID) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = *aps[0] - return nil -} - -type AttrGetTPActionPlanIds struct { - TPid string // Tariff plan id - utils.PaginatorWithSearch -} - -// GetTPActionPlanIds queries ActionPlan identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPActionPlanIds(attrs *AttrGetTPActionPlanIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPActionPlans, - utils.TPDistinctIds{utils.TagCfg}, nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// RemoveTPActionPlan removes specific ActionPlan on Tariff plan -func (apierSv1 *APIerSv1) RemoveTPActionPlan(attrs *AttrGetTPActionPlan, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.RemTpData(utils.TBLTPActionPlans, - attrs.TPid, map[string]string{utils.TagCfg: attrs.ID}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} diff --git a/apier/v1/tpactionplans_it_test.go b/apier/v1/tpactionplans_it_test.go deleted file mode 100644 index 0025b40a0..000000000 --- a/apier/v1/tpactionplans_it_test.go +++ /dev/null @@ -1,242 +0,0 @@ -// +build offline - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "net/rpc/jsonrpc" - "path" - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - tpAccPlansCfgPath string - tpAccPlansCfg *config.CGRConfig - tpAccPlansRPC *rpc.Client - tpAccPlan *utils.TPActionPlan - tpAccPlansDelay int - tpAccPlansConfigDIR string //run tests for specific configuration - -) - -var sTestsTPAccPlans = []func(t *testing.T){ - testTPAccPlansInitCfg, - testTPAccPlansResetStorDb, - testTPAccPlansStartEngine, - testTPAccPlansRpcConn, - testTPAccPlansGetTPAccPlanBeforeSet, - testTPAccPlansSetTPAccPlan, - testTPAccPlansGetTPAccPlanAfterSet, - testTPAccPlansGetTPAccPlanIds, - testTPAccPlansUpdateTPAccPlan, - testTPAccPlansGetTPAccPlanAfterUpdate, - testTPAccPlansRemTPAccPlan, - testTPAccPlansGetTPAccPlanAfterRemove, - testTPAccPlansKillEngine, -} - -//Test start here -func TestTPAccPlansIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - tpAccPlansConfigDIR = "tutinternal" - case utils.MetaMySQL: - tpAccPlansConfigDIR = "tutmysql" - case utils.MetaMongo: - tpAccPlansConfigDIR = "tutmongo" - case utils.MetaPostgres: - tpAccPlansConfigDIR = "tutpostgres" - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsTPAccPlans { - t.Run(tpAccPlansConfigDIR, stest) - } -} - -func testTPAccPlansInitCfg(t *testing.T) { - var err error - tpAccPlansCfgPath = path.Join(*dataDir, "conf", "samples", tpAccPlansConfigDIR) - tpAccPlansCfg, err = config.NewCGRConfigFromPath(tpAccPlansCfgPath) - if err != nil { - t.Error(err) - } - switch tpAccPlansConfigDIR { - case "tutmongo": // Mongo needs more time to reset db, need to investigate - tpAccPlansDelay = 2000 - default: - tpAccPlansDelay = 1000 - } -} - -// Wipe out the cdr database -func testTPAccPlansResetStorDb(t *testing.T) { - if err := engine.InitStorDb(tpAccPlansCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testTPAccPlansStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(tpAccPlansCfgPath, tpAccPlansDelay); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testTPAccPlansRpcConn(t *testing.T) { - var err error - tpAccPlansRPC, err = jsonrpc.Dial(utils.TCP, tpAccPlansCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testTPAccPlansGetTPAccPlanBeforeSet(t *testing.T) { - var reply *utils.TPActionPlan - if err := tpAccPlansRPC.Call(utils.APIerSv1GetTPActionPlan, - &AttrGetTPActionPlan{TPid: "TPAcc", ID: "ID"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPAccPlansSetTPAccPlan(t *testing.T) { - tpAccPlan = &utils.TPActionPlan{ - TPid: "TPAcc", - ID: "ID", - ActionPlan: []*utils.TPActionTiming{ - { - ActionsId: "AccId", - TimingId: "TimingID", - Weight: 10, - }, - { - ActionsId: "AccId2", - TimingId: "TimingID2", - Weight: 11, - }, - }, - } - var result string - if err := tpAccPlansRPC.Call(utils.APIerSv1SetTPActionPlan, tpAccPlan, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPAccPlansGetTPAccPlanAfterSet(t *testing.T) { - var reply *utils.TPActionPlan - if err := tpAccPlansRPC.Call(utils.APIerSv1GetTPActionPlan, - &AttrGetTPActionPlan{TPid: "TPAcc", ID: "ID"}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpAccPlan.TPid, reply.TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpAccPlan.TPid, reply.TPid) - } else if !reflect.DeepEqual(tpAccPlan.ID, reply.ID) { - t.Errorf("Expecting : %+v, received: %+v", tpAccPlan.ID, reply.ID) - } else if !reflect.DeepEqual(len(tpAccPlan.ActionPlan), len(reply.ActionPlan)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpAccPlan.ActionPlan), len(reply.ActionPlan)) - } -} - -func testTPAccPlansGetTPAccPlanIds(t *testing.T) { - var result []string - expectedTPID := []string{"ID"} - if err := tpAccPlansRPC.Call(utils.APIerSv1GetTPActionPlanIds, - &AttrGetTPActionPlanIds{TPid: "TPAcc"}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expectedTPID, result) { - t.Errorf("Expecting: %+v, received: %+v", expectedTPID, result) - } - -} - -func testTPAccPlansUpdateTPAccPlan(t *testing.T) { - tpAccPlan.ActionPlan = []*utils.TPActionTiming{ - { - ActionsId: "AccId", - TimingId: "TimingID", - Weight: 10, - }, - { - ActionsId: "AccId2", - TimingId: "TimingID2", - Weight: 11, - }, - { - ActionsId: "AccId3", - TimingId: "TimingID3", - Weight: 12, - }, - } - var result string - if err := tpAccPlansRPC.Call(utils.APIerSv1SetTPActionPlan, tpAccPlan, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } - -} - -func testTPAccPlansGetTPAccPlanAfterUpdate(t *testing.T) { - var reply *utils.TPActionPlan - if err := tpAccPlansRPC.Call(utils.APIerSv1GetTPActionPlan, - &AttrGetTPActionPlan{TPid: "TPAcc", ID: "ID"}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpAccPlan.TPid, reply.TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpAccPlan.TPid, reply.TPid) - } else if !reflect.DeepEqual(tpAccPlan.ID, reply.ID) { - t.Errorf("Expecting : %+v, received: %+v", tpAccPlan.ID, reply.ID) - } else if !reflect.DeepEqual(len(tpAccPlan.ActionPlan), len(reply.ActionPlan)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpAccPlan.ActionPlan), len(reply.ActionPlan)) - } - -} - -func testTPAccPlansRemTPAccPlan(t *testing.T) { - var resp string - if err := tpAccPlansRPC.Call(utils.APIerSv1RemoveTPActionPlan, - &AttrGetTPActionPlan{TPid: "TPAcc", ID: "ID"}, &resp); err != nil { - t.Error(err) - } else if resp != utils.OK { - t.Error("Unexpected reply returned", resp) - } - -} - -func testTPAccPlansGetTPAccPlanAfterRemove(t *testing.T) { - var reply *utils.TPActionPlan - if err := tpAccPlansRPC.Call(utils.APIerSv1GetTPActionPlan, - &AttrGetTPActionPlan{TPid: "TPAcc", ID: "ID"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPAccPlansKillEngine(t *testing.T) { - if err := engine.KillEngine(tpAccPlansDelay); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/tpactiontriggers.go b/apier/v1/tpactiontriggers.go deleted file mode 100644 index 6102e4dd1..000000000 --- a/apier/v1/tpactiontriggers.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "github.com/cgrates/cgrates/utils" -) - -// SetTPActionTriggers creates a new ActionTriggers profile within a tariff plan -func (apierSv1 *APIerSv1) SetTPActionTriggers(attrs *utils.TPActionTriggers, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.SetTPActionTriggers([]*utils.TPActionTriggers{attrs}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -// AttrGetTPActionTriggers used as argument for GetTPActionTriggers -type AttrGetTPActionTriggers struct { - TPid string // Tariff plan id - ID string // ActionTrigger id -} - -// GetTPActionTriggers queries specific ActionTriggers profile on tariff plan -func (apierSv1 *APIerSv1) GetTPActionTriggers(attrs *AttrGetTPActionTriggers, reply *utils.TPActionTriggers) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ats, err := apierSv1.StorDb.GetTPActionTriggers(attrs.TPid, attrs.ID) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = *ats[0] - return nil -} - -// AttrGetTPActionTriggerIds used as argument for GetTPActionTriggerIds and RemoveTPActionTriggers -type AttrGetTPActionTriggerIds struct { - TPid string // Tariff plan id - utils.PaginatorWithSearch -} - -// GetTPActionTriggerIds queries ActionTriggers identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPActionTriggerIds(attrs *AttrGetTPActionTriggerIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPActionTriggers, - utils.TPDistinctIds{utils.TagCfg}, nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// RemoveTPActionTriggers removes specific ActionTriggers on Tariff plan -func (apierSv1 *APIerSv1) RemoveTPActionTriggers(attrs *AttrGetTPActionTriggers, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - err := apierSv1.StorDb.RemTpData(utils.TBLTPActionTriggers, - attrs.TPid, map[string]string{utils.TagCfg: attrs.ID}) - if err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} diff --git a/apier/v1/tpactiontriggers_it_test.go b/apier/v1/tpactiontriggers_it_test.go deleted file mode 100644 index 0cb31b3e1..000000000 --- a/apier/v1/tpactiontriggers_it_test.go +++ /dev/null @@ -1,332 +0,0 @@ -// +build offline - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "net/rpc/jsonrpc" - "path" - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - tpActionTriggerCfgPath string - tpActionTriggerCfg *config.CGRConfig - tpActionTriggerRPC *rpc.Client - tpActionTriggers *utils.TPActionTriggers - tpActionTriggerDelay int - tpActionTriggerConfigDIR string //run tests for specific configuration - -) - -var sTestsTPActionTriggers = []func(t *testing.T){ - testTPActionTriggersInitCfg, - testTPActionTriggersResetStorDb, - testTPActionTriggersStartEngine, - testTPActionTriggersRpcConn, - testTPActionTriggersGetTPActionTriggersBeforeSet, - testTPActionTriggersSetTPActionTriggers, - testTPActionTriggersGetTPActionTriggersAfterSet, - testTPActionTriggersGetTPActionTriggersIds, - testTPActionTriggersUpdateTPActionTriggers, - testTPActionTriggersGetTPActionTriggersAfterUpdate, - testTPActionTriggersRemoveTPActionTriggers, - testTPActionTriggersGetTPActionTriggersAfterRemove, - testTPActionTriggersKillEngine, -} - -//Test start here -func TestTPActionTriggersIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - tpActionTriggerConfigDIR = "tutinternal" - case utils.MetaMySQL: - tpActionTriggerConfigDIR = "tutmysql" - case utils.MetaMongo: - tpActionTriggerConfigDIR = "tutmongo" - case utils.MetaPostgres: - tpActionTriggerConfigDIR = "tutpostgres" - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsTPActionTriggers { - t.Run(tpActionTriggerConfigDIR, stest) - } -} - -func testTPActionTriggersInitCfg(t *testing.T) { - var err error - tpActionTriggerCfgPath = path.Join(*dataDir, "conf", "samples", tpActionTriggerConfigDIR) - tpActionTriggerCfg, err = config.NewCGRConfigFromPath(tpActionTriggerCfgPath) - if err != nil { - t.Error(err) - } - switch tpActionTriggerConfigDIR { - case "tutmongo": // Mongo needs more time to reset db, need to investigate - tpActionTriggerDelay = 2000 - default: - tpActionTriggerDelay = 1000 - } -} - -// Wipe out the cdr database -func testTPActionTriggersResetStorDb(t *testing.T) { - if err := engine.InitStorDb(tpActionTriggerCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testTPActionTriggersStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(tpActionTriggerCfgPath, tpActionTriggerDelay); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testTPActionTriggersRpcConn(t *testing.T) { - var err error - tpActionTriggerRPC, err = jsonrpc.Dial(utils.TCP, tpActionTriggerCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testTPActionTriggersGetTPActionTriggersBeforeSet(t *testing.T) { - var reply *utils.TPActionTriggers - if err := tpActionTriggerRPC.Call(utils.APIerSv1GetTPActionTriggers, - &AttrGetTPActionTriggers{TPid: "TPAct", ID: "ID"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPActionTriggersSetTPActionTriggers(t *testing.T) { - tpActionTriggers = &utils.TPActionTriggers{ - TPid: "TPAct", - ID: "ID", - ActionTriggers: []*utils.TPActionTrigger{ - &utils.TPActionTrigger{ - Id: "STANDARD_TRIGGERS", - UniqueID: "", - ThresholdType: "*min_balance", - ThresholdValue: 2, - Recurrent: false, - MinSleep: "0", - ExpirationDate: "", - ActivationDate: "", - BalanceId: "", - BalanceType: "*monetary", - BalanceDestinationIds: "FS_USERS", - BalanceWeight: "", - BalanceExpirationDate: "", - BalanceTimingTags: "", - BalanceRatingSubject: "", - BalanceCategories: "", - BalanceSharedGroups: "", - BalanceBlocker: "", - BalanceDisabled: "", - ActionsId: "LOG_WARNING", - Weight: 10, - }, - &utils.TPActionTrigger{ - Id: "STANDARD_TRIGGERS", - UniqueID: "", - ThresholdType: "*max_event_counter", - ThresholdValue: 5, - Recurrent: false, - MinSleep: "0", - ExpirationDate: "", - ActivationDate: "", - BalanceId: "", - BalanceType: "*monetary", - BalanceDestinationIds: "FS_USERS", - BalanceWeight: "", - BalanceExpirationDate: "", - BalanceTimingTags: "", - BalanceRatingSubject: "", - BalanceCategories: "", - BalanceSharedGroups: "", - BalanceBlocker: "", - BalanceDisabled: "", - ActionsId: "LOG_WARNING", - Weight: 10, - }, - }, - } - var result string - if err := tpActionTriggerRPC.Call(utils.APIerSv1SetTPActionTriggers, tpActionTriggers, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPActionTriggersGetTPActionTriggersAfterSet(t *testing.T) { - var reply *utils.TPActionTriggers - if err := tpActionTriggerRPC.Call(utils.APIerSv1GetTPActionTriggers, - &AttrGetTPActionTriggers{TPid: "TPAct", ID: "ID"}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpActionTriggers.TPid, reply.TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpActionTriggers.TPid, reply.TPid) - } else if !reflect.DeepEqual(tpActionTriggers.ID, reply.ID) { - t.Errorf("Expecting : %+v, received: %+v", tpActionTriggers.ID, reply.ID) - } else if !reflect.DeepEqual(len(tpActionTriggers.ActionTriggers), len(reply.ActionTriggers)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpActionTriggers.ActionTriggers), len(reply.ActionTriggers)) - } -} - -func testTPActionTriggersGetTPActionTriggersIds(t *testing.T) { - var result []string - expectedTPID := []string{"ID"} - if err := tpActionTriggerRPC.Call(utils.APIerSv1GetTPActionTriggerIds, - &AttrGetTPActionTriggerIds{TPid: "TPAct"}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expectedTPID, result) { - t.Errorf("Expecting: %+v, received: %+v", expectedTPID, result) - } -} - -func testTPActionTriggersUpdateTPActionTriggers(t *testing.T) { - tpActionTriggers.ActionTriggers = []*utils.TPActionTrigger{ - &utils.TPActionTrigger{ - Id: "STANDARD_TRIGGERS", - UniqueID: "", - ThresholdType: "*min_balance", - ThresholdValue: 2, - Recurrent: false, - MinSleep: "0", - ExpirationDate: "", - ActivationDate: "", - BalanceId: "", - BalanceType: "*monetary", - BalanceDestinationIds: "FS_USERS", - BalanceWeight: "", - BalanceExpirationDate: "", - BalanceTimingTags: "", - BalanceRatingSubject: "", - BalanceCategories: "", - BalanceSharedGroups: "", - BalanceBlocker: "", - BalanceDisabled: "", - ActionsId: "LOG_WARNING", - Weight: 10, - }, - &utils.TPActionTrigger{ - Id: "STANDARD_TRIGGERS", - UniqueID: "", - ThresholdType: "*max_event_counter", - ThresholdValue: 5, - Recurrent: false, - MinSleep: "0", - ExpirationDate: "", - ActivationDate: "", - BalanceId: "", - BalanceType: "*monetary", - BalanceDestinationIds: "FS_USERS", - BalanceWeight: "", - BalanceExpirationDate: "", - BalanceTimingTags: "", - BalanceRatingSubject: "", - BalanceCategories: "", - BalanceSharedGroups: "", - BalanceBlocker: "", - BalanceDisabled: "", - ActionsId: "LOG_WARNING", - Weight: 10, - }, - &utils.TPActionTrigger{ - Id: "CDRST1_WARN", - UniqueID: "", - ThresholdType: "*min_asr", - ThresholdValue: 45, - Recurrent: true, - MinSleep: "1m", - ExpirationDate: "", - ActivationDate: "", - BalanceId: "", - BalanceType: "", - BalanceDestinationIds: "", - BalanceWeight: "", - BalanceExpirationDate: "", - BalanceTimingTags: "", - BalanceRatingSubject: "", - BalanceCategories: "", - BalanceSharedGroups: "", - BalanceBlocker: "", - BalanceDisabled: "", - ActionsId: "LOG_WARNING", - Weight: 10, - }, - } - - var result string - if err := tpActionTriggerRPC.Call(utils.APIerSv1SetTPActionTriggers, tpActionTriggers, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } - -} - -func testTPActionTriggersGetTPActionTriggersAfterUpdate(t *testing.T) { - var reply *utils.TPActionTriggers - if err := tpActionTriggerRPC.Call(utils.APIerSv1GetTPActionTriggers, - &AttrGetTPActionTriggers{TPid: "TPAct", ID: "ID"}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpActionTriggers.TPid, reply.TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpActionTriggers.TPid, reply.TPid) - } else if !reflect.DeepEqual(tpActionTriggers.ID, reply.ID) { - t.Errorf("Expecting : %+v, received: %+v", tpActionTriggers.ID, reply.ID) - } else if !reflect.DeepEqual(len(tpActionTriggers.ActionTriggers), len(reply.ActionTriggers)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpActionTriggers.ActionTriggers), len(reply.ActionTriggers)) - } - -} - -func testTPActionTriggersRemoveTPActionTriggers(t *testing.T) { - var resp string - if err := tpActionTriggerRPC.Call(utils.APIerSv1RemoveTPActionTriggers, - &AttrGetTPActionTriggers{TPid: "TPAct", ID: "ID"}, &resp); err != nil { - t.Error(err) - } else if resp != utils.OK { - t.Error("Unexpected reply returned", resp) - } - -} - -func testTPActionTriggersGetTPActionTriggersAfterRemove(t *testing.T) { - var reply *utils.TPActionTriggers - if err := tpActionTriggerRPC.Call(utils.APIerSv1GetTPActionTriggers, - &AttrGetTPActionTriggers{TPid: "TPAct", ID: "ID"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPActionTriggersKillEngine(t *testing.T) { - if err := engine.KillEngine(tpActionTriggerDelay); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/tpdestinationrates.go b/apier/v1/tpdestinationrates.go deleted file mode 100644 index c76ba21a3..000000000 --- a/apier/v1/tpdestinationrates.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -// This file deals with tp_destination_rates management over APIs - -import ( - "github.com/cgrates/cgrates/utils" -) - -// SetTPDestinationRate creates a new DestinationRate profile within a tariff plan -func (apierSv1 *APIerSv1) SetTPDestinationRate(attrs *utils.TPDestinationRate, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID, utils.DestinationRates}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.SetTPDestinationRates([]*utils.TPDestinationRate{attrs}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -type AttrGetTPDestinationRate struct { - TPid string // Tariff plan id - ID string // Rate id - utils.Paginator -} - -// GetTPDestinationRate queries specific DestinationRate profile on tariff plan -func (apierSv1 *APIerSv1) GetTPDestinationRate(attrs *AttrGetTPDestinationRate, reply *utils.TPDestinationRate) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - drs, err := apierSv1.StorDb.GetTPDestinationRates(attrs.TPid, attrs.ID, &attrs.Paginator) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = *drs[0] - return nil -} - -type AttrTPDestinationRateIds struct { - TPid string // Tariff plan id - utils.PaginatorWithSearch -} - -// GetTPDestinationRateIds queries DestinationRate identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPDestinationRateIds(attrs *AttrGetTPRateIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPDestinationRates, - utils.TPDistinctIds{utils.TagCfg}, nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// RemoveTPDestinationRate removes specific DestinationRate on Tariff plan -func (apierSv1 *APIerSv1) RemoveTPDestinationRate(attrs *AttrGetTPDestinationRate, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.RemTpData(utils.TBLTPDestinationRates, attrs.TPid, map[string]string{utils.TagCfg: attrs.ID}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} diff --git a/apier/v1/tpdestinationrates_it_test.go b/apier/v1/tpdestinationrates_it_test.go deleted file mode 100644 index d64045789..000000000 --- a/apier/v1/tpdestinationrates_it_test.go +++ /dev/null @@ -1,202 +0,0 @@ -// +build offline - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "net/rpc/jsonrpc" - "path" - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - tpDstRateCfgPath string - tpDstRateCfg *config.CGRConfig - tpDstRateRPC *rpc.Client - tpDstRate *utils.TPDestinationRate - tpDstRateDelay int - tpDstRateConfigDIR string //run tests for specific configuration -) - -var sTestsTPDstRates = []func(t *testing.T){ - testTPDstRateInitCfg, - testTPDstRateResetStorDb, - testTPDstRateStartEngine, - testTPDstRateRpcConn, - testTPDstRateGetTPDstRateBeforeSet, - testTPDstRateSetTPDstRate, - testTPDstRateGetTPDstRateAfterSet, - testTPDstRateGetTPDstRateIds, - testTPDstRateUpdateTPDstRate, - testTPDstRateGetTPDstRateAfterUpdate, - testTPDstRateRemTPDstRate, - testTPDstRateGetTPDstRateAfterRemove, - testTPDstRateKillEngine, -} - -//Test start here -func TestTPDstRateIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - tpDstRateConfigDIR = "tutinternal" - case utils.MetaMySQL: - tpDstRateConfigDIR = "tutmysql" - case utils.MetaMongo: - tpDstRateConfigDIR = "tutmongo" - case utils.MetaPostgres: - tpDstRateConfigDIR = "tutpostgres" - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsTPDstRates { - t.Run(tpDstRateConfigDIR, stest) - } -} - -func testTPDstRateInitCfg(t *testing.T) { - var err error - tpDstRateCfgPath = path.Join(*dataDir, "conf", "samples", tpDstRateConfigDIR) - tpDstRateCfg, err = config.NewCGRConfigFromPath(tpDstRateCfgPath) - if err != nil { - t.Error(err) - } - tpDstRateDelay = 1000 -} - -// Wipe out the cdr database -func testTPDstRateResetStorDb(t *testing.T) { - if err := engine.InitStorDb(tpDstRateCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testTPDstRateStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(tpDstRateCfgPath, tpDstRateDelay); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testTPDstRateRpcConn(t *testing.T) { - var err error - tpDstRateRPC, err = jsonrpc.Dial(utils.TCP, tpDstRateCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testTPDstRateGetTPDstRateBeforeSet(t *testing.T) { - var reply *utils.TPDestinationRate - if err := tpDstRateRPC.Call(utils.APIerSv1GetTPDestinationRate, - &AttrGetTPDestinationRate{TPid: "TP1", ID: "DR_FREESWITCH_USERS"}, &reply); err == nil || - err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } - -} - -func testTPDstRateSetTPDstRate(t *testing.T) { - tpDstRate = &utils.TPDestinationRate{ - TPid: "TP1", - ID: "DR_FREESWITCH_USERS", - DestinationRates: []*utils.DestinationRate{ - &utils.DestinationRate{ - DestinationId: "FS_USERS", - RateId: "RT_FS_USERS", - RoundingMethod: "*up", - RoundingDecimals: 2}, - }, - } - var result string - if err := tpDstRateRPC.Call(utils.APIerSv1SetTPDestinationRate, tpDstRate, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPDstRateGetTPDstRateAfterSet(t *testing.T) { - var reply *utils.TPDestinationRate - if err := tpDstRateRPC.Call(utils.APIerSv1GetTPDestinationRate, - &AttrGetTPDestinationRate{TPid: "TP1", ID: "DR_FREESWITCH_USERS"}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpDstRate, reply) { - t.Errorf("Expecting : %+v, received: %+v", tpDstRate, reply) - } -} - -func testTPDstRateGetTPDstRateIds(t *testing.T) { - var result []string - expectedTPID := []string{"DR_FREESWITCH_USERS"} - if err := tpDstRateRPC.Call(utils.APIerSv1GetTPDestinationRateIds, - &AttrTPDestinationRateIds{TPid: "TP1"}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expectedTPID, result) { - t.Errorf("Expecting: %+v, received: %+v", expectedTPID, result) - } - -} - -func testTPDstRateUpdateTPDstRate(t *testing.T) { - -} - -func testTPDstRateGetTPDstRateAfterUpdate(t *testing.T) { - var reply *utils.TPDestinationRate - if err := tpDstRateRPC.Call(utils.APIerSv1GetTPDestinationRate, - &AttrGetTPDestinationRate{TPid: "TP1", ID: "DR_FREESWITCH_USERS"}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpDstRate, reply) { - t.Errorf("Expecting : %+v, received: %+v", tpDstRate, reply) - } -} - -func testTPDstRateRemTPDstRate(t *testing.T) { - var resp string - if err := tpDstRateRPC.Call(utils.APIerSv1RemoveTPDestinationRate, - &AttrGetTPDestinationRate{TPid: "TP1", ID: "DR_FREESWITCH_USERS"}, &resp); err != nil { - t.Error(err) - } else if resp != utils.OK { - t.Error("Unexpected reply returned", resp) - } - -} - -func testTPDstRateGetTPDstRateAfterRemove(t *testing.T) { - var reply *utils.TPDestinationRate - if err := tpDstRateRPC.Call(utils.APIerSv1GetTPDestinationRate, - &AttrGetTPDestinationRate{TPid: "TP1", ID: "DR_FREESWITCH_USERS"}, &reply); err == nil || - err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPDstRateKillEngine(t *testing.T) { - if err := engine.KillEngine(tpDstRateDelay); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/tprates.go b/apier/v1/tprates.go deleted file mode 100644 index 7c8ea93d0..000000000 --- a/apier/v1/tprates.go +++ /dev/null @@ -1,92 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -// This file deals with tp_rates management over APIs - -import ( - "github.com/cgrates/cgrates/utils" -) - -// SetTPRate creates a new rate within a tariff plan -func (apierSv1 *APIerSv1) SetTPRate(attrs *utils.TPRateRALs, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID, utils.RateSlots}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.SetTPRates([]*utils.TPRateRALs{attrs}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -type AttrGetTPRate struct { - TPid string // Tariff plan id - ID string // Rate id -} - -// GetTPRate queries specific Rate on tariff plan -func (apierSv1 *APIerSv1) GetTPRate(attrs *AttrGetTPRate, reply *utils.TPRateRALs) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - rs, err := apierSv1.StorDb.GetTPRates(attrs.TPid, attrs.ID) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = *rs[0] - return nil -} - -type AttrGetTPRateIds struct { - TPid string // Tariff plan id - utils.PaginatorWithSearch -} - -// GetTPRateIds queries rate identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPRateIds(attrs *AttrGetTPRateIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPRates, - utils.TPDistinctIds{utils.TagCfg}, nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// RemoveTPRate removes specific Rate on Tariff plan -func (apierSv1 *APIerSv1) RemoveTPRate(attrs *AttrGetTPRate, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.RemTpData(utils.TBLTPRates, attrs.TPid, map[string]string{utils.TagCfg: attrs.ID}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} diff --git a/apier/v1/tprates_it_test.go b/apier/v1/tprates_it_test.go deleted file mode 100644 index 544e026da..000000000 --- a/apier/v1/tprates_it_test.go +++ /dev/null @@ -1,238 +0,0 @@ -// +build offline - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "net/rpc/jsonrpc" - "path" - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - tpRateCfgPath string - tpRateCfg *config.CGRConfig - tpRateRPC *rpc.Client - tpRate *utils.TPRateRALs - tpRateDelay int - tpRateConfigDIR string //run tests for specific configuration -) - -var sTestsTPRates = []func(t *testing.T){ - testTPRatesInitCfg, - testTPRatesResetStorDb, - testTPRatesStartEngine, - testTPRatesRpcConn, - testTPRatesGetTPRateforeSet, - testTPRatesSetTPRate, - testTPRatesGetTPRateAfterSet, - testTPRatesGetTPRateIds, - testTPRatesUpdateTPRate, - testTPRatesGetTPRateAfterUpdate, - testTPRatesRemoveTPRate, - testTPRatesGetTPRateAfterRemove, - testTPRatesKillEngine, -} - -//Test start here -func TestTPRatesIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - tpRateConfigDIR = "tutinternal" - case utils.MetaMySQL: - tpRateConfigDIR = "tutmysql" - case utils.MetaMongo: - tpRateConfigDIR = "tutmongo" - case utils.MetaPostgres: - tpRateConfigDIR = "tutpostgres" - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsTPRates { - t.Run(tpRateConfigDIR, stest) - } -} - -func testTPRatesInitCfg(t *testing.T) { - var err error - tpRateCfgPath = path.Join(*dataDir, "conf", "samples", tpRateConfigDIR) - tpRateCfg, err = config.NewCGRConfigFromPath(tpRateCfgPath) - if err != nil { - t.Error(err) - } - switch tpRateConfigDIR { - case "tutmongo": // Mongo needs more time to reset db, need to investigate - tpRateDelay = 2000 - default: - tpRateDelay = 1000 - } -} - -// Wipe out the cdr database -func testTPRatesResetStorDb(t *testing.T) { - if err := engine.InitStorDb(tpRateCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testTPRatesStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(tpRateCfgPath, tpRateDelay); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testTPRatesRpcConn(t *testing.T) { - var err error - tpRateRPC, err = jsonrpc.Dial(utils.TCP, tpRateCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testTPRatesGetTPRateforeSet(t *testing.T) { - var reply *utils.TPRateRALs - if err := tpRateRPC.Call(utils.APIerSv1GetTPRate, - &AttrGetTPRate{TPid: "TPidTpRate", ID: "RT_FS_USERS"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPRatesSetTPRate(t *testing.T) { - tpRate = &utils.TPRateRALs{ - TPid: "TPidTpRate", - ID: "RT_FS_USERS", - RateSlots: []*utils.RateSlot{ - &utils.RateSlot{ - ConnectFee: 12, - Rate: 3, - RateUnit: "6s", - RateIncrement: "6s", - GroupIntervalStart: "0s", - }, - &utils.RateSlot{ - ConnectFee: 12, - Rate: 3, - RateUnit: "4s", - RateIncrement: "6s", - GroupIntervalStart: "1s", - }, - }, - } - var result string - if err := tpRateRPC.Call(utils.APIerSv1SetTPRate, tpRate, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPRatesGetTPRateAfterSet(t *testing.T) { - var reply *utils.TPRateRALs - if err := tpRateRPC.Call(utils.APIerSv1GetTPRate, &AttrGetTPRate{TPid: "TPidTpRate", ID: tpRate.ID}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpRate, reply) { - t.Errorf("Expecting : %+v, received: %+v", tpRate, reply) - } -} - -func testTPRatesGetTPRateIds(t *testing.T) { - var result []string - expectedTPID := []string{"RT_FS_USERS"} - if err := tpRateRPC.Call(utils.APIerSv1GetTPRateIds, &AttrGetTPRateIds{TPid: "TPidTpRate"}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expectedTPID, result) { - t.Errorf("Expecting: %+v, received: %+v", expectedTPID, result) - } -} - -func testTPRatesUpdateTPRate(t *testing.T) { - var result string - tpRate.RateSlots = []*utils.RateSlot{ - &utils.RateSlot{ - ConnectFee: 12, - Rate: 3, - RateUnit: "6s", - RateIncrement: "6s", - GroupIntervalStart: "0s", - }, - &utils.RateSlot{ - ConnectFee: 12, - Rate: 10, - RateUnit: "4s", - RateIncrement: "6s", - GroupIntervalStart: "1s", - }, - &utils.RateSlot{ - ConnectFee: 5, - Rate: 10, - RateUnit: "4s", - RateIncrement: "6s", - GroupIntervalStart: "3s", - }, - } - if err := tpRateRPC.Call(utils.APIerSv1SetTPRate, tpRate, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPRatesGetTPRateAfterUpdate(t *testing.T) { - var reply *utils.TPRateRALs - if err := tpRateRPC.Call(utils.APIerSv1GetTPRate, - &AttrGetTPRate{TPid: "TPidTpRate", ID: tpRate.ID}, &reply); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpRate, reply) { - t.Errorf("Expecting : %+v, received: %+v", tpRate, reply) - } - -} - -func testTPRatesRemoveTPRate(t *testing.T) { - var resp string - if err := tpRateRPC.Call(utils.APIerSv1RemoveTPRate, - &AttrGetTPRate{TPid: "TPidTpRate", ID: "RT_FS_USERS"}, &resp); err != nil { - t.Error(err) - } else if resp != utils.OK { - t.Error("Unexpected reply returned", resp) - } -} - -func testTPRatesGetTPRateAfterRemove(t *testing.T) { - var reply *utils.TPRateRALs - if err := tpRateRPC.Call(utils.APIerSv1GetTPRate, - &AttrGetTPRate{TPid: "TPidTpRate", ID: "RT_FS_USERS"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPRatesKillEngine(t *testing.T) { - if err := engine.KillEngine(tpRateDelay); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/tpratingplans.go b/apier/v1/tpratingplans.go deleted file mode 100644 index d27c41075..000000000 --- a/apier/v1/tpratingplans.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -// This file deals with tp_destrates_timing management over APIs - -import ( - "github.com/cgrates/cgrates/utils" -) - -// SetTPRatingPlan creates a new DestinationRateTiming profile within a tariff plan -func (apierSv1 *APIerSv1) SetTPRatingPlan(attrs *utils.TPRatingPlan, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID, utils.RatingPlanBindings}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.SetTPRatingPlans([]*utils.TPRatingPlan{attrs}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -type AttrGetTPRatingPlan struct { - TPid string // Tariff plan id - ID string // Rate id - utils.Paginator -} - -// GetTPRatingPlan queries specific RatingPlan profile on tariff plan -func (apierSv1 *APIerSv1) GetTPRatingPlan(attrs *AttrGetTPRatingPlan, reply *utils.TPRatingPlan) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - rps, err := apierSv1.StorDb.GetTPRatingPlans(attrs.TPid, attrs.ID, &attrs.Paginator) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = *rps[0] - return nil -} - -type AttrGetTPRatingPlanIds struct { - TPid string // Tariff plan id - utils.PaginatorWithSearch -} - -// GetTPRatingPlanIds queries RatingPlan identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPRatingPlanIds(attrs *AttrGetTPRatingPlanIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPRatingPlans, - utils.TPDistinctIds{utils.TagCfg}, nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// RemoveTPRatingPlan removes specific RatingPlan on Tariff plan -func (apierSv1 *APIerSv1) RemoveTPRatingPlan(attrs *AttrGetTPRatingPlan, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.RemTpData(utils.TBLTPRatingPlans, attrs.TPid, map[string]string{utils.TagCfg: attrs.ID}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} diff --git a/apier/v1/tpratingplans_it_test.go b/apier/v1/tpratingplans_it_test.go deleted file mode 100644 index 981be4bae..000000000 --- a/apier/v1/tpratingplans_it_test.go +++ /dev/null @@ -1,237 +0,0 @@ -// +build offline - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "net/rpc/jsonrpc" - "path" - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - tpRatingPlanCfgPath string - tpRatingPlanCfg *config.CGRConfig - tpRatingPlanRPC *rpc.Client - tpRatingPlan *utils.TPRatingPlan - tpRatingPlanDelay int - tpRatingPlanConfigDIR string //run tests for specific configuration -) - -var sTestsTPRatingPlans = []func(t *testing.T){ - testTPRatingPlansInitCfg, - testTPRatingPlansResetStorDb, - testTPRatingPlansStartEngine, - testTPRatingPlansRpcConn, - testTPRatingPlansGetTPRatingPlanBeforeSet, - testTPRatingPlansSetTPRatingPlan, - testTPRatingPlansGetTPRatingPlanAfterSet, - testTPRatingPlansGetTPRatingPlanIds, - testTPRatingPlansUpdateTPRatingPlan, - testTPRatingPlansGetTPRatingPlanAfterUpdate, - testTPRatingPlansRemoveTPRatingPlan, - testTPRatingPlansGetTPRatingPlanAfterRemove, - testTPRatingPlansKillEngine, -} - -//Test start here -func TestTPRatingPlansIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - tpRatingPlanConfigDIR = "tutinternal" - case utils.MetaMySQL: - tpRatingPlanConfigDIR = "tutmysql" - case utils.MetaMongo: - tpRatingPlanConfigDIR = "tutmongo" - case utils.MetaPostgres: - tpRatingPlanConfigDIR = "tutpostgres" - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsTPRatingPlans { - t.Run(tpRatingPlanConfigDIR, stest) - } -} - -func testTPRatingPlansInitCfg(t *testing.T) { - var err error - tpRatingPlanCfgPath = path.Join(*dataDir, "conf", "samples", tpRatingPlanConfigDIR) - tpRatingPlanCfg, err = config.NewCGRConfigFromPath(tpRatingPlanCfgPath) - if err != nil { - t.Error(err) - } - switch tpRatingPlanConfigDIR { - case "tutmongo": // Mongo needs more time to reset db, need to investigate - tpRatingPlanDelay = 2000 - default: - tpRatingPlanDelay = 1000 - } -} - -// Wipe out the cdr database -func testTPRatingPlansResetStorDb(t *testing.T) { - if err := engine.InitStorDb(tpRatingPlanCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testTPRatingPlansStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(tpRatingPlanCfgPath, tpRatingPlanDelay); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testTPRatingPlansRpcConn(t *testing.T) { - var err error - tpRatingPlanRPC, err = jsonrpc.Dial(utils.TCP, tpRatingPlanCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testTPRatingPlansGetTPRatingPlanBeforeSet(t *testing.T) { - var reply *utils.TPRatingPlan - if err := tpRatingPlanRPC.Call(utils.APIerSv1GetTPRatingPlan, - &AttrGetTPRatingPlan{TPid: "TPRP1", ID: "Plan1"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPRatingPlansSetTPRatingPlan(t *testing.T) { - tpRatingPlan = &utils.TPRatingPlan{ - TPid: "TPRP1", - ID: "Plan1", - RatingPlanBindings: []*utils.TPRatingPlanBinding{ - &utils.TPRatingPlanBinding{ - DestinationRatesId: "RateId", - TimingId: "TimingID", - Weight: 12, - }, - &utils.TPRatingPlanBinding{ - DestinationRatesId: "DR_FREESWITCH_USERS", - TimingId: "ALWAYS", - Weight: 10, - }, - }, - } - var result string - if err := tpRatingPlanRPC.Call(utils.APIerSv1SetTPRatingPlan, tpRatingPlan, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPRatingPlansGetTPRatingPlanAfterSet(t *testing.T) { - var respond *utils.TPRatingPlan - if err := tpRatingPlanRPC.Call(utils.APIerSv1GetTPRatingPlan, - &AttrGetTPRatingPlan{TPid: "TPRP1", ID: "Plan1"}, &respond); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpRatingPlan.TPid, respond.TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingPlan.TPid, respond.TPid) - } else if !reflect.DeepEqual(tpRatingPlan.ID, respond.ID) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingPlan, respond) - } else if !reflect.DeepEqual(len(tpRatingPlan.RatingPlanBindings), len(respond.RatingPlanBindings)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpRatingPlan.RatingPlanBindings), len(respond.RatingPlanBindings)) - } -} - -func testTPRatingPlansGetTPRatingPlanIds(t *testing.T) { - var result []string - expected := []string{"Plan1"} - if err := tpRatingPlanRPC.Call(utils.APIerSv1GetTPRatingPlanIds, - &AttrGetTPRatingPlanIds{TPid: tpRatingPlan.TPid}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, result) { - t.Errorf("Expecting: %+v, received: %+v", expected, result) - } -} - -func testTPRatingPlansUpdateTPRatingPlan(t *testing.T) { - tpRatingPlan.RatingPlanBindings = []*utils.TPRatingPlanBinding{ - &utils.TPRatingPlanBinding{ - DestinationRatesId: "RateId", - TimingId: "TimingID", - Weight: 12, - }, - &utils.TPRatingPlanBinding{ - DestinationRatesId: "DR_FREESWITCH_USERS", - TimingId: "ALWAYS", - Weight: 10, - }, - &utils.TPRatingPlanBinding{ - DestinationRatesId: "RateID2", - TimingId: "ALWAYS", - Weight: 11, - }, - } - var result string - if err := tpRatingPlanRPC.Call(utils.APIerSv1SetTPRatingPlan, tpRatingPlan, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPRatingPlansGetTPRatingPlanAfterUpdate(t *testing.T) { - var respond *utils.TPRatingPlan - if err := tpRatingPlanRPC.Call(utils.APIerSv1GetTPRatingPlan, - &AttrGetTPRatingPlan{TPid: "TPRP1", ID: "Plan1"}, &respond); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpRatingPlan.TPid, respond.TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingPlan.TPid, respond.TPid) - } else if !reflect.DeepEqual(tpRatingPlan.ID, respond.ID) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingPlan, respond) - } else if !reflect.DeepEqual(len(tpRatingPlan.RatingPlanBindings), len(respond.RatingPlanBindings)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpRatingPlan.RatingPlanBindings), len(respond.RatingPlanBindings)) - } -} - -func testTPRatingPlansRemoveTPRatingPlan(t *testing.T) { - var resp string - if err := tpRatingPlanRPC.Call(utils.APIerSv1RemoveTPRatingPlan, - &AttrGetTPRatingPlan{TPid: "TPRP1", ID: "Plan1"}, &resp); err != nil { - t.Error(err) - } else if resp != utils.OK { - t.Error("Unexpected reply returned", resp) - } -} - -func testTPRatingPlansGetTPRatingPlanAfterRemove(t *testing.T) { - var respond *utils.TPRatingPlan - if err := tpRatingPlanRPC.Call(utils.APIerSv1GetTPRatingPlan, - &AttrGetTPRatingPlan{TPid: "TPRP1", ID: "Plan1"}, &respond); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPRatingPlansKillEngine(t *testing.T) { - if err := engine.KillEngine(tpRatingPlanDelay); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/tpratingprofiles.go b/apier/v1/tpratingprofiles.go deleted file mode 100644 index d6baa1881..000000000 --- a/apier/v1/tpratingprofiles.go +++ /dev/null @@ -1,161 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -// This file deals with tp_rate_profiles management over APIs - -import ( - "github.com/cgrates/cgrates/utils" -) - -// SetTPRatingProfile creates a new RatingProfile within a tariff plan -func (apierSv1 *APIerSv1) SetTPRatingProfile(attrs *utils.TPRatingProfile, reply *string) error { - if missing := utils.MissingStructFields(attrs, - []string{utils.TPid, utils.LoadId, utils.Category, utils.Subject, utils.RatingPlanActivations}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if attrs.Tenant == utils.EmptyString { - attrs.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - if err := apierSv1.StorDb.SetTPRatingProfiles([]*utils.TPRatingProfile{attrs}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -// GetTPRatingProfilesByLoadID queries specific RatingProfile on tariff plan -func (apierSv1 *APIerSv1) GetTPRatingProfilesByLoadID(attrs *utils.TPRatingProfile, reply *[]*utils.TPRatingProfile) error { - mndtryFlds := []string{utils.TPid, utils.LoadId} - if len(attrs.Subject) != 0 { // If Subject provided as filter, make all related fields mandatory - mndtryFlds = append(mndtryFlds, utils.Category, utils.Subject) - } - if missing := utils.MissingStructFields(attrs, mndtryFlds); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - if attrs.Tenant == utils.EmptyString { - attrs.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - rps, err := apierSv1.StorDb.GetTPRatingProfiles(attrs) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = rps - return nil -} - -// GetTPRatingProfileLoadIds queries RatingProfile identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPRatingProfileLoadIds(attrs *utils.AttrTPRatingProfileIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - if attrs.Tenant == utils.EmptyString { - attrs.Tenant = apierSv1.Config.GeneralCfg().DefaultTenant - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPRatingProfiles, - utils.TPDistinctIds{utils.Loadid}, map[string]string{ - utils.TenantCfg: attrs.Tenant, - utils.CategoryLowerCase: attrs.Category, - utils.SubjectLowerCase: attrs.Subject, - }, new(utils.PaginatorWithSearch)) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// AttrGetTPRatingProfile arguments used by GetTPRatingProfile and RemoveTPRatingProfile -type AttrGetTPRatingProfile struct { - TPid string // Tariff plan id - RatingProfileID string // RatingProfile id -} - -// GetTPRatingProfile queries specific RatingProfile on tariff plan -func (apierSv1 *APIerSv1) GetTPRatingProfile(attrs *AttrGetTPRatingProfile, reply *utils.TPRatingProfile) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.RatingProfileID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - tmpRpf := &utils.TPRatingProfile{TPid: attrs.TPid} - if err := tmpRpf.SetRatingProfileID(attrs.RatingProfileID); err != nil { - return err - } - rpfs, err := apierSv1.StorDb.GetTPRatingProfiles(tmpRpf) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = *rpfs[0] - return nil -} - -// AttrGetTPRatingProfileIds arguments used by GetTPRatingProfileIds -type AttrGetTPRatingProfileIds struct { - TPid string // Tariff plan id - utils.PaginatorWithSearch -} - -// GetTPRatingProfileIds queries RatingProfiles identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPRatingProfileIds(attrs *AttrGetTPRatingProfileIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPRatingProfiles, - utils.TPDistinctIds{utils.Loadid, utils.TenantCfg, utils.CategoryLowerCase, utils.SubjectLowerCase}, - nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// RemoveTPRatingProfile removes specific RatingProfiles on Tariff plan -func (apierSv1 *APIerSv1) RemoveTPRatingProfile(attrs *AttrGetTPRatingProfile, reply *string) (err error) { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.RatingProfileID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - tmpRpf := new(utils.TPRatingProfile) - if err = tmpRpf.SetRatingProfileID(attrs.RatingProfileID); err != nil { - return - } - err = apierSv1.StorDb.RemTpData(utils.TBLTPRatingProfiles, - attrs.TPid, map[string]string{ - utils.Loadid: tmpRpf.LoadId, - utils.TenantCfg: tmpRpf.Tenant, - utils.CategoryLowerCase: tmpRpf.Category, - utils.SubjectLowerCase: tmpRpf.Subject, - }) - if err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return -} diff --git a/apier/v1/tpratingprofiles_it_test.go b/apier/v1/tpratingprofiles_it_test.go deleted file mode 100644 index 3654aeaf3..000000000 --- a/apier/v1/tpratingprofiles_it_test.go +++ /dev/null @@ -1,287 +0,0 @@ -// +build offline - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "net/rpc/jsonrpc" - "path" - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - tpRatingProfileCfgPath string - tpRatingProfileCfg *config.CGRConfig - tpRatingProfileRPC *rpc.Client - tpRatingProfile *utils.TPRatingProfile - tpRatingProfileDelay int - tpRatingProfileConfigDIR string //run tests for specific configuration - tpRatingProfileID = "RPrf:Tenant1:Category:Subject" -) - -var sTestsTPRatingProfiles = []func(t *testing.T){ - testTPRatingProfilesInitCfg, - testTPRatingProfilesResetStorDb, - testTPRatingProfilesStartEngine, - testTPRatingProfilesRpcConn, - testTPRatingProfilesGetTPRatingProfileBeforeSet, - testTPRatingProfilesSetTPRatingProfile, - testTPRatingProfilesGetTPRatingProfileAfterSet, - testTPRatingProfilesGetTPRatingProfileLoadIds, - testTPRatingProfilesGetTPRatingProfilesByLoadID, - testTPRatingProfilesUpdateTPRatingProfile, - testTPRatingProfilesGetTPRatingProfileAfterUpdate, - testTPRatingProfilesGetTPRatingProfileIds, - testTPRatingProfilesRemoveTPRatingProfile, - testTPRatingProfilesGetTPRatingProfileAfterRemove, - testTPRatingProfilesKillEngine, -} - -//Test start here -func TestTPRatingProfilesIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - tpRatingProfileConfigDIR = "tutinternal" - case utils.MetaMySQL: - tpRatingProfileConfigDIR = "tutmysql" - case utils.MetaMongo: - tpRatingProfileConfigDIR = "tutmongo" - case utils.MetaPostgres: - tpRatingProfileConfigDIR = "tutpostgres" - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsTPRatingProfiles { - t.Run(tpRatingProfileConfigDIR, stest) - } -} - -func testTPRatingProfilesInitCfg(t *testing.T) { - var err error - tpRatingProfileCfgPath = path.Join(*dataDir, "conf", "samples", tpRatingProfileConfigDIR) - tpRatingProfileCfg, err = config.NewCGRConfigFromPath(tpRatingProfileCfgPath) - if err != nil { - t.Error(err) - } - switch tpRatingProfileConfigDIR { - case "tutmongo": // Mongo needs more time to reset db, need to investigate - tpRatingProfileDelay = 2000 - default: - tpRatingProfileDelay = 1000 - } -} - -// Wipe out the cdr database -func testTPRatingProfilesResetStorDb(t *testing.T) { - if err := engine.InitStorDb(tpRatingProfileCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testTPRatingProfilesStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(tpRatingProfileCfgPath, tpRatingProfileDelay); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testTPRatingProfilesRpcConn(t *testing.T) { - var err error - tpRatingProfileRPC, err = jsonrpc.Dial(utils.TCP, tpRatingProfileCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testTPRatingProfilesGetTPRatingProfileBeforeSet(t *testing.T) { - var reply *utils.TPRatingProfile - if err := tpRatingProfileRPC.Call(utils.APIerSv1GetTPRatingProfile, - &AttrGetTPRatingProfile{TPid: "TPRProf1", RatingProfileID: tpRatingProfileID}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPRatingProfilesSetTPRatingProfile(t *testing.T) { - tpRatingProfile = &utils.TPRatingProfile{ - TPid: "TPRProf1", - LoadId: "RPrf", - Tenant: "Tenant1", - Category: "Category", - Subject: "Subject", - RatingPlanActivations: []*utils.TPRatingActivation{ - &utils.TPRatingActivation{ - ActivationTime: "2014-07-29T15:00:00Z", - RatingPlanId: "PlanOne", - FallbackSubjects: "FallBack", - }, - &utils.TPRatingActivation{ - ActivationTime: "2015-07-29T10:00:00Z", - RatingPlanId: "PlanTwo", - FallbackSubjects: "FallOut", - }, - }, - } - var result string - if err := tpRatingProfileRPC.Call(utils.APIerSv1SetTPRatingProfile, tpRatingProfile, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPRatingProfilesGetTPRatingProfileAfterSet(t *testing.T) { - var respond *utils.TPRatingProfile - if err := tpRatingProfileRPC.Call(utils.APIerSv1GetTPRatingProfile, - &AttrGetTPRatingProfile{TPid: "TPRProf1", RatingProfileID: tpRatingProfileID}, &respond); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpRatingProfile.TPid, respond.TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.TPid, respond.TPid) - } else if !reflect.DeepEqual(tpRatingProfile.LoadId, respond.LoadId) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.LoadId, respond.LoadId) - } else if !reflect.DeepEqual(tpRatingProfile.Tenant, respond.Tenant) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Tenant, respond.Tenant) - } else if !reflect.DeepEqual(tpRatingProfile.Category, respond.Category) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Category, respond.Category) - } else if !reflect.DeepEqual(tpRatingProfile.Subject, respond.Subject) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Subject, respond.Subject) - } else if !reflect.DeepEqual(len(tpRatingProfile.RatingPlanActivations), len(respond.RatingPlanActivations)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpRatingProfile.RatingPlanActivations), len(respond.RatingPlanActivations)) - } -} - -func testTPRatingProfilesGetTPRatingProfileLoadIds(t *testing.T) { - var result []string - expected := []string{"RPrf"} - if err := tpRatingProfileRPC.Call(utils.APIerSv1GetTPRatingProfileLoadIds, - &utils.AttrTPRatingProfileIds{TPid: tpRatingProfile.TPid, Tenant: tpRatingProfile.Tenant, - Category: tpRatingProfile.Category, Subject: tpRatingProfile.Subject}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, result) { - t.Errorf("Expecting: %+v, received: %+v", expected, result) - } -} - -func testTPRatingProfilesGetTPRatingProfilesByLoadID(t *testing.T) { - var respond *[]*utils.TPRatingProfile - if err := tpRatingProfileRPC.Call(utils.APIerSv1GetTPRatingProfilesByLoadID, - &utils.TPRatingProfile{TPid: "TPRProf1", LoadId: "RPrf", Tenant: "Tenant1"}, &respond); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpRatingProfile.TPid, (*respond)[0].TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.TPid, (*respond)[0].TPid) - } else if !reflect.DeepEqual(tpRatingProfile.LoadId, (*respond)[0].LoadId) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.LoadId, (*respond)[0].LoadId) - } else if !reflect.DeepEqual(tpRatingProfile.Tenant, (*respond)[0].Tenant) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Tenant, (*respond)[0].Tenant) - } else if !reflect.DeepEqual(tpRatingProfile.Category, (*respond)[0].Category) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Category, (*respond)[0].Category) - } else if !reflect.DeepEqual(tpRatingProfile.Subject, (*respond)[0].Subject) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Subject, (*respond)[0].Subject) - } else if !reflect.DeepEqual(len(tpRatingProfile.RatingPlanActivations), len((*respond)[0].RatingPlanActivations)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpRatingProfile.RatingPlanActivations), len((*respond)[0].RatingPlanActivations)) - } -} - -func testTPRatingProfilesUpdateTPRatingProfile(t *testing.T) { - var result string - tpRatingProfile.RatingPlanActivations = []*utils.TPRatingActivation{ - &utils.TPRatingActivation{ - ActivationTime: "2014-07-29T15:00:00Z", - RatingPlanId: "PlanOne", - FallbackSubjects: "FallBack", - }, - &utils.TPRatingActivation{ - ActivationTime: "2015-07-29T10:00:00Z", - RatingPlanId: "PlanTwo", - FallbackSubjects: "FallOut", - }, - &utils.TPRatingActivation{ - ActivationTime: "2017-07-29T10:00:00Z", - RatingPlanId: "BackupPlan", - FallbackSubjects: "Retreat", - }, - } - if err := tpRatingProfileRPC.Call(utils.APIerSv1SetTPRatingProfile, tpRatingProfile, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPRatingProfilesGetTPRatingProfileAfterUpdate(t *testing.T) { - var respond *utils.TPRatingProfile - if err := tpRatingProfileRPC.Call(utils.APIerSv1GetTPRatingProfile, - &AttrGetTPRatingProfile{TPid: "TPRProf1", RatingProfileID: tpRatingProfileID}, &respond); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpRatingProfile.TPid, respond.TPid) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.TPid, respond.TPid) - } else if !reflect.DeepEqual(tpRatingProfile.LoadId, respond.LoadId) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.LoadId, respond.LoadId) - } else if !reflect.DeepEqual(tpRatingProfile.Tenant, respond.Tenant) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Tenant, respond.Tenant) - } else if !reflect.DeepEqual(tpRatingProfile.Category, respond.Category) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Category, respond.Category) - } else if !reflect.DeepEqual(tpRatingProfile.Subject, respond.Subject) { - t.Errorf("Expecting : %+v, received: %+v", tpRatingProfile.Subject, respond.Subject) - } else if !reflect.DeepEqual(len(tpRatingProfile.RatingPlanActivations), len(respond.RatingPlanActivations)) { - t.Errorf("Expecting : %+v, received: %+v", len(tpRatingProfile.RatingPlanActivations), len(respond.RatingPlanActivations)) - } -} - -func testTPRatingProfilesGetTPRatingProfileIds(t *testing.T) { - var respond []string - expected := []string{"RPrf:Tenant1:Category:Subject"} - if err := tpRatingProfileRPC.Call(utils.APIerSv1GetTPRatingProfileIds, - &AttrGetTPRatingProfileIds{TPid: "TPRProf1"}, &respond); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, respond) { - t.Errorf("Expecting : %+v, received: %+v", expected, respond) - } -} - -func testTPRatingProfilesRemoveTPRatingProfile(t *testing.T) { - var resp string - if err := tpRatingProfileRPC.Call(utils.APIerSv1RemoveTPRatingProfile, - &AttrGetTPRatingProfile{TPid: "TPRProf1", RatingProfileID: utils.ConcatenatedKey(tpRatingProfile.LoadId, tpRatingProfile.Tenant, tpRatingProfile.Category, tpRatingProfile.Subject)}, &resp); err != nil { - t.Error(err) - } else if resp != utils.OK { - t.Error("Unexpected reply returned", resp) - } -} - -func testTPRatingProfilesGetTPRatingProfileAfterRemove(t *testing.T) { - var respond *utils.TPRatingProfile - if err := tpRatingProfileRPC.Call(utils.APIerSv1GetTPRatingProfile, - &AttrGetTPRatingProfile{TPid: "TPRProf1", RatingProfileID: tpRatingProfileID}, &respond); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPRatingProfilesKillEngine(t *testing.T) { - if err := engine.KillEngine(tpRatingProfileDelay); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/tpsharedgroups.go b/apier/v1/tpsharedgroups.go deleted file mode 100644 index 1b1b5ad9b..000000000 --- a/apier/v1/tpsharedgroups.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "github.com/cgrates/cgrates/utils" -) - -// SetTPSharedGroups creates a new SharedGroups profile within a tariff plan -func (apierSv1 *APIerSv1) SetTPSharedGroups(attrs *utils.TPSharedGroups, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID, utils.SharedGroups}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.SetTPSharedGroups([]*utils.TPSharedGroups{attrs}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - -type AttrGetTPSharedGroups struct { - TPid string // Tariff plan id - ID string // SharedGroup id -} - -// GetTPSharedGroups queries specific SharedGroup on tariff plan -func (apierSv1 *APIerSv1) GetTPSharedGroups(attrs *AttrGetTPSharedGroups, reply *utils.TPSharedGroups) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - sgs, err := apierSv1.StorDb.GetTPSharedGroups(attrs.TPid, attrs.ID) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = *sgs[0] - return nil -} - -type AttrGetTPSharedGroupIds struct { - TPid string // Tariff plan id - utils.PaginatorWithSearch -} - -// GetTPSharedGroupIds queries SharedGroups identities on specific tariff plan. -func (apierSv1 *APIerSv1) GetTPSharedGroupIds(attrs *AttrGetTPSharedGroupIds, reply *[]string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - ids, err := apierSv1.StorDb.GetTpTableIds(attrs.TPid, utils.TBLTPSharedGroups, - utils.TPDistinctIds{utils.TagCfg}, nil, &attrs.PaginatorWithSearch) - if err != nil { - if err.Error() != utils.ErrNotFound.Error() { - err = utils.NewErrServerError(err) - } - return err - } - *reply = ids - return nil -} - -// RemoveTPSharedGroups removes specific SharedGroups on Tariff plan -func (apierSv1 *APIerSv1) RemoveTPSharedGroups(attrs *AttrGetTPSharedGroups, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{utils.TPid, utils.ID}); len(missing) != 0 { //Params missing - return utils.NewErrMandatoryIeMissing(missing...) - } - if err := apierSv1.StorDb.RemTpData(utils.TBLTPSharedGroups, attrs.TPid, map[string]string{utils.TagCfg: attrs.ID}); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} diff --git a/apier/v1/tpsharedgroups_it_test.go b/apier/v1/tpsharedgroups_it_test.go deleted file mode 100644 index 4e8ba4479..000000000 --- a/apier/v1/tpsharedgroups_it_test.go +++ /dev/null @@ -1,232 +0,0 @@ -// +build offline - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "net/rpc" - "net/rpc/jsonrpc" - "path" - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - tpSharedGroupCfgPath string - tpSharedGroupCfg *config.CGRConfig - tpSharedGroupRPC *rpc.Client - tpSharedGroups *utils.TPSharedGroups - tpSharedGroupDelay int - tpSharedGroupConfigDIR string //run tests for specific configuration -) - -var sTestsTPSharedGroups = []func(t *testing.T){ - testTPSharedGroupsInitCfg, - testTPSharedGroupsResetStorDb, - testTPSharedGroupsStartEngine, - testTPSharedGroupsRpcConn, - testTPSharedGroupsBeforeSet, - testTPSharedGroupsSetSharedGroups, - testTPSharedGroupsAfterSet, - testTPSharedGroupsGetTPSharedGroupIds, - testTPSharedGroupsUpdateTPShareGroups, - testTpSharedGroupsGetTPSharedGroupsAfterUpdate, - testTPSharedGroupsRemoveTPSharedGroups, - testTPSharedGroupsGetTPSharedGroupsAfterRemove, - testTPSharedGroupsKillEngine, -} - -//Test start here -func TestTPSharedGroupsIT(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - tpSharedGroupConfigDIR = "tutinternal" - case utils.MetaMySQL: - tpSharedGroupConfigDIR = "tutmysql" - case utils.MetaMongo: - tpSharedGroupConfigDIR = "tutmongo" - case utils.MetaPostgres: - tpSharedGroupConfigDIR = "tutpostgres" - default: - t.Fatal("Unknown Database type") - } - for _, stest := range sTestsTPSharedGroups { - t.Run(tpSharedGroupConfigDIR, stest) - } -} - -func testTPSharedGroupsInitCfg(t *testing.T) { - var err error - tpSharedGroupCfgPath = path.Join(*dataDir, "conf", "samples", tpSharedGroupConfigDIR) - tpSharedGroupCfg, err = config.NewCGRConfigFromPath(tpSharedGroupCfgPath) - if err != nil { - t.Error(err) - } - switch tpSharedGroupConfigDIR { - case "tutmongo": // Mongo needs more time to reset db - tpSharedGroupDelay = 2000 - default: - tpSharedGroupDelay = 1000 - } -} - -// Wipe out the cdr database -func testTPSharedGroupsResetStorDb(t *testing.T) { - if err := engine.InitStorDb(tpSharedGroupCfg); err != nil { - t.Fatal(err) - } -} - -// Start CGR Engine -func testTPSharedGroupsStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(tpSharedGroupCfgPath, tpSharedGroupDelay); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testTPSharedGroupsRpcConn(t *testing.T) { - var err error - tpSharedGroupRPC, err = jsonrpc.Dial(utils.TCP, tpSharedGroupCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal(err) - } -} - -func testTPSharedGroupsBeforeSet(t *testing.T) { - var reply *utils.TPSharedGroups - if err := tpSharedGroupRPC.Call(utils.APIerSv1GetTPSharedGroups, &AttrGetTPSharedGroups{TPid: "TPS1", ID: "Group1"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPSharedGroupsSetSharedGroups(t *testing.T) { - tpSharedGroups = &utils.TPSharedGroups{ - TPid: "TPS1", - ID: "Group1", - SharedGroups: []*utils.TPSharedGroup{ - &utils.TPSharedGroup{ - Account: "AccOne", - Strategy: "StrategyOne", - RatingSubject: "SubOne", - }, - &utils.TPSharedGroup{ - Account: "AccTow", - Strategy: "StrategyTwo", - RatingSubject: "SubTwo", - }, - }, - } - var result string - if err := tpSharedGroupRPC.Call(utils.APIerSv1SetTPSharedGroups, &tpSharedGroups, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTPSharedGroupsAfterSet(t *testing.T) { - var respond *utils.TPSharedGroups - if err := tpSharedGroupRPC.Call(utils.APIerSv1GetTPSharedGroups, &AttrGetTPSharedGroups{TPid: tpSharedGroups.TPid, ID: tpSharedGroups.ID}, &respond); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpSharedGroups.TPid, respond.TPid) { - t.Errorf("Expecting: %+v, received: %+v", tpSharedGroups.TPid, respond.TPid) - } else if !reflect.DeepEqual(tpSharedGroups.ID, respond.ID) { - t.Errorf("Expecting: %+v, received: %+v", tpSharedGroups.ID, respond.ID) - } else if !reflect.DeepEqual(len(tpSharedGroups.SharedGroups), len(respond.SharedGroups)) { - t.Errorf("Expecting: %+v, received: %+v", len(tpSharedGroups.SharedGroups), len(respond.SharedGroups)) - } -} - -func testTPSharedGroupsGetTPSharedGroupIds(t *testing.T) { - var result []string - expectedTPID := []string{"Group1"} - if err := tpSharedGroupRPC.Call(utils.APIerSv1GetTPSharedGroupIds, - &AttrGetTPSharedGroupIds{tpSharedGroups.TPid, utils.PaginatorWithSearch{}}, &result); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(result, expectedTPID) { - t.Errorf("Expecting: %+v, received: %+v", result, expectedTPID) - } -} - -func testTPSharedGroupsUpdateTPShareGroups(t *testing.T) { - var result string - tpSharedGroups.SharedGroups = []*utils.TPSharedGroup{ - &utils.TPSharedGroup{ - Account: "AccOne", - Strategy: "StrategyOne", - RatingSubject: "SubOne", - }, - &utils.TPSharedGroup{ - Account: "AccTow", - Strategy: "StrategyTwo", - RatingSubject: "SubTwo", - }, - &utils.TPSharedGroup{ - Account: "AccPlus", - Strategy: "StrategyPlus", - RatingSubject: "SubPlus", - }, - } - if err := tpSharedGroupRPC.Call(utils.APIerSv1SetTPSharedGroups, tpSharedGroups, &result); err != nil { - t.Error(err) - } else if result != utils.OK { - t.Error("Unexpected reply returned", result) - } -} - -func testTpSharedGroupsGetTPSharedGroupsAfterUpdate(t *testing.T) { - var expectedTPS *utils.TPSharedGroups - if err := tpSharedGroupRPC.Call(utils.APIerSv1GetTPSharedGroups, &AttrGetTPSharedGroups{TPid: tpSharedGroups.TPid, ID: tpSharedGroups.ID}, &expectedTPS); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(tpSharedGroups.TPid, expectedTPS.TPid) { - t.Errorf("Expecting: %+v, received: %+v", tpSharedGroups.TPid, expectedTPS.TPid) - } else if !reflect.DeepEqual(tpSharedGroups.ID, expectedTPS.ID) { - t.Errorf("Expecting: %+v, received: %+v", tpSharedGroups.ID, expectedTPS.ID) - } else if !reflect.DeepEqual(len(tpSharedGroups.SharedGroups), len(expectedTPS.SharedGroups)) { - t.Errorf("Expecting: %+v, received: %+v", len(tpSharedGroups.SharedGroups), len(expectedTPS.SharedGroups)) - } -} - -func testTPSharedGroupsRemoveTPSharedGroups(t *testing.T) { - var resp string - if err := tpSharedGroupRPC.Call(utils.APIerSv1RemoveTPSharedGroups, &AttrGetTPSharedGroups{TPid: tpSharedGroups.TPid, ID: tpSharedGroups.ID}, &resp); err != nil { - t.Error(err) - } else if resp != utils.OK { - t.Error("Unexpected reply returned", resp) - } -} - -func testTPSharedGroupsGetTPSharedGroupsAfterRemove(t *testing.T) { - var reply *utils.TPSharedGroups - if err := tpSharedGroupRPC.Call(utils.APIerSv1GetTPSharedGroups, &AttrGetTPSharedGroups{TPid: "TPS1", ID: "Group1"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Error(err) - } -} - -func testTPSharedGroupsKillEngine(t *testing.T) { - if err := engine.KillEngine(tpSharedGroupDelay); err != nil { - t.Error(err) - } -} diff --git a/apier/v1/triggers.go b/apier/v1/triggers.go deleted file mode 100644 index 49f8b88f2..000000000 --- a/apier/v1/triggers.go +++ /dev/null @@ -1,604 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "errors" - "strings" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/guardian" - "github.com/cgrates/cgrates/utils" -) - -// Returns a list of ActionTriggers on an account -func (apierSv1 *APIerSv1) GetAccountActionTriggers(attrs *utils.TenantAccount, reply *engine.ActionTriggers) error { - if missing := utils.MissingStructFields(attrs, []string{utils.AccountField}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - tnt := attrs.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - if account, err := apierSv1.DataManager.GetAccount(utils.ConcatenatedKey(tnt, attrs.Account)); err != nil { - return utils.NewErrServerError(err) - } else { - ats := account.ActionTriggers - if ats == nil { - ats = engine.ActionTriggers{} - } - *reply = ats - } - return nil -} - -type AttrAddAccountActionTriggers struct { - Tenant string - Account string - ActionTriggerIDs []string - ActionTriggerOverwrite bool - ActivationDate string - Executed bool -} - -func (apierSv1 *APIerSv1) AddAccountActionTriggers(attr *AttrAddAccountActionTriggers, reply *string) (err error) { - if missing := utils.MissingStructFields(attr, []string{utils.AccountField}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - tnt := attr.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - var actTime time.Time - if actTime, err = utils.ParseTimeDetectLayout(attr.ActivationDate, - apierSv1.Config.GeneralCfg().DefaultTimezone); err != nil { - return - } - accID := utils.ConcatenatedKey(tnt, attr.Account) - var account *engine.Account - _, err = guardian.Guardian.Guard(func() (interface{}, error) { - if account, err = apierSv1.DataManager.GetAccount(accID); err != nil { - return 0, err - } - if attr.ActionTriggerOverwrite { - account.ActionTriggers = make(engine.ActionTriggers, 0) - } - for _, actionTriggerID := range attr.ActionTriggerIDs { - atrs, err := apierSv1.DataManager.GetActionTriggers(actionTriggerID, false, utils.NonTransactional) - if err != nil { - return 0, err - } - for _, at := range atrs { - var found bool - for _, existingAt := range account.ActionTriggers { - if existingAt.Equals(at) { - found = true - break - } - } - at.ActivationDate = actTime - at.Executed = attr.Executed - if !found { - account.ActionTriggers = append(account.ActionTriggers, at) - } - } - } - account.InitCounters() - return 0, apierSv1.DataManager.SetAccount(account) - }, config.CgrConfig().GeneralCfg().LockingTimeout, utils.AccountPrefix+accID) - if err != nil { - return - } - *reply = utils.OK - return -} - -type AttrRemoveAccountActionTriggers struct { - Tenant string - Account string - GroupID string - UniqueID string -} - -func (apierSv1 *APIerSv1) RemoveAccountActionTriggers(attr *AttrRemoveAccountActionTriggers, reply *string) error { - if missing := utils.MissingStructFields(attr, []string{utils.AccountField}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - tnt := attr.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - accID := utils.ConcatenatedKey(tnt, attr.Account) - _, err := guardian.Guardian.Guard(func() (interface{}, error) { - var account *engine.Account - if acc, err := apierSv1.DataManager.GetAccount(accID); err == nil { - account = acc - } else { - return 0, err - } - var newActionTriggers engine.ActionTriggers - for _, at := range account.ActionTriggers { - if (attr.UniqueID == "" || at.UniqueID == attr.UniqueID) && - (attr.GroupID == "" || at.ID == attr.GroupID) { - // remove action trigger - continue - } - newActionTriggers = append(newActionTriggers, at) - } - account.ActionTriggers = newActionTriggers - account.InitCounters() - return 0, apierSv1.DataManager.SetAccount(account) - }, config.CgrConfig().GeneralCfg().LockingTimeout, accID) - if err != nil { - *reply = err.Error() - return err - } - *reply = utils.OK - return nil -} - -type AttrResetAccountActionTriggers struct { - Tenant string - Account string - GroupID string - UniqueID string - Executed bool -} - -func (apierSv1 *APIerSv1) ResetAccountActionTriggers(attr *AttrResetAccountActionTriggers, reply *string) error { - if missing := utils.MissingStructFields(attr, []string{utils.AccountField}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - tnt := attr.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - accID := utils.ConcatenatedKey(tnt, attr.Account) - var account *engine.Account - _, err := guardian.Guardian.Guard(func() (interface{}, error) { - if acc, err := apierSv1.DataManager.GetAccount(accID); err == nil { - account = acc - } else { - return 0, err - } - for _, at := range account.ActionTriggers { - if (attr.UniqueID == "" || at.UniqueID == attr.UniqueID) && - (attr.GroupID == "" || at.ID == attr.GroupID) { - // reset action trigger - at.Executed = attr.Executed - } - - } - if attr.Executed == false { - account.ExecuteActionTriggers(nil) - } - return 0, apierSv1.DataManager.SetAccount(account) - }, config.CgrConfig().GeneralCfg().LockingTimeout, utils.AccountPrefix+accID) - if err != nil { - *reply = err.Error() - return err - } - *reply = utils.OK - return nil -} - -type AttrSetAccountActionTriggers struct { - Tenant string - Account string - AttrSetActionTrigger -} -type AttrSetActionTrigger struct { - GroupID string - UniqueID string - ActionTrigger map[string]interface{} -} - -// UpdateActionTrigger updates the ActionTrigger if is matching -func (attr *AttrSetActionTrigger) UpdateActionTrigger(at *engine.ActionTrigger, timezone string) (updated bool, err error) { - if at == nil { - return false, errors.New("Empty ActionTrigger") - } - if at.ID == utils.EmptyString { // New AT, update it's data - if attr.GroupID == utils.EmptyString { - return false, utils.NewErrMandatoryIeMissing(utils.GroupID) - } - if missing := utils.MissingMapFields(attr.ActionTrigger, []string{"ThresholdType", "ThresholdValue"}); len(missing) != 0 { - return false, utils.NewErrMandatoryIeMissing(missing...) - } - at.ID = attr.GroupID - if attr.UniqueID != utils.EmptyString { - at.UniqueID = attr.UniqueID - } - } - if attr.GroupID != utils.EmptyString && attr.GroupID != at.ID { - return - } - if attr.UniqueID != utils.EmptyString && attr.UniqueID != at.UniqueID { - return - } - // at matches - updated = true - if thr, has := attr.ActionTrigger[utils.ThresholdType]; has { - at.ThresholdType = utils.IfaceAsString(thr) - } - if thr, has := attr.ActionTrigger[utils.ThresholdValue]; has { - if at.ThresholdValue, err = utils.IfaceAsFloat64(thr); err != nil { - return - } - } - if rec, has := attr.ActionTrigger[utils.Recurrent]; has { - if at.Recurrent, err = utils.IfaceAsBool(rec); err != nil { - return - } - } - if exec, has := attr.ActionTrigger[utils.Executed]; has { - if at.Executed, err = utils.IfaceAsBool(exec); err != nil { - return - } - } - if minS, has := attr.ActionTrigger[utils.MinSleep]; has { - if at.MinSleep, err = utils.IfaceAsDuration(minS); err != nil { - return - } - } - if exp, has := attr.ActionTrigger[utils.ExpirationDate]; has { - if at.ExpirationDate, err = utils.IfaceAsTime(exp, timezone); err != nil { - return - } - } - if act, has := attr.ActionTrigger[utils.ActivationDate]; has { - if at.ActivationDate, err = utils.IfaceAsTime(act, timezone); err != nil { - return - } - } - if at.Balance == nil { - at.Balance = &engine.BalanceFilter{} - } - if bid, has := attr.ActionTrigger[utils.BalanceID]; has { - at.Balance.ID = utils.StringPointer(utils.IfaceAsString(bid)) - } - if btype, has := attr.ActionTrigger[utils.BalanceType]; has { - at.Balance.Type = utils.StringPointer(utils.IfaceAsString(btype)) - } - if bdest, has := attr.ActionTrigger[utils.BalanceDestinationIds]; has { - var bdIds []string - if bdIds, err = utils.IfaceAsSliceString(bdest); err != nil { - return - } - at.Balance.DestinationIDs = utils.StringMapPointer(utils.NewStringMap(bdIds...)) - } - if bweight, has := attr.ActionTrigger[utils.BalanceWeight]; has { - var bw float64 - if bw, err = utils.IfaceAsFloat64(bweight); err != nil { - return - } - at.Balance.Weight = utils.Float64Pointer(bw) - } - if exp, has := attr.ActionTrigger[utils.BalanceExpirationDate]; has { - var balanceExpTime time.Time - if balanceExpTime, err = utils.IfaceAsTime(exp, timezone); err != nil { - return - } - at.Balance.ExpirationDate = utils.TimePointer(balanceExpTime) - } - if bTimeTag, has := attr.ActionTrigger[utils.BalanceTimingTags]; has { - var timeTag []string - if timeTag, err = utils.IfaceAsSliceString(bTimeTag); err != nil { - return - } - at.Balance.TimingIDs = utils.StringMapPointer(utils.NewStringMap(timeTag...)) - } - if brs, has := attr.ActionTrigger[utils.BalanceRatingSubject]; has { - at.Balance.RatingSubject = utils.StringPointer(utils.IfaceAsString(brs)) - } - if bcat, has := attr.ActionTrigger[utils.BalanceCategories]; has { - var cat []string - if cat, err = utils.IfaceAsSliceString(bcat); err != nil { - return - } - at.Balance.Categories = utils.StringMapPointer(utils.NewStringMap(cat...)) - } - if bsg, has := attr.ActionTrigger[utils.BalanceSharedGroups]; has { - var shrgrps []string - if shrgrps, err = utils.IfaceAsSliceString(bsg); err != nil { - return - } - at.Balance.SharedGroups = utils.StringMapPointer(utils.NewStringMap(shrgrps...)) - } - if bb, has := attr.ActionTrigger[utils.BalanceBlocker]; has { - var bBlocker bool - if bBlocker, err = utils.IfaceAsBool(bb); err != nil { - return - } - at.Balance.Blocker = utils.BoolPointer(bBlocker) - } - if bd, has := attr.ActionTrigger[utils.BalanceDisabled]; has { - var bDis bool - if bDis, err = utils.IfaceAsBool(bd); err != nil { - return - } - at.Balance.Disabled = utils.BoolPointer(bDis) - } - if minQ, has := attr.ActionTrigger[utils.MinQueuedItems]; has { - var mQ int64 - if mQ, err = utils.IfaceAsInt64(minQ); err != nil { - return - } - at.MinQueuedItems = int(mQ) - } - if accID, has := attr.ActionTrigger[utils.ActionsID]; has { - at.ActionsID = utils.IfaceAsString(accID) - } - return -} - -// SetAccountActionTriggers updates or creates if not present the ActionTrigger for an Account -func (apierSv1 *APIerSv1) SetAccountActionTriggers(attr *AttrSetAccountActionTriggers, reply *string) error { - if missing := utils.MissingStructFields(attr, []string{utils.AccountField}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - tnt := attr.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - accID := utils.ConcatenatedKey(tnt, attr.Account) - var account *engine.Account - _, err := guardian.Guardian.Guard(func() (interface{}, error) { - if acc, err := apierSv1.DataManager.GetAccount(accID); err == nil { - account = acc - } else { - return 0, err - } - var foundOne bool - for _, at := range account.ActionTriggers { - if updated, err := attr.UpdateActionTrigger(at, - apierSv1.Config.GeneralCfg().DefaultTimezone); err != nil { - return 0, err - } else if updated && !foundOne { - foundOne = true - } - } - if !foundOne { // Did not find one to update, create a new AT - at := new(engine.ActionTrigger) - if updated, err := attr.UpdateActionTrigger(at, - apierSv1.Config.GeneralCfg().DefaultTimezone); err != nil { - return 0, err - } else if updated { // Adding a new AT - account.ActionTriggers = append(account.ActionTriggers, at) - } - } - account.ExecuteActionTriggers(nil) - return 0, apierSv1.DataManager.SetAccount(account) - }, config.CgrConfig().GeneralCfg().LockingTimeout, utils.AccountPrefix+accID) - if err != nil { - *reply = err.Error() - return err - } - *reply = utils.OK - return nil -} - -type AttrRemoveActionTrigger struct { - GroupID string - UniqueID string -} - -func (apierSv1 *APIerSv1) RemoveActionTrigger(attr *AttrRemoveActionTrigger, reply *string) (err error) { - if missing := utils.MissingStructFields(attr, []string{"GroupID"}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - if attr.UniqueID == "" { - err = apierSv1.DataManager.RemoveActionTriggers(attr.GroupID, utils.NonTransactional) - if err != nil { - return - } - *reply = utils.OK - return - } - var atrs engine.ActionTriggers - if atrs, err = apierSv1.DataManager.GetActionTriggers(attr.GroupID, false, utils.NonTransactional); err != nil { - return - } - remainingAtrs := make(engine.ActionTriggers, 0, len(atrs)) - for _, atr := range atrs { - if atr.UniqueID != attr.UniqueID { - remainingAtrs = append(remainingAtrs, atr) - } - } - // set the cleared list back - if err = apierSv1.DataManager.SetActionTriggers(attr.GroupID, remainingAtrs, utils.NonTransactional); err != nil { - return - } - // CacheReload - if err = apierSv1.ConnMgr.Call(apierSv1.Config.ApierCfg().CachesConns, nil, - utils.CacheSv1ReloadCache, utils.AttrReloadCacheWithAPIOpts{ - ArgsCache: map[string][]string{utils.ActionTriggerIDs: {attr.GroupID}}, - }, reply); err != nil { - return - } - // generate a loadID for CacheActionTriggers and store it in database - if err = apierSv1.DataManager.SetLoadIDs(map[string]int64{utils.CacheActionTriggers: time.Now().UnixNano()}); err != nil { - return utils.APIErrorHandler(err) - } - *reply = utils.OK - return -} - -// SetActionTrigger updates a ActionTrigger -func (apierSv1 *APIerSv1) SetActionTrigger(attr *AttrSetActionTrigger, reply *string) (err error) { - if missing := utils.MissingStructFields(attr, []string{"GroupID"}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - - atrs, _ := apierSv1.DataManager.GetActionTriggers(attr.GroupID, false, utils.NonTransactional) - var newAtr *engine.ActionTrigger - if attr.UniqueID != utils.EmptyString { - //search for exiting one - for _, atr := range atrs { - if atr.UniqueID == attr.UniqueID { - newAtr = atr - break - } - } - } - - if newAtr == nil { - newAtr = &engine.ActionTrigger{} - atrs = append(atrs, newAtr) - } - if attr.UniqueID == utils.EmptyString { - attr.UniqueID = utils.GenUUID() - } - newAtr.ID = attr.GroupID - newAtr.UniqueID = attr.UniqueID - if _, err = attr.UpdateActionTrigger(newAtr, - apierSv1.Config.GeneralCfg().DefaultTimezone); err != nil { - return - } - - if err = apierSv1.DataManager.SetActionTriggers(attr.GroupID, atrs, utils.NonTransactional); err != nil { - return - } - // CacheReload - if err = apierSv1.ConnMgr.Call(apierSv1.Config.ApierCfg().CachesConns, nil, - utils.CacheSv1ReloadCache, utils.AttrReloadCacheWithAPIOpts{ - ArgsCache: map[string][]string{utils.ActionTriggerIDs: {attr.GroupID}}, - }, reply); err != nil { - return - } - // generate a loadID for CacheActionTriggers and store it in database - if err = apierSv1.DataManager.SetLoadIDs(map[string]int64{utils.CacheActionTriggers: time.Now().UnixNano()}); err != nil { - return utils.APIErrorHandler(err) - } - *reply = utils.OK - return -} - -type AttrGetActionTriggers struct { - GroupIDs []string -} - -func (apierSv1 *APIerSv1) GetActionTriggers(attr *AttrGetActionTriggers, atrs *engine.ActionTriggers) error { - var allAttrs engine.ActionTriggers - if len(attr.GroupIDs) > 0 { - for _, key := range attr.GroupIDs { - getAttrs, err := apierSv1.DataManager.GetActionTriggers(key, false, utils.NonTransactional) - if err != nil { - return err - } - allAttrs = append(allAttrs, getAttrs...) - } - - } else { - keys, err := apierSv1.DataManager.DataDB().GetKeysForPrefix(utils.ActionTriggerPrefix) - if err != nil { - return err - } - if len(keys) == 0 { - return utils.ErrNotFound - } - for _, key := range keys { - getAttrs, err := apierSv1.DataManager.GetActionTriggers(key[len(utils.ActionTriggerPrefix):], false, utils.NonTransactional) - if err != nil { - return err - } - allAttrs = append(allAttrs, getAttrs...) - } - } - *atrs = allAttrs - return nil -} - -type AttrAddActionTrigger struct { - ActionTriggersId string - Tenant string - Account string - ThresholdType string - ThresholdValue float64 - BalanceId string - BalanceType string - BalanceDestinationIds string - BalanceRatingSubject string - BalanceWeight float64 - BalanceExpiryTime string - BalanceSharedGroup string - Weight float64 - ActionsId string -} - -// Deprecated in rc8, replaced by AddAccountActionTriggers -func (apierSv1 *APIerSv1) AddTriggeredAction(attr AttrAddActionTrigger, reply *string) error { - if missing := utils.MissingStructFields(&attr, []string{utils.AccountField}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - tnt := attr.Tenant - if tnt == utils.EmptyString { - tnt = apierSv1.Config.GeneralCfg().DefaultTenant - } - at := &engine.ActionTrigger{ - ID: attr.ActionTriggersId, - ThresholdType: attr.ThresholdType, - ThresholdValue: attr.ThresholdValue, - Balance: new(engine.BalanceFilter), - Weight: attr.Weight, - ActionsID: attr.ActionsId, - } - if attr.BalanceId != "" { - at.Balance.ID = utils.StringPointer(attr.BalanceId) - } - if attr.BalanceType != "" { - at.Balance.Type = utils.StringPointer(attr.BalanceType) - } - if attr.BalanceDestinationIds != "" { - dstIDsMp := utils.StringMapFromSlice(strings.Split(attr.BalanceDestinationIds, utils.InfieldSep)) - at.Balance.DestinationIDs = &dstIDsMp - } - if attr.BalanceRatingSubject != "" { - at.Balance.RatingSubject = utils.StringPointer(attr.BalanceRatingSubject) - } - if attr.BalanceWeight != 0.0 { - at.Balance.Weight = utils.Float64Pointer(attr.BalanceWeight) - } - if balExpiryTime, err := utils.ParseTimeDetectLayout(attr.BalanceExpiryTime, - apierSv1.Config.GeneralCfg().DefaultTimezone); err != nil { - return utils.NewErrServerError(err) - } else { - at.Balance.ExpirationDate = &balExpiryTime - } - if attr.BalanceSharedGroup != "" { - at.Balance.SharedGroups = &utils.StringMap{attr.BalanceSharedGroup: true} - } - acntID := utils.ConcatenatedKey(tnt, attr.Account) - _, err := guardian.Guardian.Guard(func() (interface{}, error) { - acnt, err := apierSv1.DataManager.GetAccount(acntID) - if err != nil { - return 0, err - } - acnt.ActionTriggers = append(acnt.ActionTriggers, at) - - return 0, apierSv1.DataManager.SetAccount(acnt) - }, config.CgrConfig().GeneralCfg().LockingTimeout, utils.AccountPrefix+acntID) - if err != nil { - return err - } - *reply = utils.OK - return nil -} diff --git a/apier/v1/triggers_test.go b/apier/v1/triggers_test.go deleted file mode 100644 index b5103fbb9..000000000 --- a/apier/v1/triggers_test.go +++ /dev/null @@ -1,208 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package v1 - -import ( - "reflect" - "testing" - "time" - - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func TestAttrSetActionTriggerUpdateActionTrigger(t *testing.T) { - ast := AttrSetActionTrigger{} - if _, err := ast.UpdateActionTrigger(nil, ""); err == nil || err.Error() != "Empty ActionTrigger" { - t.Errorf("Expected error \"Empty ActionTrigger\", received: %v", err) - } - expErr := utils.NewErrMandatoryIeMissing(utils.GroupID) - args := &engine.ActionTrigger{} - if _, err := ast.UpdateActionTrigger(args, ""); err == nil || err.Error() != expErr.Error() { - t.Errorf("Expected error %s , received: %v", expErr, err) - } - ast.GroupID = "GroupID" - expErr = utils.NewErrMandatoryIeMissing("ThresholdType", "ThresholdValue") - if _, err := ast.UpdateActionTrigger(args, ""); err == nil || err.Error() != expErr.Error() { - t.Errorf("Expected error %s , received: %v", expErr, err) - } - tNow := time.Now() - ast = AttrSetActionTrigger{ - GroupID: "GroupID", - UniqueID: "ID", - ActionTrigger: map[string]interface{}{ - utils.ThresholdType: "THR", - utils.ThresholdValue: 10, - utils.Recurrent: false, - utils.Executed: false, - utils.MinSleep: time.Second, - utils.ExpirationDate: tNow, - utils.ActivationDate: tNow, - utils.BalanceID: "*default", - utils.BalanceType: "*call", - utils.BalanceDestinationIds: []interface{}{"DST1", "DST2"}, - utils.BalanceWeight: 10, - utils.BalanceExpirationDate: tNow, - utils.BalanceTimingTags: []string{"*asap"}, - utils.BalanceRatingSubject: "*zero", - utils.BalanceCategories: []string{utils.Call}, - utils.BalanceSharedGroups: []string{"SHRGroup"}, - utils.BalanceBlocker: true, - utils.BalanceDisabled: false, - utils.ActionsID: "ACT1", - utils.MinQueuedItems: 5, - }, - } - exp := &engine.ActionTrigger{ - ID: "GroupID", - UniqueID: "ID", - ThresholdType: "THR", - ThresholdValue: 10, - Recurrent: false, - MinSleep: time.Second, - ExpirationDate: tNow, - ActivationDate: tNow, - Balance: &engine.BalanceFilter{ - ID: utils.StringPointer(utils.MetaDefault), - Type: utils.StringPointer("*call"), - ExpirationDate: utils.TimePointer(tNow), - Weight: utils.Float64Pointer(10), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("DST1", "DST2")), - RatingSubject: utils.StringPointer("*zero"), - Categories: utils.StringMapPointer(utils.NewStringMap(utils.Call)), - SharedGroups: utils.StringMapPointer(utils.NewStringMap("SHRGroup")), - TimingIDs: utils.StringMapPointer(utils.NewStringMap("*asap")), - Disabled: utils.BoolPointer(false), - Blocker: utils.BoolPointer(true), - }, - ActionsID: "ACT1", - MinQueuedItems: 5, - Executed: false, - } - if updated, err := ast.UpdateActionTrigger(args, ""); err != nil { - t.Error(err) - } else if !updated { - t.Errorf("Expected to be updated") - } else if !reflect.DeepEqual(exp, args) { - t.Errorf("Expected: %s ,received: %s", utils.ToJSON(exp), utils.ToJSON(args)) - } - - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.MinQueuedItems] = "NotInt" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.BalanceDisabled] = "NotBool" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.BalanceBlocker] = "NotBool" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.BalanceSharedGroups] = "notSlice" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.BalanceCategories] = "notSlice" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.BalanceTimingTags] = "notSlice" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.BalanceExpirationDate] = "notTime" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.BalanceWeight] = "notFloat" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.BalanceDestinationIds] = "notSlice" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.ActivationDate] = "notTime" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.ExpirationDate] = "notTime" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.MinSleep] = "notDuration" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.Executed] = "notBool" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.Recurrent] = "notBool" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{} - ast.ActionTrigger[utils.ThresholdValue] = "notFloat" - if _, err := ast.UpdateActionTrigger(args, ""); err == nil { - t.Errorf("Expected error received: %v", err) - } - args = &engine.ActionTrigger{ - ID: "GroupID2", - UniqueID: "ID2", - } - ast = AttrSetActionTrigger{ - GroupID: "GroupID", - UniqueID: "ID", - } - if updated, err := ast.UpdateActionTrigger(args, ""); err != nil { - t.Error(err) - } else if updated { - t.Errorf("Expected to not be updated") - } - args = &engine.ActionTrigger{ - ID: "GroupID", - UniqueID: "ID2", - } - ast = AttrSetActionTrigger{ - GroupID: "GroupID", - UniqueID: "ID", - } - if updated, err := ast.UpdateActionTrigger(args, ""); err != nil { - t.Error(err) - } else if updated { - t.Errorf("Expected to not be updated") - } - -} diff --git a/apier/v2/apier.go b/apier/v2/apier.go index 0e17d7fe8..281dd022b 100644 --- a/apier/v2/apier.go +++ b/apier/v2/apier.go @@ -19,13 +19,9 @@ along with this program. If not, see package v2 import ( - "errors" "fmt" - "math" "os" - "strconv" "strings" - "time" v1 "github.com/cgrates/cgrates/apier/v1" "github.com/cgrates/cgrates/config" @@ -43,36 +39,6 @@ func (apiv2 *APIerSv2) Call(serviceMethod string, return utils.APIerRPCCall(apiv2, serviceMethod, args, reply) } -type AttrLoadRatingProfile struct { - TPid string - RatingProfileID string -} - -// Process dependencies and load a specific rating profile from storDb into dataDb. -func (apiv2 *APIerSv2) LoadRatingProfile(attrs *AttrLoadRatingProfile, reply *string) error { - if len(attrs.TPid) == 0 { - return utils.NewErrMandatoryIeMissing("TPid") - } - dbReader, err := engine.NewTpReader(apiv2.DataManager.DataDB(), apiv2.StorDb, - attrs.TPid, apiv2.Config.GeneralCfg().DefaultTimezone, - apiv2.Config.ApierCfg().CachesConns, apiv2.Config.ApierCfg().ActionConns, - apiv2.Config.DataDbCfg().Type == utils.INTERNAL) - if err != nil { - return utils.NewErrServerError(err) - } - if err := dbReader.LoadRatingProfilesFiltered(&utils.TPRatingProfile{TPid: attrs.TPid}); err != nil { - return utils.NewErrServerError(err) - } - if err := apiv2.DataManager.SetLoadIDs(map[string]int64{utils.CacheRatingProfiles: time.Now().UnixNano()}); err != nil { - return utils.APIErrorHandler(err) - } - if err = dbReader.ReloadCache(config.CgrConfig().GeneralCfg().DefaultCaching, true, make(map[string]interface{})); err != nil { - return utils.NewErrServerError(err) - } - *reply = utils.OK - return nil -} - type AttrLoadAccountActions struct { TPid string AccountActionsId string @@ -105,12 +71,6 @@ func (apiv2 *APIerSv2) LoadTariffPlanFromFolder(attrs *utils.AttrLoadTpFromFolde return nil // Mission complete, no errors } - if attrs.Validate { - if !loader.IsValid() { - return errors.New("invalid data") - } - } - if err := loader.WriteToDatabase(false, false); err != nil { return utils.NewErrServerError(err) } @@ -142,61 +102,6 @@ func (apiv2 *APIerSv2) LoadTariffPlanFromFolder(attrs *utils.AttrLoadTpFromFolde return nil } -type AttrGetActions struct { - ActionIDs []string - Offset int // Set the item offset - Limit int // Limit number of items retrieved -} - -// Retrieves actions attached to specific ActionsId within cache -func (apiv2 *APIerSv2) GetActions(attr *AttrGetActions, reply *map[string]engine.Actions) error { - var actionKeys []string - var err error - if len(attr.ActionIDs) == 0 { - if actionKeys, err = apiv2.DataManager.DataDB().GetKeysForPrefix(utils.ActionPrefix); err != nil { - return err - } - } else { - for _, accID := range attr.ActionIDs { - if len(accID) == 0 { // Source of error returned from redis (key not found) - continue - } - actionKeys = append(actionKeys, utils.AccountPrefix+accID) - } - } - if len(actionKeys) == 0 { - return nil - } - if attr.Offset > len(actionKeys) { - attr.Offset = len(actionKeys) - } - if attr.Offset < 0 { - attr.Offset = 0 - } - var limitedActions []string - if attr.Limit != 0 { - max := math.Min(float64(attr.Offset+attr.Limit), float64(len(actionKeys))) - limitedActions = actionKeys[attr.Offset:int(max)] - } else { - limitedActions = actionKeys[attr.Offset:] - } - retActions := make(map[string]engine.Actions) - for _, accKey := range limitedActions { - key := accKey[len(utils.ActionPrefix):] - acts, err := apiv2.DataManager.GetActions(key, false, utils.NonTransactional) - if err != nil { - return utils.NewErrServerError(err) - } - if len(acts) > 0 { - retActions[key] = acts - - } - } - - *reply = retActions - return nil -} - type AttrGetActionsCount struct{} // GetActionsCount sets in reply var the total number of actions registered for the received tenant @@ -238,108 +143,6 @@ func (apiv2 *APIerSv2) GetDestinations(attr *AttrGetDestinations, reply *[]*engi return } -func (apiv2 *APIerSv2) SetActions(attrs *utils.AttrSetActions, reply *string) error { - if missing := utils.MissingStructFields(attrs, []string{"ActionsId", "Actions"}); len(missing) != 0 { - return utils.NewErrMandatoryIeMissing(missing...) - } - for _, action := range attrs.Actions { - requiredFields := []string{"Identifier", "Weight"} - if action.BalanceType != "" { // Add some inter-dependent parameters - if balanceType then we are not talking about simply calling actions - requiredFields = append(requiredFields, "Units") - } - if missing := utils.MissingStructFields(action, requiredFields); len(missing) != 0 { - return fmt.Errorf("%s:Action:%s:%v", utils.ErrMandatoryIeMissing.Error(), action.Identifier, missing) - } - } - if !attrs.Overwrite { - if exists, err := apiv2.DataManager.HasData(utils.ActionPrefix, attrs.ActionsId, ""); err != nil { - return utils.NewErrServerError(err) - } else if exists { - return utils.ErrExists - } - } - storeActions := make(engine.Actions, len(attrs.Actions)) - for idx, apiAct := range attrs.Actions { - var vf *utils.ValueFormula - if apiAct.Units != "" { - x, err := utils.ParseBalanceFilterValue(apiAct.BalanceType, apiAct.Units) - if err != nil { - return err - } - vf = x - } - - var weight *float64 - if apiAct.BalanceWeight != "" { - x, err := strconv.ParseFloat(apiAct.BalanceWeight, 64) - if err != nil { - return err - } - weight = &x - } - - var blocker *bool - if apiAct.BalanceBlocker != "" { - x, err := strconv.ParseBool(apiAct.BalanceBlocker) - if err != nil { - return err - } - blocker = &x - } - - var disabled *bool - if apiAct.BalanceDisabled != "" { - x, err := strconv.ParseBool(apiAct.BalanceDisabled) - if err != nil { - return err - } - disabled = &x - } - - a := &engine.Action{ - Id: attrs.ActionsId, - ActionType: apiAct.Identifier, - Weight: apiAct.Weight, - ExpirationString: apiAct.ExpiryTime, - ExtraParameters: apiAct.ExtraParameters, - Filter: apiAct.Filter, - } - if apiAct.Identifier != utils.MetaResetTriggers { // add an exception for ResetTriggers - a.Balance = &engine.BalanceFilter{ // TODO: update this part - Uuid: utils.StringPointer(apiAct.BalanceUuid), - ID: utils.StringPointer(apiAct.BalanceId), - Type: utils.StringPointer(apiAct.BalanceType), - Value: vf, - Weight: weight, - DestinationIDs: utils.StringMapPointer(utils.ParseStringMap(apiAct.DestinationIds)), - RatingSubject: utils.StringPointer(apiAct.RatingSubject), - SharedGroups: utils.StringMapPointer(utils.ParseStringMap(apiAct.SharedGroups)), - Categories: utils.StringMapPointer(utils.ParseStringMap(apiAct.Categories)), - TimingIDs: utils.StringMapPointer(utils.ParseStringMap(apiAct.TimingTags)), - Blocker: blocker, - Disabled: disabled, - } - } - storeActions[idx] = a - } - if err := apiv2.DataManager.SetActions(attrs.ActionsId, storeActions, utils.NonTransactional); err != nil { - return utils.NewErrServerError(err) - } - //CacheReload - if err := apiv2.ConnMgr.Call(apiv2.Config.ApierCfg().CachesConns, nil, - utils.CacheSv1ReloadCache, utils.AttrReloadCacheWithAPIOpts{ - ArgsCache: map[string][]string{utils.ActionIDs: {attrs.ActionsId}}, - }, reply); err != nil { - return err - } - //generate a loadID for CacheActions and store it in database - if err := apiv2.DataManager.SetLoadIDs(map[string]int64{utils.CacheActions: time.Now().UnixNano()}); err != nil { - return utils.APIErrorHandler(err) - } - *reply = utils.OK - return nil -} - // Ping return pong if the service is active func (apiv2 *APIerSv2) Ping(ign *utils.CGREvent, reply *string) error { *reply = utils.Pong diff --git a/cmd/cgr-engine/cgr-engine.go b/cmd/cgr-engine/cgr-engine.go index 8290702bb..e56373050 100644 --- a/cmd/cgr-engine/cgr-engine.go +++ b/cmd/cgr-engine/cgr-engine.go @@ -644,11 +644,7 @@ func main() { routeS := services.NewRouteService(cfg, dmService, cacheS, filterSChan, server, internalRouteSChan, connManager, anz, srvDep) - rals := services.NewRalService(cfg, cacheS, server, - internalRALsChan, internalResponderChan, - shdChan, connManager, anz, srvDep) - - apiSv1 := services.NewAPIerSv1Service(cfg, dmService, storDBService, filterSChan, server, rals.GetResponder(), + apiSv1 := services.NewAPIerSv1Service(cfg, dmService, storDBService, filterSChan, server, internalAPIerSv1Chan, connManager, anz, srvDep) apiSv2 := services.NewAPIerSv2Service(apiSv1, cfg, server, internalAPIerSv2Chan, anz, srvDep) @@ -661,7 +657,7 @@ func main() { ldrs := services.NewLoaderService(cfg, dmService, filterSChan, server, internalLoaderSChan, connManager, anz, srvDep) - srvManager.AddServices(gvService, attrS, chrS, tS, stS, reS, routeS, rals, + srvManager.AddServices(gvService, attrS, chrS, tS, stS, reS, routeS, apiSv1, apiSv2, cdrS, smg, coreS, services.NewEventReaderService(cfg, filterSChan, shdChan, connManager, srvDep), services.NewDNSAgent(cfg, filterSChan, shdChan, connManager, srvDep), @@ -700,8 +696,6 @@ func main() { engine.IntRPC.AddInternalRPCClient(utils.GuardianSv1, internalGuardianSChan) engine.IntRPC.AddInternalRPCClient(utils.LoaderSv1, internalLoaderSChan) engine.IntRPC.AddInternalRPCClient(utils.ResourceSv1, internalResourceSChan) - engine.IntRPC.AddInternalRPCClient(utils.Responder, internalResponderChan) - engine.IntRPC.AddInternalRPCClient(utils.SchedulerSv1, internalSchedulerSChan) engine.IntRPC.AddInternalRPCClient(utils.SessionSv1, internalSessionSChan) engine.IntRPC.AddInternalRPCClient(utils.StatSv1, internalStatSChan) engine.IntRPC.AddInternalRPCClient(utils.RouteSv1, internalRouteSChan) @@ -709,7 +703,6 @@ func main() { engine.IntRPC.AddInternalRPCClient(utils.ServiceManagerV1, internalServeManagerChan) engine.IntRPC.AddInternalRPCClient(utils.ConfigSv1, internalConfigChan) engine.IntRPC.AddInternalRPCClient(utils.CoreSv1, internalCoreSv1Chan) - engine.IntRPC.AddInternalRPCClient(utils.RALsV1, internalRALsChan) engine.IntRPC.AddInternalRPCClient(utils.RateSv1, internalRateSChan) engine.IntRPC.AddInternalRPCClient(utils.ActionSv1, internalActionSChan) engine.IntRPC.AddInternalRPCClient(utils.EeSv1, internalEEsChan) diff --git a/cmd/cgr-tester/parallel/parallel.go b/cmd/cgr-tester/parallel/parallel.go deleted file mode 100644 index feb059992..000000000 --- a/cmd/cgr-tester/parallel/parallel.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package main - -import ( - "bytes" - "fmt" - "io" - "log" - "net/http" - "sync" - - "github.com/cgrates/cgrates/utils" -) - -func main() { - log.Print("Start!") - var wg sync.WaitGroup - for i := 1; i < 1002; i++ { - wg.Add(1) - go func(index int) { - resp, err := http.Post("http://localhost:2080/jsonrpc", "application/json", bytes.NewBuffer([]byte(fmt.Sprintf(`{"method": "APIerSv1.SetAccount","params": [{"Tenant":"reglo","Account":"100%d","ActionPlanId":"PACKAGE_NEW_FOR795", "ReloadScheduler":false}], "id":%d}`, index, index)))) - if err != nil { - log.Print("Post error: ", err) - } - contents, err := io.ReadAll(resp.Body) - if err != nil { - log.Print("Body error: ", err) - } - log.Printf("SetAccount(%d): %s", index, string(contents)) - wg.Done() - }(i) - } - wg.Wait() - for index := 1; index < 1002; index++ { - resp, err := http.Post("http://localhost:2080/jsonrpc", "application/json", bytes.NewBuffer([]byte(fmt.Sprintf(`{"method": "%s","params": [{"Tenant":"reglo","Account":"100%d"}], "id":%d}`, utils.APIerSv1GetAccountActionPlan, index, index)))) - if err != nil { - log.Print("Post error: ", err) - } - contents, err := io.ReadAll(resp.Body) - if err != nil { - log.Print("Body error: ", err) - } - log.Printf("GetAccountActionPlan(%d): %s", index, string(contents)) - } - - log.Print("Done!") -} diff --git a/cmd/cgr-tester/proc_event/proc_ev.go b/cmd/cgr-tester/proc_event/proc_ev.go deleted file mode 100644 index 0d57511de..000000000 --- a/cmd/cgr-tester/proc_event/proc_ev.go +++ /dev/null @@ -1,153 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package main - -import ( - "flag" - "fmt" - "log" - "math/rand" - "net/rpc" - "net/rpc/jsonrpc" - "path" - "strconv" - "sync" - "time" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/engine" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/utils" -) - -var ( - dataDir = flag.String("data_dir", "/usr/share/cgrates", "CGR data dir path here") - requests = flag.Int("requests", 10000, "Number of requests") - gorutines = flag.Int("goroutines", 5, "Number of simultaneous goroutines") -) - -// How to run: -// 1) Start the engine with the following configuration cgr-engine -config_path=/usr/share/cgrates/conf/samples/hundred_rates -// 2) Load the data with cgr-loader cgr-loader -config_path=/usr/share/cgrates/conf/samples/hundred_rates -verbose -path=/usr/share/cgrates/tariffplans/hundredrates -// 3) Run the program with go run proc_ev.go -requests=10000 -goroutines=5 - -func main() { - flag.Parse() - var err error - var rpc *rpc.Client - var cfgPath string - var cfg *config.CGRConfig - cfgPath = path.Join(*dataDir, "conf", "samples", "cdrsv1mysql") - if cfg, err = config.NewCGRConfigFromPath(cfgPath); err != nil { - log.Fatal("Got config error: ", err.Error()) - } - if rpc, err = jsonrpc.Dial(utils.TCP, cfg.ListenCfg().RPCJSONListen); err != nil { - return - } - var sumApier float64 - var sumRateS float64 - s1 := rand.NewSource(time.Now().UnixNano()) - r1 := rand.New(s1) - // - var sls []string - for i := 100; i < 200; i++ { - sls = append(sls, strconv.Itoa(i)) - } - - var wgApier sync.WaitGroup - var wgRateS sync.WaitGroup - var apierTime time.Duration - var rateSTime time.Duration - for i := 0; i < *requests; i++ { - wgApier.Add(1) - wgRateS.Add(1) - destination := fmt.Sprintf("%+v%+v", sls[r1.Intn(100)], 1000000+rand.Intn(9999999-1000000)) - usage := fmt.Sprintf("%+vm", r1.Intn(250)) - go func() { - attrs := v1.AttrGetCost{ - Category: "call", - Tenant: "cgrates.org", - Subject: "*any", - AnswerTime: utils.MetaNow, - Destination: destination, - Usage: usage, - } - var replyApier *engine.EventCost - tNow := time.Now() - if err := rpc.Call(utils.APIerSv1GetCost, &attrs, &replyApier); err != nil { - fmt.Println(err) - return - } - apierTime += time.Now().Sub(tNow) - sumApier += *replyApier.Cost - wgApier.Done() - }() - - go func() { - argsRateS := &utils.ArgsCostForEvent{ - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: utils.UUIDSha1Prefix(), - Event: map[string]interface{}{ - utils.Category: "call", - utils.Tenant: "cgrates.org", - utils.Subject: "*any", - utils.AnswerTime: utils.MetaNow, - utils.Destination: destination, - "PrefixDestination": destination[:3], - }, - APIOpts: map[string]interface{}{ - utils.OptsRatesUsage: usage, - }, - }, - } - - var rplyRateS *utils.RateProfileCost - tNow := time.Now() - if err := rpc.Call(utils.RateSv1CostForEvent, argsRateS, &rplyRateS); err != nil { - fmt.Printf("Unexpected nil error received for RateSv1CostForEvent: %+v\n", err.Error()) - return - } - rateSTime += time.Now().Sub(tNow) - sumRateS += rplyRateS.Cost - wgRateS.Done() - }() - if i%*gorutines == 0 { - wgApier.Wait() - wgRateS.Wait() - } - - } - wgApier.Wait() - wgRateS.Wait() - fmt.Println("Cost for apier get cost : ") - fmt.Println(sumApier) - fmt.Println("Cost for RateS") - fmt.Println(sumRateS) - fmt.Println("Average ApierTime") - fmt.Println(apierTime / time.Duration(*requests)) - fmt.Println("Average RateSTime") - fmt.Println(rateSTime / time.Duration(*requests)) - fmt.Println("Total ApierTime") - fmt.Println(apierTime) - fmt.Println("Total RateSTime") - fmt.Println(rateSTime) - -} diff --git a/config/cachecfg.go b/config/cachecfg.go index 51c867bd9..98f009cb3 100644 --- a/config/cachecfg.go +++ b/config/cachecfg.go @@ -130,14 +130,6 @@ func (cCfg CacheCfg) AsTransCacheConfig() (tcCfg map[string]*ltcache.CacheConfig return } -// AddTmpCaches adds all the temporary caches configuration needed -func (cCfg *CacheCfg) AddTmpCaches() { - cCfg.Partitions[utils.CacheRatingProfilesTmp] = &CacheParamCfg{ - Limit: -1, - TTL: time.Minute, - } -} - // AsMapInterface returns the config as a map[string]interface{} func (cCfg *CacheCfg) AsMapInterface() (initialMP map[string]interface{}) { initialMP = make(map[string]interface{}) diff --git a/console/account_actionplan_get.go b/console/account_actionplan_get.go deleted file mode 100644 index b22a27f68..000000000 --- a/console/account_actionplan_get.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetAccountActionPlan{ - name: "account_actionplan_get", - rpcMethod: utils.APIerSv1GetAccountActionPlan, - rpcParams: &utils.TenantAccount{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetAccountActionPlan struct { - name string - rpcMethod string - rpcParams *utils.TenantAccount - *CommandExecuter -} - -func (self *CmdGetAccountActionPlan) Name() string { - return self.name -} - -func (self *CmdGetAccountActionPlan) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetAccountActionPlan) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &utils.TenantAccount{} - } - return self.rpcParams -} - -func (self *CmdGetAccountActionPlan) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetAccountActionPlan) RpcResult() interface{} { - s := make([]*v1.AccountActionTiming, 0) - return &s -} diff --git a/console/account_actionplan_get_test.go b/console/account_actionplan_get_test.go deleted file mode 100644 index 814aed328..000000000 --- a/console/account_actionplan_get_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - "github.com/cgrates/cgrates/utils" - - v1 "github.com/cgrates/cgrates/apier/v1" -) - -func TestCmdGetAccountActionPlan(t *testing.T) { - // commands map is initiated in init function - command := commands["account_actionplan_get"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/account_remove.go b/console/account_remove.go deleted file mode 100644 index 38ddc0274..000000000 --- a/console/account_remove.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import "github.com/cgrates/cgrates/utils" - -func init() { - c := &CmdRemoveAccount{ - name: "account_remove", - rpcMethod: utils.APIerSv1RemoveAccount, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdRemoveAccount struct { - name string - rpcMethod string - rpcParams *utils.AttrRemoveAccount - *CommandExecuter -} - -func (self *CmdRemoveAccount) Name() string { - return self.name -} - -func (self *CmdRemoveAccount) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdRemoveAccount) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &utils.AttrRemoveAccount{} - } - return self.rpcParams -} - -func (self *CmdRemoveAccount) PostprocessRpcParams() error { - return nil -} - -func (self *CmdRemoveAccount) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/account_remove_test.go b/console/account_remove_test.go deleted file mode 100644 index e546ec65d..000000000 --- a/console/account_remove_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - "github.com/cgrates/cgrates/utils" - - v1 "github.com/cgrates/cgrates/apier/v1" -) - -func TestCmdRemoveAccount(t *testing.T) { - // commands map is initiated in init function - command := commands["account_remove"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/account_set.go b/console/account_set.go deleted file mode 100644 index 5146d62f7..000000000 --- a/console/account_set.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v2 "github.com/cgrates/cgrates/apier/v2" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdAddAccount{ - name: "account_set", - rpcMethod: utils.APIerSv2SetAccount, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdAddAccount struct { - name string - rpcMethod string - rpcParams *v2.AttrSetAccount - *CommandExecuter -} - -func (self *CmdAddAccount) Name() string { - return self.name -} - -func (self *CmdAddAccount) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdAddAccount) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v2.AttrSetAccount{} - } - return self.rpcParams -} - -func (self *CmdAddAccount) PostprocessRpcParams() error { - return nil -} - -func (self *CmdAddAccount) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/account_set_test.go b/console/account_set_test.go deleted file mode 100644 index 9844e67ba..000000000 --- a/console/account_set_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v2 "github.com/cgrates/cgrates/apier/v2" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdSetAccount(t *testing.T) { - // commands map is initiated in init function - command := commands["account_set"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v2.APIerSv2)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/account_trigger_add.go b/console/account_trigger_add.go deleted file mode 100644 index 152d3a6f1..000000000 --- a/console/account_trigger_add.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdAccountAddTriggers{ - name: "account_triggers_add", - rpcMethod: utils.APIerSv1AddAccountActionTriggers, - rpcParams: &v1.AttrAddAccountActionTriggers{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdAccountAddTriggers struct { - name string - rpcMethod string - rpcParams *v1.AttrAddAccountActionTriggers - *CommandExecuter -} - -func (self *CmdAccountAddTriggers) Name() string { - return self.name -} - -func (self *CmdAccountAddTriggers) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdAccountAddTriggers) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrAddAccountActionTriggers{} - } - return self.rpcParams -} - -func (self *CmdAccountAddTriggers) PostprocessRpcParams() error { - return nil -} - -func (self *CmdAccountAddTriggers) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/account_trigger_add_test.go b/console/account_trigger_add_test.go deleted file mode 100644 index 18a8bc68f..000000000 --- a/console/account_trigger_add_test.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdAccountTriggerAdd(t *testing.T) { - // commands map is initiated in init function - command := commands["account_triggers_add"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/account_trigger_remove.go b/console/account_trigger_remove.go deleted file mode 100644 index 0b3277320..000000000 --- a/console/account_trigger_remove.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdAccountRemoveTriggers{ - name: "account_triggers_remove", - rpcMethod: utils.APIerSv1RemoveAccountActionTriggers, - rpcParams: &v1.AttrRemoveAccountActionTriggers{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdAccountRemoveTriggers struct { - name string - rpcMethod string - rpcParams *v1.AttrRemoveAccountActionTriggers - *CommandExecuter -} - -func (self *CmdAccountRemoveTriggers) Name() string { - return self.name -} - -func (self *CmdAccountRemoveTriggers) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdAccountRemoveTriggers) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrRemoveAccountActionTriggers{} - } - return self.rpcParams -} - -func (self *CmdAccountRemoveTriggers) PostprocessRpcParams() error { - return nil -} - -func (self *CmdAccountRemoveTriggers) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/account_trigger_remove_test.go b/console/account_trigger_remove_test.go deleted file mode 100644 index e2b5b15c0..000000000 --- a/console/account_trigger_remove_test.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdAccountTriggerRemove(t *testing.T) { - // commands map is initiated in init function - command := commands["account_triggers_remove"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/account_trigger_reset.go b/console/account_trigger_reset.go deleted file mode 100644 index 61a1d7701..000000000 --- a/console/account_trigger_reset.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdAccountResetTriggers{ - name: "account_triggers_reset", - rpcMethod: utils.APIerSv1ResetAccountActionTriggers, - rpcParams: &v1.AttrResetAccountActionTriggers{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdAccountResetTriggers struct { - name string - rpcMethod string - rpcParams *v1.AttrResetAccountActionTriggers - *CommandExecuter -} - -func (self *CmdAccountResetTriggers) Name() string { - return self.name -} - -func (self *CmdAccountResetTriggers) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdAccountResetTriggers) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrResetAccountActionTriggers{} - } - return self.rpcParams -} - -func (self *CmdAccountResetTriggers) PostprocessRpcParams() error { - return nil -} - -func (self *CmdAccountResetTriggers) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/account_trigger_reset_test.go b/console/account_trigger_reset_test.go deleted file mode 100644 index c9633a69b..000000000 --- a/console/account_trigger_reset_test.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdAccountTriggerReset(t *testing.T) { - // commands map is initiated in init function - command := commands["account_triggers_reset"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/account_trigger_set.go b/console/account_trigger_set.go deleted file mode 100644 index 97f5df218..000000000 --- a/console/account_trigger_set.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdAccountSetTriggers{ - name: "account_triggers_set", - rpcMethod: utils.APIerSv1SetAccountActionTriggers, - rpcParams: &v1.AttrSetAccountActionTriggers{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdAccountSetTriggers struct { - name string - rpcMethod string - rpcParams *v1.AttrSetAccountActionTriggers - *CommandExecuter -} - -func (self *CmdAccountSetTriggers) Name() string { - return self.name -} - -func (self *CmdAccountSetTriggers) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdAccountSetTriggers) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrSetAccountActionTriggers{} - } - return self.rpcParams -} - -func (self *CmdAccountSetTriggers) PostprocessRpcParams() error { - return nil -} - -func (self *CmdAccountSetTriggers) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/account_trigger_set_test.go b/console/account_trigger_set_test.go deleted file mode 100644 index 76e17df91..000000000 --- a/console/account_trigger_set_test.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdAccountTriggerSet(t *testing.T) { - // commands map is initiated in init function - command := commands["account_triggers_set"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/accounts.go b/console/accounts.go deleted file mode 100644 index 33995bd5a..000000000 --- a/console/accounts.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetAccounts{ - name: "accounts", - rpcMethod: utils.APIerSv2GetAccounts, - rpcParams: &utils.AttrGetAccounts{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetAccounts struct { - name string - rpcMethod string - rpcParams *utils.AttrGetAccounts - *CommandExecuter -} - -func (self *CmdGetAccounts) Name() string { - return self.name -} - -func (self *CmdGetAccounts) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetAccounts) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &utils.AttrGetAccounts{} - } - return self.rpcParams -} - -func (self *CmdGetAccounts) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetAccounts) RpcResult() interface{} { - a := make([]*engine.Account, 0) - return &a -} - -func (self *CmdGetAccounts) GetFormatedResult(result interface{}) string { - return GetFormatedSliceResult(result, utils.StringSet{ - utils.MinSleep: {}, - }) -} diff --git a/console/accounts_test.go b/console/accounts_test.go deleted file mode 100644 index 0f794a143..000000000 --- a/console/accounts_test.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v2 "github.com/cgrates/cgrates/apier/v2" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdAccounts(t *testing.T) { - // commands map is initiated in init function - command := commands["accounts"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v2.APIerSv2)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } - // for coverage purpose - formatedResult := command.GetFormatedResult(command.RpcResult()) - expected := GetFormatedResult(command.RpcResult(), utils.StringSet{ - utils.Usage: {}, - utils.GroupIntervalStart: {}, - utils.RateIncrement: {}, - utils.RateUnit: {}, - }) - if !reflect.DeepEqual(formatedResult, expected) { - t.Errorf("Expected <%+v>, Received <%+v>", expected, formatedResult) - } -} diff --git a/console/action_execute.go b/console/action_execute.go deleted file mode 100644 index e9d997c41..000000000 --- a/console/action_execute.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdExecuteAction{ - name: "action_execute", - rpcMethod: utils.APIerSv1ExecuteAction, - rpcParams: &utils.AttrExecuteAction{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdExecuteAction struct { - name string - rpcMethod string - rpcParams *utils.AttrExecuteAction - *CommandExecuter -} - -func (self *CmdExecuteAction) Name() string { - return self.name -} - -func (self *CmdExecuteAction) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdExecuteAction) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &utils.AttrExecuteAction{} - } - return self.rpcParams -} - -func (self *CmdExecuteAction) PostprocessRpcParams() error { - return nil -} - -func (self *CmdExecuteAction) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/action_execute_test.go b/console/action_execute_test.go deleted file mode 100644 index 39646db12..000000000 --- a/console/action_execute_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v2 "github.com/cgrates/cgrates/apier/v2" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdActionExecute(t *testing.T) { - // commands map is initiated in init function - command := commands["action_execute"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v2.APIerSv2)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/actionplan_get.go b/console/actionplan_get.go deleted file mode 100644 index 9d8c90b81..000000000 --- a/console/actionplan_get.go +++ /dev/null @@ -1,67 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetActionPlan{ - name: "actionplan_get", - rpcMethod: utils.APIerSv1GetActionPlan, - rpcParams: &v1.AttrGetActionPlan{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetActionPlan struct { - name string - rpcMethod string - rpcParams *v1.AttrGetActionPlan - *CommandExecuter -} - -func (self *CmdGetActionPlan) Name() string { - return self.name -} - -func (self *CmdGetActionPlan) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetActionPlan) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrGetActionPlan{} - } - return self.rpcParams -} - -func (self *CmdGetActionPlan) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetActionPlan) RpcResult() interface{} { - s := make([]*engine.ActionPlan, 0) - return &s -} diff --git a/console/actionplan_get_test.go b/console/actionplan_get_test.go deleted file mode 100644 index 96d37af06..000000000 --- a/console/actionplan_get_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v2 "github.com/cgrates/cgrates/apier/v2" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdActionPlanGet(t *testing.T) { - // commands map is initiated in init function - command := commands["actionplan_get"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v2.APIerSv2)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/actionplan_remove.go b/console/actionplan_remove.go deleted file mode 100644 index 3a38c33aa..000000000 --- a/console/actionplan_remove.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdRemoveActionPlan{ - name: "actionplan_remove", - rpcMethod: utils.APIerSv1RemoveActionPlan, - rpcParams: &v1.AttrGetActionPlan{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdRemoveActionPlan struct { - name string - rpcMethod string - rpcParams *v1.AttrGetActionPlan - *CommandExecuter -} - -func (self *CmdRemoveActionPlan) Name() string { - return self.name -} - -func (self *CmdRemoveActionPlan) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdRemoveActionPlan) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrGetActionPlan{} - } - return self.rpcParams -} - -func (self *CmdRemoveActionPlan) PostprocessRpcParams() error { - return nil -} - -func (self *CmdRemoveActionPlan) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/actionplan_remove_test.go b/console/actionplan_remove_test.go deleted file mode 100644 index 5e1c722e5..000000000 --- a/console/actionplan_remove_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v2 "github.com/cgrates/cgrates/apier/v2" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdActionPlanRemove(t *testing.T) { - // commands map is initiated in init function - command := commands["actionplan_remove"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v2.APIerSv2)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/actionplan_set.go b/console/actionplan_set.go deleted file mode 100644 index c67550633..000000000 --- a/console/actionplan_set.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdSetActionPlan{ - name: "actionplan_set", - rpcMethod: utils.APIerSv1SetActionPlan, - rpcParams: &v1.AttrSetActionPlan{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdSetActionPlan struct { - name string - rpcMethod string - rpcParams *v1.AttrSetActionPlan - *CommandExecuter -} - -func (self *CmdSetActionPlan) Name() string { - return self.name -} - -func (self *CmdSetActionPlan) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdSetActionPlan) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrSetActionPlan{} - } - return self.rpcParams -} - -func (self *CmdSetActionPlan) PostprocessRpcParams() error { - return nil -} - -func (self *CmdSetActionPlan) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/actionplan_set_test.go b/console/actionplan_set_test.go deleted file mode 100644 index 343e50223..000000000 --- a/console/actionplan_set_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v2 "github.com/cgrates/cgrates/apier/v2" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdActionPlanSet(t *testing.T) { - // commands map is initiated in init function - command := commands["actionplan_set"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v2.APIerSv2)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/actions.go b/console/actions.go deleted file mode 100644 index 2765a5c28..000000000 --- a/console/actions.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v2 "github.com/cgrates/cgrates/apier/v2" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetActions{ - name: "actions", - rpcMethod: utils.APIerSv2GetActions, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetActions struct { - name string - rpcMethod string - rpcParams *v2.AttrGetActions - *CommandExecuter -} - -func (self *CmdGetActions) Name() string { - return self.name -} - -func (self *CmdGetActions) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetActions) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v2.AttrGetActions{} - } - return self.rpcParams -} - -func (self *CmdGetActions) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetActions) RpcResult() interface{} { - a := make(map[string]engine.Actions, 0) - return &a -} diff --git a/console/actions_remove.go b/console/actions_remove.go deleted file mode 100644 index a0a0d8348..000000000 --- a/console/actions_remove.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdRemoveActions{ - name: "actions_remove", - rpcMethod: utils.APIerSv1RemoveActions, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdRemoveActions struct { - name string - rpcMethod string - rpcParams *v1.AttrRemoveActions - *CommandExecuter -} - -func (self *CmdRemoveActions) Name() string { - return self.name -} - -func (self *CmdRemoveActions) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdRemoveActions) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrRemoveActions{} - } - return self.rpcParams -} - -func (self *CmdRemoveActions) PostprocessRpcParams() error { - return nil -} - -func (self *CmdRemoveActions) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/actions_remove_test.go b/console/actions_remove_test.go deleted file mode 100644 index ea4be2bbb..000000000 --- a/console/actions_remove_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v2 "github.com/cgrates/cgrates/apier/v2" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdActionsRemove(t *testing.T) { - // commands map is initiated in init function - command := commands["actions_remove"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v2.APIerSv2)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/actions_test.go b/console/actions_test.go deleted file mode 100644 index d70a1e61c..000000000 --- a/console/actions_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v2 "github.com/cgrates/cgrates/apier/v2" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdActions(t *testing.T) { - // commands map is initiated in init function - command := commands["actions"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v2.APIerSv2)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/balance_add.go b/console/balance_add.go deleted file mode 100644 index 73659957a..000000000 --- a/console/balance_add.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdAddBalance{ - name: "balance_add", - rpcMethod: utils.APIerSv1AddBalance, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdAddBalance struct { - name string - rpcMethod string - rpcParams *v1.AttrAddBalance - *CommandExecuter -} - -func (self *CmdAddBalance) Name() string { - return self.name -} - -func (self *CmdAddBalance) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdAddBalance) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrAddBalance{BalanceType: utils.MetaMonetary, Overwrite: false} - } - return self.rpcParams -} - -func (self *CmdAddBalance) PostprocessRpcParams() error { - return nil -} - -func (self *CmdAddBalance) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/balance_add_test.go b/console/balance_add_test.go deleted file mode 100644 index 79cca09bd..000000000 --- a/console/balance_add_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdBalanceAdd(t *testing.T) { - // commands map is initiated in init function - command := commands["balance_add"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/balance_debit.go b/console/balance_debit.go deleted file mode 100644 index 8e025e983..000000000 --- a/console/balance_debit.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdBalanceDebit{ - name: "balance_debit", - rpcMethod: utils.APIerSv1DebitBalance, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdBalanceDebit struct { - name string - rpcMethod string - rpcParams *v1.AttrAddBalance - clientArgs []string - *CommandExecuter -} - -func (self *CmdBalanceDebit) Name() string { - return self.name -} - -func (self *CmdBalanceDebit) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdBalanceDebit) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrAddBalance{} - } - return self.rpcParams -} - -func (self *CmdBalanceDebit) PostprocessRpcParams() error { - return nil -} - -func (self *CmdBalanceDebit) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/balance_debit_test.go b/console/balance_debit_test.go deleted file mode 100644 index 025d459e1..000000000 --- a/console/balance_debit_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdBalanceDebit(t *testing.T) { - // commands map is initiated in init function - command := commands["balance_debit"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/balance_remove.go b/console/balance_remove.go deleted file mode 100644 index 75fc535bc..000000000 --- a/console/balance_remove.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdRemoveBalance{ - name: "balance_remove", - rpcMethod: utils.APIerSv1RemoveBalances, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdRemoveBalance struct { - name string - rpcMethod string - rpcParams *utils.AttrSetBalance - *CommandExecuter -} - -func (self *CmdRemoveBalance) Name() string { - return self.name -} - -func (self *CmdRemoveBalance) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdRemoveBalance) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &utils.AttrSetBalance{BalanceType: utils.MetaMonetary} - } - return self.rpcParams -} - -func (self *CmdRemoveBalance) PostprocessRpcParams() error { - return nil -} - -func (self *CmdRemoveBalance) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/balance_remove_test.go b/console/balance_remove_test.go deleted file mode 100644 index 1df36f508..000000000 --- a/console/balance_remove_test.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdBalanceRemove(t *testing.T) { - // commands map is initiated in init function - command := commands["balance_remove"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/balance_set.go b/console/balance_set.go deleted file mode 100644 index 67576bb8e..000000000 --- a/console/balance_set.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdSetBalance{ - name: "balance_set", - rpcMethod: utils.APIerSv1SetBalance, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdSetBalance struct { - name string - rpcMethod string - rpcParams *utils.AttrSetBalance - *CommandExecuter -} - -func (self *CmdSetBalance) Name() string { - return self.name -} - -func (self *CmdSetBalance) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdSetBalance) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &utils.AttrSetBalance{BalanceType: utils.MetaMonetary} - } - return self.rpcParams -} - -func (self *CmdSetBalance) PostprocessRpcParams() error { - return nil -} - -func (self *CmdSetBalance) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/balance_set_test.go b/console/balance_set_test.go deleted file mode 100644 index 1fd75fb97..000000000 --- a/console/balance_set_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdBalanceSet(t *testing.T) { - // commands map is initiated in init function - command := commands["balance_set"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/compute_actionplan_indexes.go b/console/compute_actionplan_indexes.go deleted file mode 100644 index e77a870aa..000000000 --- a/console/compute_actionplan_indexes.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdComputeActionPlanIndexes{ - name: "compute_actionplan_indexes", - rpcMethod: utils.APIerSv1ComputeActionPlanIndexes, - rpcParams: new(EmptyWrapper), - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdComputeActionPlanIndexes struct { - name string - rpcMethod string - rpcParams *EmptyWrapper - *CommandExecuter -} - -func (self *CmdComputeActionPlanIndexes) Name() string { - return self.name -} - -func (self *CmdComputeActionPlanIndexes) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdComputeActionPlanIndexes) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = new(EmptyWrapper) - } - return self.rpcParams -} - -func (self *CmdComputeActionPlanIndexes) PostprocessRpcParams() error { - return nil -} - -func (self *CmdComputeActionPlanIndexes) RpcResult() interface{} { - s := "" - return &s -} diff --git a/console/compute_actionplan_indexes_test.go b/console/compute_actionplan_indexes_test.go deleted file mode 100644 index 9851d1fae..000000000 --- a/console/compute_actionplan_indexes_test.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdComputeActionPlanIndexes(t *testing.T) { - // commands map is initiated in init function - command := commands["compute_actionplan_indexes"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - - // for coverage purpose - result := command.RpcParams(true) - if !reflect.DeepEqual(result, new(EmptyWrapper)) { - t.Errorf("Expected <%T>, Received <%T>", new(EmptyWrapper), result) - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/cost.go b/console/cost.go deleted file mode 100644 index 95ed83f10..000000000 --- a/console/cost.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetCost{ - name: "cost", - rpcMethod: utils.APIerSv1GetCost, - clientArgs: []string{utils.Tenant, utils.Category, utils.Subject, utils.AnswerTime, utils.Destination, utils.Usage}, - rpcParams: &v1.AttrGetCost{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetCost struct { - name string - rpcMethod string - rpcParams *v1.AttrGetCost - clientArgs []string - *CommandExecuter -} - -func (self *CmdGetCost) Name() string { - return self.name -} - -func (self *CmdGetCost) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetCost) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrGetCost{APIOpts: make(map[string]interface{})} - } - return self.rpcParams -} - -func (self *CmdGetCost) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetCost) RpcResult() interface{} { - return &engine.EventCost{} -} - -func (self *CmdGetCost) ClientArgs() []string { - return self.clientArgs -} - -func (self *CmdGetCost) GetFormatedResult(result interface{}) string { - return GetFormatedResult(result, utils.StringSet{ - utils.Usage: {}, - utils.GroupIntervalStart: {}, - utils.RateIncrement: {}, - utils.RateUnit: {}, - }) -} diff --git a/console/cost_test.go b/console/cost_test.go deleted file mode 100644 index 9bb44a2d4..000000000 --- a/console/cost_test.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdCost(t *testing.T) { - // commands map is initiated in init function - command := commands["cost"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } - // for coverage purpose - formatedResult := command.GetFormatedResult(command.RpcResult()) - expected := GetFormatedResult(command.RpcResult(), utils.StringSet{ - utils.Usage: {}, - utils.GroupIntervalStart: {}, - utils.RateIncrement: {}, - utils.RateUnit: {}, - }) - if !reflect.DeepEqual(formatedResult, expected) { - t.Errorf("Expected <%+v>, Received <%+v>", expected, formatedResult) - } - // for coverage purpose - result := command.ClientArgs() - expected2 := []string{utils.Tenant, utils.Category, utils.Subject, utils.AnswerTime, utils.Destination, utils.Usage} - if !reflect.DeepEqual(result, expected2) { - t.Errorf("Expected <%+v>, Received <%+v>", expected2, result) - } -} diff --git a/console/datacost.go b/console/datacost.go deleted file mode 100644 index df13f3e99..000000000 --- a/console/datacost.go +++ /dev/null @@ -1,80 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetDataCost{ - name: "datacost", - rpcMethod: utils.APIerSv1GetDataCost, - clientArgs: []string{utils.Category, utils.Tenant, utils.AccountField, utils.Subject, utils.StartTime, utils.Usage}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetDataCost struct { - name string - rpcMethod string - rpcParams *v1.AttrGetDataCost - clientArgs []string - *CommandExecuter -} - -func (self *CmdGetDataCost) Name() string { - return self.name -} - -func (self *CmdGetDataCost) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetDataCost) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrGetDataCost{Opts: make(map[string]interface{})} - } - return self.rpcParams -} - -func (self *CmdGetDataCost) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetDataCost) RpcResult() interface{} { - return &engine.DataCost{} -} - -func (self *CmdGetDataCost) ClientArgs() []string { - return self.clientArgs -} - -func (self *CmdGetDataCost) GetFormatedResult(result interface{}) string { - return GetFormatedResult(result, utils.StringSet{ - utils.Usage: {}, - utils.GroupIntervalStart: {}, - utils.RateIncrement: {}, - utils.RateUnit: {}, - }) -} diff --git a/console/datacost_test.go b/console/datacost_test.go deleted file mode 100644 index 2c2882a71..000000000 --- a/console/datacost_test.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdDatacost(t *testing.T) { - // commands map is initiated in init function - command := commands["datacost"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } - // for coverage purpose - formatedResult := command.GetFormatedResult(command.RpcResult()) - expected := GetFormatedResult(command.RpcResult(), utils.StringSet{ - utils.Usage: {}, - utils.GroupIntervalStart: {}, - utils.RateIncrement: {}, - utils.RateUnit: {}, - }) - if !reflect.DeepEqual(formatedResult, expected) { - t.Errorf("Expected <%+v>, Received <%+v>", expected, formatedResult) - } - // for coverage purpose - result := command.ClientArgs() - expected2 := []string{utils.Category, utils.Tenant, utils.AccountField, utils.Subject, utils.StartTime, utils.Usage} - if !reflect.DeepEqual(result, expected2) { - t.Errorf("Expected <%+v>, Received <%+v>", expected2, result) - } -} diff --git a/console/ping.go b/console/ping.go index 5069f4045..efa63b979 100644 --- a/console/ping.go +++ b/console/ping.go @@ -71,10 +71,6 @@ func (self *CmdApierPing) RpcMethod() string { return utils.DispatcherSv1Ping case utils.AnalyzerSLow: return utils.AnalyzerSv1Ping - case utils.SchedulerSLow: - return utils.SchedulerSv1Ping - case utils.RALsLow: - return utils.RALsV1Ping case utils.ReplicatorLow: return utils.ReplicatorSv1Ping case utils.ApierSLow: diff --git a/console/ratingplan_cost.go b/console/ratingplan_cost.go deleted file mode 100644 index e67765431..000000000 --- a/console/ratingplan_cost.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/dispatchers" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetRatingPlanCost{ - name: "ratingplan_cost", - rpcMethod: utils.RALsV1GetRatingPlansCost, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetRatingPlanCost struct { - name string - rpcMethod string - rpcParams *utils.RatingPlanCostArg - rpcResult string - *CommandExecuter -} - -func (self *CmdGetRatingPlanCost) Name() string { - return self.name -} - -func (self *CmdGetRatingPlanCost) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetRatingPlanCost) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = new(utils.RatingPlanCostArg) - } - return self.rpcParams -} - -func (self *CmdGetRatingPlanCost) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetRatingPlanCost) RpcResult() interface{} { - var s dispatchers.RatingPlanCost - return &s -} diff --git a/console/ratingplan_cost_test.go b/console/ratingplan_cost_test.go deleted file mode 100644 index 8ec9512ed..000000000 --- a/console/ratingplan_cost_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdRatingPlanCost(t *testing.T) { - // commands map is initiated in init function - command := commands["ratingplan_cost"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.RALsV1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/ratingprofile.go b/console/ratingprofile.go deleted file mode 100755 index 4bc003c63..000000000 --- a/console/ratingprofile.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetRatingProfile{ - name: "ratingprofile", - rpcMethod: utils.APIerSv1GetRatingProfile, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetRatingProfile struct { - name string - rpcMethod string - rpcParams *utils.AttrGetRatingProfile - rpcResult string - *CommandExecuter -} - -func (self *CmdGetRatingProfile) Name() string { - return self.name -} - -func (self *CmdGetRatingProfile) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetRatingProfile) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = new(utils.AttrGetRatingProfile) - } - return self.rpcParams -} - -func (self *CmdGetRatingProfile) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetRatingProfile) RpcResult() interface{} { - var s engine.RatingProfile - return &s -} diff --git a/console/ratingprofile_ids.go b/console/ratingprofile_ids.go deleted file mode 100644 index 43cad5726..000000000 --- a/console/ratingprofile_ids.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetRatingProfileIDs{ - name: "ratingprofile_ids", - rpcMethod: utils.APIerSv1GetRatingProfileIDs, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetRatingProfileIDs struct { - name string - rpcMethod string - rpcParams *utils.PaginatorWithTenant - *CommandExecuter -} - -func (self *CmdGetRatingProfileIDs) Name() string { - return self.name -} - -func (self *CmdGetRatingProfileIDs) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetRatingProfileIDs) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = new(utils.PaginatorWithTenant) - } - return self.rpcParams -} - -func (self *CmdGetRatingProfileIDs) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetRatingProfileIDs) RpcResult() interface{} { - var s []string - return &s -} diff --git a/console/ratingprofile_ids_test.go b/console/ratingprofile_ids_test.go deleted file mode 100644 index 52e449e09..000000000 --- a/console/ratingprofile_ids_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdRatingPlanIDs(t *testing.T) { - // commands map is initiated in init function - command := commands["ratingprofile_ids"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/ratingprofile_remove.go b/console/ratingprofile_remove.go deleted file mode 100644 index 5c0287c84..000000000 --- a/console/ratingprofile_remove.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdRemRatingProfile{ - name: "ratingprofile_remove", - rpcMethod: utils.APIerSv1RemoveRatingProfile, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdRemRatingProfile struct { - name string - rpcMethod string - rpcParams *v1.AttrRemoveRatingProfile - rpcResult string - *CommandExecuter -} - -func (self *CmdRemRatingProfile) Name() string { - return self.name -} - -func (self *CmdRemRatingProfile) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdRemRatingProfile) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrRemoveRatingProfile{} - } - return self.rpcParams -} - -func (self *CmdRemRatingProfile) PostprocessRpcParams() error { - if reflect.DeepEqual(self.rpcParams, &v1.AttrRemoveRatingProfile{}) { - return utils.ErrMandatoryIeMissing - } - return nil -} - -func (self *CmdRemRatingProfile) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/ratingprofile_remove_test.go b/console/ratingprofile_remove_test.go deleted file mode 100644 index c3da0a2a9..000000000 --- a/console/ratingprofile_remove_test.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdRatingPlanRem(t *testing.T) { - // commands map is initiated in init function - command := commands["ratingprofile_remove"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - -} - -func TestCmdRatingPlanRemPostprocessRpcParams(t *testing.T) { - testStruct := CmdRemRatingProfile{ - name: "", - rpcMethod: "", - rpcParams: nil, - rpcResult: "", - CommandExecuter: nil, - } - - if err := testStruct.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} - -func TestCmdRatingPlanRemPostprocessRpcParamsError(t *testing.T) { - testStruct := CmdRemRatingProfile{ - name: "", - rpcMethod: "", - rpcParams: &v1.AttrRemoveRatingProfile{}, - rpcResult: "", - CommandExecuter: nil, - } - - err := testStruct.PostprocessRpcParams() - - if err == nil || err != utils.ErrMandatoryIeMissing { - t.Fatal(err) - } - -} diff --git a/console/ratingprofile_set.go b/console/ratingprofile_set.go deleted file mode 100644 index 7cb4ab634..000000000 --- a/console/ratingprofile_set.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdSetRatingProfile{ - name: "ratingprofile_set", - rpcMethod: utils.APIerSv1SetRatingProfile, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdSetRatingProfile struct { - name string - rpcMethod string - rpcParams *utils.AttrSetRatingProfile - rpcResult string - *CommandExecuter -} - -func (self *CmdSetRatingProfile) Name() string { - return self.name -} - -func (self *CmdSetRatingProfile) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdSetRatingProfile) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = new(utils.AttrSetRatingProfile) - } - return self.rpcParams -} - -func (self *CmdSetRatingProfile) PostprocessRpcParams() error { - return nil -} - -func (self *CmdSetRatingProfile) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/ratingprofile_set_test.go b/console/ratingprofile_set_test.go deleted file mode 100644 index 8be1a9138..000000000 --- a/console/ratingprofile_set_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdRatingPlanSet(t *testing.T) { - // commands map is initiated in init function - command := commands["ratingprofile_set"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/ratingprofile_test.go b/console/ratingprofile_test.go deleted file mode 100644 index 083d09fba..000000000 --- a/console/ratingprofile_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - - "github.com/cgrates/cgrates/utils" -) - -func TestCmdRatingPlan(t *testing.T) { - // commands map is initiated in init function - command := commands["ratingprofile"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/sharedgroup.go b/console/sharedgroup.go deleted file mode 100644 index ba0468222..000000000 --- a/console/sharedgroup.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetSharedGroup{ - name: "sharedgroup", - rpcMethod: utils.APIerSv1GetSharedGroup, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetSharedGroup struct { - name string - rpcMethod string - rpcParams *StringWrapper - *CommandExecuter -} - -func (self *CmdGetSharedGroup) Name() string { - return self.name -} - -func (self *CmdGetSharedGroup) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetSharedGroup) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &StringWrapper{} - } - return self.rpcParams -} - -func (self *CmdGetSharedGroup) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetSharedGroup) RpcResult() interface{} { - return &engine.SharedGroup{} -} diff --git a/console/sharedgroup_test.go b/console/sharedgroup_test.go deleted file mode 100644 index 0b56f28ce..000000000 --- a/console/sharedgroup_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdSharedGroup(t *testing.T) { - // commands map is initiated in init function - command := commands["sharedgroup"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // for coverage purpose - result := command.RpcParams(false) - if !reflect.DeepEqual(result, new(StringWrapper)) { - t.Errorf("Expected <%T>, Received <%T>", new(StringWrapper), result) - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/trigger_remove.go b/console/trigger_remove.go deleted file mode 100644 index 551a78d23..000000000 --- a/console/trigger_remove.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdRemoveTriggers{ - name: "triggers_remove", - rpcMethod: utils.APIerSv1RemoveActionTrigger, - rpcParams: &v1.AttrRemoveActionTrigger{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdRemoveTriggers struct { - name string - rpcMethod string - rpcParams *v1.AttrRemoveActionTrigger - *CommandExecuter -} - -func (self *CmdRemoveTriggers) Name() string { - return self.name -} - -func (self *CmdRemoveTriggers) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdRemoveTriggers) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrRemoveActionTrigger{} - } - return self.rpcParams -} - -func (self *CmdRemoveTriggers) PostprocessRpcParams() error { - return nil -} - -func (self *CmdRemoveTriggers) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/trigger_remove_test.go b/console/trigger_remove_test.go deleted file mode 100644 index c95ab69bc..000000000 --- a/console/trigger_remove_test.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" - "reflect" - "strings" - "testing" -) - -func TestCmdTriggerRemove(t *testing.T) { - // commands map is initiated in init function - command := commands["triggers_remove"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/trigger_set.go b/console/trigger_set.go deleted file mode 100644 index 09255b731..000000000 --- a/console/trigger_set.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdSetTriggers{ - name: "triggers_set", - rpcMethod: utils.APIerSv1SetActionTrigger, - rpcParams: &v1.AttrSetActionTrigger{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdSetTriggers struct { - name string - rpcMethod string - rpcParams *v1.AttrSetActionTrigger - *CommandExecuter -} - -func (self *CmdSetTriggers) Name() string { - return self.name -} - -func (self *CmdSetTriggers) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdSetTriggers) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrSetActionTrigger{} - } - return self.rpcParams -} - -func (self *CmdSetTriggers) PostprocessRpcParams() error { - return nil -} - -func (self *CmdSetTriggers) RpcResult() interface{} { - var s string - return &s -} diff --git a/console/trigger_set_test.go b/console/trigger_set_test.go deleted file mode 100644 index b6594004f..000000000 --- a/console/trigger_set_test.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdTriggerSet(t *testing.T) { - // commands map is initiated in init function - command := commands["triggers_set"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} diff --git a/console/triggers.go b/console/triggers.go deleted file mode 100644 index 07b523ad2..000000000 --- a/console/triggers.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func init() { - c := &CmdGetTriggers{ - name: "triggers", - rpcMethod: utils.APIerSv1GetActionTriggers, - rpcParams: &v1.AttrGetActionTriggers{}, - } - commands[c.Name()] = c - c.CommandExecuter = &CommandExecuter{c} -} - -// Commander implementation -type CmdGetTriggers struct { - name string - rpcMethod string - rpcParams *v1.AttrGetActionTriggers - *CommandExecuter -} - -func (self *CmdGetTriggers) Name() string { - return self.name -} - -func (self *CmdGetTriggers) RpcMethod() string { - return self.rpcMethod -} - -func (self *CmdGetTriggers) RpcParams(reset bool) interface{} { - if reset || self.rpcParams == nil { - self.rpcParams = &v1.AttrGetActionTriggers{} - } - return self.rpcParams -} - -func (self *CmdGetTriggers) PostprocessRpcParams() error { - return nil -} - -func (self *CmdGetTriggers) RpcResult() interface{} { - var atr engine.ActionTriggers - return &atr -} - -func (self *CmdGetTriggers) GetFormatedResult(result interface{}) string { - return GetFormatedSliceResult(result, utils.StringSet{ - utils.MinSleep: {}, - }) -} diff --git a/console/triggers_test.go b/console/triggers_test.go deleted file mode 100644 index ccdb590ad..000000000 --- a/console/triggers_test.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package console - -import ( - "reflect" - "strings" - "testing" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/utils" -) - -func TestCmdTriggers(t *testing.T) { - // commands map is initiated in init function - command := commands["triggers"] - // verify if ApierSv1 object has method on it - m, ok := reflect.TypeOf(new(v1.APIerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // verify the type of input parameter - if ok := m.Type.In(1).AssignableTo(reflect.TypeOf(command.RpcParams(true))); !ok { - t.Fatalf("cannot assign input parameter") - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } - // for coverage purpose - formatedResult := command.GetFormatedResult(command.RpcResult()) - expected := GetFormatedSliceResult(command.RpcResult(), utils.StringSet{ - utils.MinSleep: {}, - }) - if !reflect.DeepEqual(formatedResult, expected) { - t.Errorf("Expected <%+v>, Received <%+v>", expected, formatedResult) - } -} diff --git a/dispatchers/rals.go b/dispatchers/rals.go deleted file mode 100644 index 0d0d10c97..000000000 --- a/dispatchers/rals.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package dispatchers - -import ( - "time" - - "github.com/cgrates/cgrates/utils" -) - -func (dS *DispatcherService) RALsV1Ping(args *utils.CGREvent, rpl *string) (err error) { - if args == nil { - args = new(utils.CGREvent) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.RALsV1Ping, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), args.Time); err != nil { - return - } - } - return dS.Dispatch(args, utils.MetaRALs, utils.RALsV1Ping, args, rpl) -} - -func (dS *DispatcherService) RALsV1GetRatingPlansCost(args *utils.RatingPlanCostArg, rpl *RatingPlanCost) (err error) { - tenant := dS.cfg.GeneralCfg().DefaultTenant - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.RALsV1GetRatingPlansCost, tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: tenant, - APIOpts: args.APIOpts, - }, utils.MetaRALs, utils.RALsV1GetRatingPlansCost, args, rpl) -} diff --git a/dispatchers/rals_it_test.go b/dispatchers/rals_it_test.go deleted file mode 100644 index 41c287543..000000000 --- a/dispatchers/rals_it_test.go +++ /dev/null @@ -1,102 +0,0 @@ -// +build integration - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package dispatchers - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/utils" -) - -var sTestsDspRALs = []func(t *testing.T){ - testDspRALsPing, - testDspRALsGetRatingPlanCost, -} - -//Test start here -func TestDspRALsIT(t *testing.T) { - var config1, config2, config3 string - switch *dbType { - case utils.MetaInternal: - t.SkipNow() - case utils.MetaMySQL: - config1 = "all_mysql" - config2 = "all2_mysql" - config3 = "dispatchers_mysql" - case utils.MetaMongo: - config1 = "all_mongo" - config2 = "all2_mongo" - config3 = "dispatchers_mongo" - case utils.MetaPostgres: - t.SkipNow() - default: - t.Fatal("Unknown Database type") - } - - dispDIR := "dispatchers" - if *encoding == utils.MetaGOB { - dispDIR += "_gob" - } - testDsp(t, sTestsDspRALs, "TestDspRALsITMySQL", config1, config2, config3, "tutorial", "oldtutorial", dispDIR) -} - -func testDspRALsPing(t *testing.T) { - var reply string - if err := allEngine.RPC.Call(utils.RALsV1Ping, new(utils.CGREvent), &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } - if err := dispEngine.RPC.Call(utils.RALsV1Ping, &utils.CGREvent{ - Tenant: "cgrates.org", - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "rals12345", - }, - }, &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } -} - -func testDspRALsGetRatingPlanCost(t *testing.T) { - arg := &utils.RatingPlanCostArg{ - Destination: "1002", - RatingPlanIDs: []string{"RP_1001", "RP_1002"}, - SetupTime: utils.MetaNow, - Usage: "1h", - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "rals12345", - }, - } - var reply RatingPlanCost - if err := dispEngine.RPC.Call(utils.RALsV1GetRatingPlansCost, arg, &reply); err != nil { - t.Error(err) - } else if reply.RatingPlanID != "RP_1001" { - t.Error("Unexpected RatingPlanID: ", reply.RatingPlanID) - } else if *reply.EventCost.Cost != 6.5118 { - t.Error("Unexpected Cost: ", *reply.EventCost.Cost) - } else if *reply.EventCost.Usage != time.Hour { - t.Error("Unexpected Usage: ", *reply.EventCost.Usage) - } -} diff --git a/dispatchers/replicator.go b/dispatchers/replicator.go index 6c9fd10d1..0662f86ff 100644 --- a/dispatchers/replicator.go +++ b/dispatchers/replicator.go @@ -39,23 +39,6 @@ func (dS *DispatcherService) ReplicatorSv1Ping(args *utils.CGREvent, rpl *string return dS.Dispatch(args, utils.MetaReplicator, utils.ReplicatorSv1Ping, args, rpl) } -func (dS *DispatcherService) ReplicatorSv1GetAccount(args *utils.StringWithAPIOpts, rpl *engine.Account) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetAccount, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetAccount, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1GetDestination(args *utils.StringWithAPIOpts, rpl *engine.Destination) (err error) { if args == nil { args = new(utils.StringWithAPIOpts) @@ -233,142 +216,6 @@ func (dS *DispatcherService) ReplicatorSv1GetResourceProfile(args *utils.TenantI }, utils.MetaReplicator, utils.ReplicatorSv1GetResourceProfile, args, reply) } -func (dS *DispatcherService) ReplicatorSv1GetActionTriggers(args *utils.StringWithAPIOpts, rpl *engine.ActionTriggers) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetActionTriggers, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetActionTriggers, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1GetSharedGroup(args *utils.StringWithAPIOpts, rpl *engine.SharedGroup) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetSharedGroup, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetSharedGroup, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1GetActions(args *utils.StringWithAPIOpts, rpl *engine.Actions) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetActions, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetActions, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1GetActionPlan(args *utils.StringWithAPIOpts, rpl *engine.ActionPlan) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetActionPlan, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetActionPlan, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1GetAllActionPlans(args *utils.StringWithAPIOpts, rpl *map[string]*engine.ActionPlan) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetAllActionPlans, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetAllActionPlans, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1GetAccountActionPlans(args *utils.StringWithAPIOpts, rpl *[]string) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetAccountActionPlans, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetAccountActionPlans, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1GetRatingPlan(args *utils.StringWithAPIOpts, rpl *engine.RatingPlan) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetRatingPlan, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetRatingPlan, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1GetRatingProfile(args *utils.StringWithAPIOpts, rpl *engine.RatingProfile) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1GetRatingProfile, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1GetRatingProfile, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1GetRouteProfile(args *utils.TenantIDWithAPIOpts, reply *engine.RouteProfile) (err error) { tnt := dS.cfg.GeneralCfg().DefaultTenant if args.TenantID != nil && args.TenantID.Tenant != utils.EmptyString { @@ -563,23 +410,6 @@ func (dS *DispatcherService) ReplicatorSv1SetDestination(args *engine.Destinatio }, utils.MetaReplicator, utils.ReplicatorSv1SetDestination, args, rpl) } -func (dS *DispatcherService) ReplicatorSv1SetAccount(args *engine.AccountWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = &engine.AccountWithAPIOpts{} - } - tenant := utils.FirstNonEmpty(utils.SplitConcatenatedKey(args.ID)[0], dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1SetAccount, tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1SetAccount, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1SetReverseDestination(args *engine.DestinationWithAPIOpts, rpl *string) (err error) { if args == nil { args = &engine.DestinationWithAPIOpts{} @@ -699,40 +529,6 @@ func (dS *DispatcherService) ReplicatorSv1SetResourceProfile(args *engine.Resour }, utils.MetaReplicator, utils.ReplicatorSv1SetResourceProfile, args, rpl) } -func (dS *DispatcherService) ReplicatorSv1SetActionTriggers(args *engine.SetActionTriggersArgWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = &engine.SetActionTriggersArgWithAPIOpts{} - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1SetActionTriggers, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1SetActionTriggers, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1SetSharedGroup(args *engine.SharedGroupWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = &engine.SharedGroupWithAPIOpts{} - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1SetSharedGroup, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1SetSharedGroup, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1SetActions(args *engine.SetActionsArgsWithAPIOpts, rpl *string) (err error) { if args == nil { args = &engine.SetActionsArgsWithAPIOpts{} @@ -750,40 +546,6 @@ func (dS *DispatcherService) ReplicatorSv1SetActions(args *engine.SetActionsArgs }, utils.MetaReplicator, utils.ReplicatorSv1SetActions, args, rpl) } -func (dS *DispatcherService) ReplicatorSv1SetRatingPlan(args *engine.RatingPlanWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = &engine.RatingPlanWithAPIOpts{} - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1SetRatingPlan, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1SetRatingPlan, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1SetRatingProfile(args *engine.RatingProfileWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = &engine.RatingProfileWithAPIOpts{} - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1SetRatingProfile, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1SetRatingProfile, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1SetRouteProfile(args *engine.RouteProfileWithAPIOpts, rpl *string) (err error) { if args == nil { args = &engine.RouteProfileWithAPIOpts{} @@ -886,40 +648,6 @@ func (dS *DispatcherService) ReplicatorSv1SetActionProfile(args *engine.ActionPr }, utils.MetaReplicator, utils.ReplicatorSv1SetActionProfile, args, rpl) } -func (dS *DispatcherService) ReplicatorSv1SetActionPlan(args *engine.SetActionPlanArgWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = &engine.SetActionPlanArgWithAPIOpts{} - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1SetActionPlan, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1SetActionPlan, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1SetAccountActionPlans(args *engine.SetAccountActionPlansArgWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = &engine.SetAccountActionPlansArgWithAPIOpts{} - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1SetAccountActionPlans, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1SetAccountActionPlans, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1SetDispatcherHost(args *engine.DispatcherHostWithAPIOpts, rpl *string) (err error) { if args == nil { args = &engine.DispatcherHostWithAPIOpts{} @@ -988,23 +716,6 @@ func (dS *DispatcherService) ReplicatorSv1SetLoadIDs(args *utils.LoadIDsWithAPIO }, utils.MetaReplicator, utils.ReplicatorSv1SetLoadIDs, args, rpl) } -func (dS *DispatcherService) ReplicatorSv1RemoveAccount(args *utils.StringWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1RemoveAccount, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1RemoveAccount, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1RemoveStatQueue(args *utils.TenantIDWithAPIOpts, rpl *string) (err error) { if args == nil { args = &utils.TenantIDWithAPIOpts{} @@ -1124,40 +835,6 @@ func (dS *DispatcherService) ReplicatorSv1RemoveResourceProfile(args *utils.Tena }, utils.MetaReplicator, utils.ReplicatorSv1RemoveResourceProfile, args, rpl) } -func (dS *DispatcherService) ReplicatorSv1RemoveActionTriggers(args *utils.StringWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1RemoveActionTriggers, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1RemoveActionTriggers, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1RemoveSharedGroup(args *utils.StringWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1RemoveSharedGroup, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1RemoveSharedGroup, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1RemoveActions(args *utils.StringWithAPIOpts, rpl *string) (err error) { if args == nil { args = new(utils.StringWithAPIOpts) @@ -1175,74 +852,6 @@ func (dS *DispatcherService) ReplicatorSv1RemoveActions(args *utils.StringWithAP }, utils.MetaReplicator, utils.ReplicatorSv1RemoveActions, args, rpl) } -func (dS *DispatcherService) ReplicatorSv1RemoveActionPlan(args *utils.StringWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1RemoveActionPlan, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1RemoveActionPlan, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1RemAccountActionPlans(args *engine.RemAccountActionPlansArgsWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = &engine.RemAccountActionPlansArgsWithAPIOpts{} - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1RemAccountActionPlans, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1RemAccountActionPlans, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1RemoveRatingPlan(args *utils.StringWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1RemoveRatingPlan, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1RemoveRatingPlan, args, rpl) -} - -func (dS *DispatcherService) ReplicatorSv1RemoveRatingProfile(args *utils.StringWithAPIOpts, rpl *string) (err error) { - if args == nil { - args = new(utils.StringWithAPIOpts) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ReplicatorSv1RemoveRatingProfile, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaReplicator, utils.ReplicatorSv1RemoveRatingProfile, args, rpl) -} - func (dS *DispatcherService) ReplicatorSv1RemoveRouteProfile(args *utils.TenantIDWithAPIOpts, rpl *string) (err error) { if args == nil { args = &utils.TenantIDWithAPIOpts{} diff --git a/dispatchers/responder.go b/dispatchers/responder.go deleted file mode 100644 index bbefd8284..000000000 --- a/dispatchers/responder.go +++ /dev/null @@ -1,123 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package dispatchers - -import ( - "time" - - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -// ResponderPing interogates Responder server responsible to process the event -func (dS *DispatcherService) ResponderPing(args *utils.CGREvent, - reply *string) (err error) { - if args == nil { - args = new(utils.CGREvent) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ResponderPing, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), args.Time); err != nil { - return - } - } - return dS.Dispatch(args, utils.MetaResponder, utils.ResponderPing, args, reply) -} - -func (dS *DispatcherService) ResponderGetCost(args *engine.CallDescriptorWithAPIOpts, - reply *engine.CallCost) (err error) { - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ResponderGetCost, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(args.AsCGREvent(args.APIOpts), utils.MetaResponder, utils.ResponderGetCost, args, reply) -} - -func (dS *DispatcherService) ResponderDebit(args *engine.CallDescriptorWithAPIOpts, - reply *engine.CallCost) (err error) { - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ResponderDebit, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(args.AsCGREvent(args.APIOpts), utils.MetaResponder, utils.ResponderDebit, args, reply) -} - -func (dS *DispatcherService) ResponderMaxDebit(args *engine.CallDescriptorWithAPIOpts, - reply *engine.CallCost) (err error) { - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ResponderMaxDebit, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(args.AsCGREvent(args.APIOpts), utils.MetaResponder, utils.ResponderMaxDebit, args, reply) -} - -func (dS *DispatcherService) ResponderRefundIncrements(args *engine.CallDescriptorWithAPIOpts, - reply *engine.Account) (err error) { - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ResponderRefundIncrements, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(args.AsCGREvent(args.APIOpts), utils.MetaResponder, utils.ResponderRefundIncrements, args, reply) -} - -func (dS *DispatcherService) ResponderRefundRounding(args *engine.CallDescriptorWithAPIOpts, - reply *float64) (err error) { - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ResponderRefundRounding, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(args.AsCGREvent(args.APIOpts), utils.MetaResponder, utils.ResponderRefundRounding, args, reply) -} - -func (dS *DispatcherService) ResponderGetMaxSessionTime(args *engine.CallDescriptorWithAPIOpts, - reply *time.Duration) (err error) { - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ResponderGetMaxSessionTime, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(args.AsCGREvent(args.APIOpts), utils.MetaResponder, utils.ResponderGetMaxSessionTime, args, reply) -} - -func (dS *DispatcherService) ResponderShutdown(args *utils.TenantWithAPIOpts, - reply *string) (err error) { - tnt := utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.ResponderShutdown, tnt, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: tnt, - APIOpts: args.APIOpts, - }, utils.MetaResponder, utils.ResponderShutdown, args, reply) -} diff --git a/dispatchers/scheduler.go b/dispatchers/scheduler.go deleted file mode 100644 index 56e7c1120..000000000 --- a/dispatchers/scheduler.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package dispatchers - -import ( - "time" - - "github.com/cgrates/cgrates/utils" -) - -func (dS *DispatcherService) SchedulerSv1Ping(args *utils.CGREvent, reply *string) (err error) { - if args == nil { - args = new(utils.CGREvent) - } - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.SchedulerSv1Ping, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), args.Time); err != nil { - return - } - } - return dS.Dispatch(args, utils.MetaScheduler, utils.SchedulerSv1Ping, args, reply) -} - -func (dS *DispatcherService) SchedulerSv1Reload(args *utils.CGREvent, reply *string) (err error) { - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.SchedulerSv1Ping, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), args.Time); err != nil { - return - } - } - return dS.Dispatch(args, utils.MetaScheduler, utils.SchedulerSv1Reload, args, reply) -} - -func (dS *DispatcherService) SchedulerSv1ExecuteActions(args *utils.AttrsExecuteActions, reply *string) (err error) { - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.SchedulerSv1ExecuteActions, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaScheduler, utils.SchedulerSv1ExecuteActions, args, reply) -} - -func (dS *DispatcherService) SchedulerSv1ExecuteActionPlans(args *utils.AttrsExecuteActionPlans, reply *string) (err error) { - args.Tenant = utils.FirstNonEmpty(args.Tenant, dS.cfg.GeneralCfg().DefaultTenant) - if len(dS.cfg.DispatcherSCfg().AttributeSConns) != 0 { - if err = dS.authorize(utils.SchedulerSv1ExecuteActionPlans, args.Tenant, - utils.IfaceAsString(args.APIOpts[utils.OptsAPIKey]), utils.TimePointer(time.Now())); err != nil { - return - } - } - return dS.Dispatch(&utils.CGREvent{ - Tenant: args.Tenant, - APIOpts: args.APIOpts, - }, utils.MetaScheduler, utils.SchedulerSv1ExecuteActionPlans, args, reply) -} diff --git a/dispatchers/scheduler_it_test.go b/dispatchers/scheduler_it_test.go deleted file mode 100644 index 85b6f47e5..000000000 --- a/dispatchers/scheduler_it_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// +build integration - -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package dispatchers - -import ( - "testing" - - "github.com/cgrates/cgrates/utils" -) - -var sTestsDspSched = []func(t *testing.T){ - testDspSchedPing, -} - -//Test start here - -func TestDspSchedulerS(t *testing.T) { - var config1, config2, config3 string - switch *dbType { - case utils.MetaInternal: - t.SkipNow() - case utils.MetaMySQL: - config1 = "all_mysql" - config2 = "all2_mysql" - config3 = "dispatchers_mysql" - case utils.MetaMongo: - config1 = "all_mongo" - config2 = "all2_mongo" - config3 = "dispatchers_mongo" - case utils.MetaPostgres: - t.SkipNow() - default: - t.Fatal("Unknown Database type") - } - - dispDIR := "dispatchers" - if *encoding == utils.MetaGOB { - dispDIR += "_gob" - } - testDsp(t, sTestsDspSched, "TestDspSchedulerSTMySQL", config1, config2, config3, "tutorial", "oldtutorial", dispDIR) -} - -func testDspSchedPing(t *testing.T) { - var reply string - if err := allEngine.RPC.Call(utils.SchedulerSv1Ping, new(utils.CGREvent), &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } - if err := dispEngine.RPC.Call(utils.SchedulerSv1Ping, &utils.CGREvent{ - Tenant: "cgrates.org", - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "sched12345", - }, - }, &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } -} diff --git a/engine/account_test.go b/engine/account_test.go deleted file mode 100644 index 221b89974..000000000 --- a/engine/account_test.go +++ /dev/null @@ -1,2369 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ -package engine - -import ( - "reflect" - "testing" - "time" - - "github.com/cgrates/cgrates/utils" -) - -var ( - NAT = &Destination{Id: "NAT", - Prefixes: []string{"0257", "0256", "0723"}} - RET = &Destination{Id: "RET", - Prefixes: []string{"0723", "0724"}} -) - -func TestBalanceStoreRestore(t *testing.T) { - b := &Balance{Value: 14, Weight: 1, Uuid: "test", - ExpirationDate: time.Date(2013, time.July, 15, 17, 48, 0, 0, time.UTC)} - marsh := NewCodecMsgpackMarshaler() - output, err := marsh.Marshal(b) - if err != nil { - t.Error("Error storing balance: ", err) - } - b1 := &Balance{} - err = marsh.Unmarshal(output, b1) - if err != nil { - t.Error("Error restoring balance: ", err) - } - //t.Logf("INITIAL: %+v", b) - if !b.Equal(b1) { - t.Errorf("Balance store/restore failed: expected %+v was %+v", b, b1) - } -} - -func TestBalanceStoreRestoreZero(t *testing.T) { - b := &Balance{} - - output, err := marsh.Marshal(b) - if err != nil { - t.Error("Error storing balance: ", err) - } - b1 := &Balance{} - err = marsh.Unmarshal(output, b1) - if err != nil { - t.Error("Error restoring balance: ", err) - } - if !b.Equal(b1) { - t.Errorf("Balance store/restore failed: expected %v was %v", b, b1) - } -} - -func TestBalancesStoreRestore(t *testing.T) { - bc := Balances{&Balance{Value: 14, - ExpirationDate: time.Date(2013, time.July, 15, 17, 48, 0, 0, time.UTC)}, - &Balance{Value: 1024}} - output, err := marsh.Marshal(bc) - if err != nil { - t.Error("Error storing balance chain: ", err) - } - bc1 := Balances{} - err = marsh.Unmarshal(output, &bc1) - if err != nil { - t.Error("Error restoring balance chain: ", err) - } - if !bc.Equal(bc1) { - t.Errorf("Balance chain store/restore failed: expected %v was %v", bc, bc1) - } -} - -func TestAccountStorageStoreRestore(t *testing.T) { - b1 := &Balance{Value: 10, Weight: 10, - DestinationIDs: utils.StringMap{"NAT": true}} - b2 := &Balance{Value: 100, Weight: 20, - DestinationIDs: utils.StringMap{"RET": true}} - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1, b2}, - utils.MetaMonetary: {&Balance{Value: 21}}}} - dm.SetAccount(rifsBalance) - ub1, err := dm.GetAccount("other") - if err != nil || - !ub1.BalanceMap[utils.MetaMonetary].Equal(rifsBalance.BalanceMap[utils.MetaMonetary]) { - t.Log("UB: ", ub1) - t.Errorf("Expected %v was %v", rifsBalance, ub1) - } -} - -func TestGetSecondsForPrefix(t *testing.T) { - b1 := &Balance{Value: 10, Weight: 10, - DestinationIDs: utils.StringMap{"NAT": true}} - b2 := &Balance{Value: 100, Weight: 20, - DestinationIDs: utils.StringMap{"RET": true}} - ub1 := &Account{ID: "CUSTOMER_1:rif", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1, b2}, - utils.MetaMonetary: {&Balance{Value: 200}}}} - cd := &CallDescriptor{ - Category: "0", - Tenant: "vdf", - TimeStart: time.Date(2013, 10, 4, 15, 46, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 10, 4, 15, 46, 10, 0, time.UTC), - LoopIndex: 0, - DurationIndex: 10 * time.Second, - Destination: "0723", - ToR: utils.MetaVoice, - } - seconds, credit, bucketList := ub1.getCreditForPrefix(cd) - expected := 110 * time.Second - if credit != 200 || seconds != expected || bucketList[0].Weight < bucketList[1].Weight { - t.Log(seconds, credit, bucketList) - t.Errorf("Expected %v was %v", expected, seconds) - } -} - -func TestGetSpecialPricedSeconds(t *testing.T) { - b1 := &Balance{Value: 10, Weight: 10, - DestinationIDs: utils.StringMap{"NAT": true}, RatingSubject: "minu"} - b2 := &Balance{Value: 100, Weight: 20, - DestinationIDs: utils.StringMap{"RET": true}, RatingSubject: "minu"} - - ub1 := &Account{ - ID: "OUT:CUSTOMER_1:rif", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1, b2}, - utils.MetaMonetary: {&Balance{Value: 21}}, - }, - } - cd := &CallDescriptor{ - Category: "0", - Tenant: "vdf", - TimeStart: time.Date(2013, 10, 4, 15, 46, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 10, 4, 15, 46, 60, 0, time.UTC), - LoopIndex: 0, - Destination: "0723", - ToR: utils.MetaVoice, - } - seconds, credit, bucketList := ub1.getCreditForPrefix(cd) - expected := 20 * time.Second - if credit != 0 || seconds != expected || - len(bucketList) != 2 || bucketList[0].Weight < bucketList[1].Weight { - t.Errorf("Expected %v was %v", expected, seconds) - } -} - -func TestAccountStorageStore(t *testing.T) { - b1 := &Balance{Value: 10, Weight: 10, - DestinationIDs: utils.StringMap{"NAT": true}} - b2 := &Balance{Value: 100, Weight: 20, DestinationIDs: utils.StringMap{"RET": true}} - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1, b2}, - utils.MetaMonetary: {&Balance{Value: 21}}}} - dm.SetAccount(rifsBalance) - result, err := dm.GetAccount(rifsBalance.ID) - if err != nil || rifsBalance.ID != result.ID || - len(rifsBalance.BalanceMap[utils.MetaVoice]) < 2 || - len(result.BalanceMap[utils.MetaVoice]) < 2 || - !(rifsBalance.BalanceMap[utils.MetaVoice][0].Equal(result.BalanceMap[utils.MetaVoice][0])) || - !(rifsBalance.BalanceMap[utils.MetaVoice][1].Equal(result.BalanceMap[utils.MetaVoice][1])) || - !rifsBalance.BalanceMap[utils.MetaMonetary].Equal(result.BalanceMap[utils.MetaMonetary]) { - t.Errorf("Expected %s was %s", utils.ToIJSON(rifsBalance), utils.ToIJSON(result)) - } -} - -func TestDebitCreditZeroSecond(t *testing.T) { - b1 := &Balance{ - Uuid: "testb", Value: 10 * float64(time.Second), Weight: 10, - DestinationIDs: utils.StringMap{"NAT": true}, - RatingSubject: "*zero1s"} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{Rating: &RIRate{ - Rates: RateGroups{&RGRate{GroupIntervalStart: 0, - Value: 100, RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - Destination: "0723045326", - Category: "0", - ToR: utils.MetaVoice, - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1}, - utils.MetaMonetary: {&Balance{ - Categories: utils.NewStringMap("0"), Value: 21}}}} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Fatal("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testb" { - t.Logf("%+v", cc.Timespans[0]) - t.Error("Error setting balance id to increment: ", cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 0 || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 21 { - t.Error("Error extracting minutes from balance: ", rifsBalance.BalanceMap[utils.MetaVoice][0]) - } -} - -func TestDebitCreditBlocker(t *testing.T) { - b1 := &Balance{Uuid: "testa", Value: 0.1152, - Weight: 20, DestinationIDs: utils.StringMap{"NAT": true}, - RatingSubject: "passmonde", Blocker: true} - b2 := &Balance{Uuid: utils.MetaDefault, Value: 1.5, Weight: 0} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ConnectFee: 0.15, - Rates: RateGroups{&RGRate{GroupIntervalStart: 0, - Value: 0.1, RateIncrement: time.Second, - RateUnit: time.Second}}}}, - }, - }, - deductConnectFee: true, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - Destination: "0723045326", - Category: "0", - ToR: utils.MetaVoice, - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{utils.MetaMonetary: {b1, b2}}} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, true, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if len(cc.Timespans) != 0 { - t.Error("Wrong call cost: ", utils.ToIJSON(cc)) - } - if rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 0.1152 || - rifsBalance.BalanceMap[utils.MetaMonetary][1].GetValue() != 1.5 { - t.Error("should not have touched the balances: ", - utils.ToIJSON(rifsBalance.BalanceMap[utils.MetaMonetary])) - } -} - -func TestDebitFreeEmpty(t *testing.T) { - cc := &CallCost{ - Destination: "112", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{Rating: &RIRate{ - ConnectFee: 0, Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 0, - RateIncrement: time.Second, - RateUnit: time.Second}}}}, - }, - }, - deductConnectFee: true, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - Tenant: "CUSTOMER_1", - Subject: "rif:from:tm", - Destination: "112", - Category: "0", - ToR: utils.MetaVoice, - testCallcost: cc, - } - // empty account - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{utils.MetaMonetary: {}}} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, true, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if len(cc.Timespans) == 0 || cc.Cost != 0 { - t.Error("Wrong call cost: ", utils.ToIJSON(cc)) - } - if len(rifsBalance.BalanceMap[utils.MetaMonetary]) != 0 { - t.Error("should not have touched the balances: ", - utils.ToIJSON(rifsBalance.BalanceMap[utils.MetaMonetary])) - } -} - -func TestDebitCreditZeroMinute(t *testing.T) { - b1 := &Balance{Uuid: "testb", Value: 70 * float64(time.Second), - Weight: 10, DestinationIDs: utils.StringMap{"NAT": true}, - RatingSubject: "*zero1m"} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 100, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - Destination: "0723045326", - Category: "0", - ToR: utils.MetaVoice, - testCallcost: cc, - } - rifsBalance := &Account{ - ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1}, - utils.MetaMonetary: {&Balance{Value: 21}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - //t.Logf("%+v", cc.Timespans) - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testb" || - cc.Timespans[0].Increments[0].Duration != time.Minute { - t.Errorf("Error setting balance id to increment: %s", - utils.ToJSON(cc)) - } - if rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 10*float64(time.Second) || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 21 { - t.Errorf("Error extracting minutes from balance: %s", - utils.ToJSON(rifsBalance.BalanceMap[utils.MetaVoice][0])) - } -} - -func TestDebitCreditZeroMixedMinute(t *testing.T) { - b1 := &Balance{ - Uuid: "testm", Value: 70 * float64(time.Second), - DestinationIDs: utils.StringMap{"NAT": true}, - RatingSubject: "*zero1m", Weight: 5} - b2 := &Balance{Uuid: "tests", Value: 10 * float64(time.Second), Weight: 10, - DestinationIDs: utils.StringMap{"NAT": true}, RatingSubject: "*zero1s"} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 20, 0, time.UTC), - ratingInfo: &RatingInfo{}, - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 100, RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.Timespans[0].GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1, b2}, - utils.MetaMonetary: {&Balance{Value: 21}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "tests" || - cc.Timespans[1].Increments[0].BalanceInfo.Unit.UUID != "testm" { - t.Error("Error setting balance id to increment: ", cc.Timespans) - } - if rifsBalance.BalanceMap[utils.MetaVoice][1].GetValue() != 0 || - rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 10*float64(time.Second) || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 21 { - t.Logf("TS0: %+v", cc.Timespans[0]) - t.Logf("TS1: %+v", cc.Timespans[1]) - t.Errorf("Error extracting minutes from balance: %+v", rifsBalance.BalanceMap[utils.MetaVoice][1]) - } -} - -func TestDebitCreditNoCredit(t *testing.T) { - b1 := &Balance{Uuid: "testb", Value: 70 * float64(time.Second), - DestinationIDs: utils.StringMap{"NAT": true}, - RatingSubject: "*zero1m", Weight: 10} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 100, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 20, 0, time.UTC), - DurationIndex: 10 * time.Second, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 100, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[1].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err == nil { - t.Error("Showing no enough credit error ") - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testb" || - cc.Timespans[0].Increments[0].Duration != time.Minute { - t.Error("Error setting balance id to increment: ", - cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 10*float64(time.Second) { - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaVoice][0]) - } - if len(cc.Timespans) != 1 || - cc.Timespans[0].GetDuration() != time.Minute { - t.Error("Error truncating extra timespans: ", cc.Timespans) - } -} - -func TestDebitCreditHasCredit(t *testing.T) { - b1 := &Balance{Uuid: "testb", Value: 70 * float64(time.Second), - DestinationIDs: utils.StringMap{"NAT": true}, - Weight: 10, RatingSubject: "*zero1m"} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 1, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 20, 0, time.UTC), - DurationIndex: 10 * time.Second, - RateInterval: &RateInterval{ - Rating: &RIRate{Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 1, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[1].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1}, - utils.MetaMonetary: {&Balance{Uuid: "moneya", Value: 110}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testb" || - cc.Timespans[0].Increments[0].Duration != time.Minute { - t.Error("Error setting balance id to increment: ", cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 10*float64(time.Second) || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 30 { - t.Errorf("Error extracting minutes from balance: %+v, %+v", - rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue(), - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } - if len(cc.Timespans) != 3 || cc.Timespans[0].GetDuration() != time.Minute { - t.Error("Error truncating extra timespans: ", cc.Timespans) - } -} - -func TestDebitCreditSplitMinutesMoney(t *testing.T) { - b1 := &Balance{Uuid: "testb", - Value: 10 * float64(time.Second), - DestinationIDs: utils.StringMap{"NAT": true}, - Weight: 10, RatingSubject: "*zero1s"} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 20, 0, time.UTC), - DurationIndex: 0, - ratingInfo: &RatingInfo{}, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 1, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1}, - utils.MetaMonetary: {&Balance{Uuid: "moneya", Value: 50}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testb" || - cc.Timespans[0].Increments[0].Duration != time.Second { - t.Error("Error setting balance id to increment: ", - cc.Timespans[0].Increments[0].Duration) - } - if rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 0 || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 30 { - t.Errorf("Error extracting minutes from balance: %+v, %+v", - rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue(), - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } - if len(cc.Timespans) != 2 || - cc.Timespans[0].GetDuration() != 10*time.Second || - cc.Timespans[1].GetDuration() != 20*time.Second { - t.Error("Error truncating extra timespans: ", - cc.Timespans[1].GetDuration()) - } -} - -func TestDebitCreditMoreTimespans(t *testing.T) { - b1 := &Balance{Uuid: "testb", - Value: 150 * float64(time.Second), - DestinationIDs: utils.StringMap{"NAT": true}, - Weight: 10, RatingSubject: "*zero1m"} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 100, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 20, 0, time.UTC), - DurationIndex: 10 * time.Second, - RateInterval: &RateInterval{ - Rating: &RIRate{Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 100, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[1].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testb" || - cc.Timespans[0].Increments[0].Duration != time.Minute { - t.Error("Error setting balance id to increment: ", - cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 30*float64(time.Second) { - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaVoice][0]) - } -} - -func TestDebitCreditMoreTimespansMixed(t *testing.T) { - b1 := &Balance{Uuid: "testb", Value: 70 * float64(time.Second), - DestinationIDs: utils.StringMap{"NAT": true}, - Weight: 10, RatingSubject: "*zero1m"} - b2 := &Balance{Uuid: "testa", Value: 150 * float64(time.Second), - DestinationIDs: utils.StringMap{"NAT": true}, - Weight: 5, RatingSubject: "*zero1s"} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 100, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 20, 0, time.UTC), - DurationIndex: 10 * time.Second, - RateInterval: &RateInterval{ - Rating: &RIRate{Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 100, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[1].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ - ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1, b2}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testb" || - cc.Timespans[0].Increments[0].Duration != time.Minute { - t.Error("Error setting balance id to increment: ", - cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 10*float64(time.Second) || - rifsBalance.BalanceMap[utils.MetaVoice][1].GetValue() != 130*float64(time.Second) { - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaVoice][1], cc.Timespans[1]) - } -} - -func TestDebitCreditNoConectFeeCredit(t *testing.T) { - b1 := &Balance{Uuid: "testb", Value: 70 * float64(time.Second), - DestinationIDs: utils.StringMap{"NAT": true}, - Weight: 10, RatingSubject: "*zero1m"} - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ConnectFee: 10.0, - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 100, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 20, 0, time.UTC), - DurationIndex: 10 * time.Second, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 1, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - deductConnectFee: true, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[1].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err == nil { - t.Error("Error showing debiting balance error: ", err) - } - if len(cc.Timespans) != 1 || - rifsBalance.BalanceMap[utils.MetaMonetary].GetTotalValue() != 0 { - t.Error("Error cutting at no connect fee: ", - rifsBalance.BalanceMap[utils.MetaMonetary]) - } -} - -func TestDebitCreditMoneyOnly(t *testing.T) { - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 1, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 10, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 20, 0, time.UTC), - DurationIndex: 10 * time.Second, - ratingInfo: &RatingInfo{}, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 1, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[1].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Uuid: "money", Value: 50}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err == nil { - t.Error("Missing noy enough credit error ") - } - if cc.Timespans[0].Increments[0].BalanceInfo.Monetary.UUID != "money" || - cc.Timespans[0].Increments[0].Duration != 10*time.Second { - t.Logf("%+v", cc.Timespans[0].Increments) - t.Error("Error setting balance id to increment: ", - cc.Timespans[0].Increments[0].BalanceInfo) - } - if rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 0 { - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaMonetary][0]) - } - if len(cc.Timespans) != 2 || - cc.Timespans[0].GetDuration() != 10*time.Second || - cc.Timespans[1].GetDuration() != 40*time.Second { - t.Error("Error truncating extra timespans: ", cc.Timespans) - } -} - -func TestDebitCreditSubjectMinutes(t *testing.T) { - b1 := &Balance{Uuid: "testb", - Categories: utils.NewStringMap("0"), - Value: 250 * float64(time.Second), - Weight: 10, - DestinationIDs: utils.StringMap{"NAT": true}, - RatingSubject: "minu"} - cc := &CallCost{ - Tenant: "vdf", - Category: "0", - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 1, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - deductConnectFee: true, - } - cd := &CallDescriptor{ - Tenant: cc.Tenant, - Category: "0", - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaVoice: {b1}, - utils.MetaMonetary: {&Balance{Uuid: "moneya", Value: 350}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testb" || - cc.Timespans[0].Increments[0].BalanceInfo.Monetary.UUID != "moneya" || - cc.Timespans[0].Increments[0].Duration != 10*time.Second { - t.Errorf("Error setting balance id to increment: %+v", - cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue() != 180*float64(time.Second) || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 280 { - t.Errorf("Error extracting minutes from balance: %+v, %+v", - rifsBalance.BalanceMap[utils.MetaVoice][0].GetValue(), - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } - if len(cc.Timespans) != 1 || - cc.Timespans[0].GetDuration() != 70*time.Second { - for _, ts := range cc.Timespans { - t.Log(ts) - } - t.Error("Error truncating extra timespans: ", cc.Timespans) - } -} - -func TestDebitCreditSubjectMoney(t *testing.T) { - cc := &CallCost{ - Tenant: "vdf", - Category: "0", - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 10, 0, time.UTC), - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 1, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - deductConnectFee: true, - } - cd := &CallDescriptor{ - Tenant: cc.Tenant, - Category: cc.Category, - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{Uuid: "moneya", Value: 75, - DestinationIDs: utils.StringMap{"NAT": true}, - RatingSubject: "minu"}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Monetary.UUID != "moneya" || - cc.Timespans[0].Increments[0].Duration != 10*time.Second { - t.Error("Error setting balance id to increment: ", - cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 5 { - t.Errorf("Error extracting minutes from balance: %+v", - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } - if len(cc.Timespans) != 1 || - cc.Timespans[0].GetDuration() != 70*time.Second { - t.Error("Error truncating extra timespans: ", cc.Timespans) - } -} - -func TestAccountdebitBalance(t *testing.T) { - ub := &Account{ - ID: "rif", - AllowNegative: true, - BalanceMap: map[string]Balances{ - utils.MetaSMS: {&Balance{Value: 14}}, - utils.MetaData: {&Balance{Value: 1204}}, - utils.MetaVoice: { - &Balance{Weight: 20, - DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{Weight: 10, - DestinationIDs: utils.StringMap{"RET": true}}}}, - } - newMb := &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(20), - DestinationIDs: utils.StringMapPointer(utils.StringMap{"NEW": true}), - } - a := &Action{Balance: newMb} - ub.debitBalanceAction(a, false, false) - if len(ub.BalanceMap[utils.MetaVoice]) != 3 || - !ub.BalanceMap[utils.MetaVoice][2].DestinationIDs.Equal(*newMb.DestinationIDs) { - t.Errorf("Error adding minute bucket! %d %+v %+v", - len(ub.BalanceMap[utils.MetaVoice]), ub.BalanceMap[utils.MetaVoice][2], newMb) - } -} - -func TestAccountdebitBalanceExists(t *testing.T) { - ub := &Account{ - ID: "rif", - AllowNegative: true, - BalanceMap: map[string]Balances{ - utils.MetaSMS: {&Balance{Value: 14}}, - utils.MetaData: {&Balance{Value: 1024}}, - utils.MetaVoice: { - &Balance{ - Value: 15, Weight: 20, - DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{Weight: 10, - DestinationIDs: utils.StringMap{"RET": true}}}}, - } - newMb := &BalanceFilter{ - Value: &utils.ValueFormula{Static: -10}, - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(20), - DestinationIDs: utils.StringMapPointer(utils.StringMap{"NAT": true}), - } - a := &Action{Balance: newMb} - ub.debitBalanceAction(a, false, false) - if len(ub.BalanceMap[utils.MetaVoice]) != 2 || - ub.BalanceMap[utils.MetaVoice][0].GetValue() != 25 { - t.Error("Error adding minute bucket!") - } -} - -func TestAccountAddMinuteNil(t *testing.T) { - ub := &Account{ - ID: "rif", - AllowNegative: true, - BalanceMap: map[string]Balances{ - utils.MetaSMS: {&Balance{Value: 14}}, - utils.MetaData: {&Balance{Value: 1024}}, - utils.MetaVoice: { - &Balance{Weight: 20, DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{Weight: 10, DestinationIDs: utils.StringMap{"RET": true}}}}, - } - ub.debitBalanceAction(nil, false, false) - if len(ub.BalanceMap[utils.MetaVoice]) != 2 { - t.Error("Error adding minute bucket!") - } -} - -func TestAccountAddMinutBucketEmpty(t *testing.T) { - mb1 := &BalanceFilter{ - Value: &utils.ValueFormula{Static: -10}, - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.StringMap{"NAT": true}), - } - mb2 := &BalanceFilter{ - Value: &utils.ValueFormula{Static: -10}, - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.StringMap{"NAT": true}), - } - mb3 := &BalanceFilter{ - Value: &utils.ValueFormula{Static: -10}, - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.StringMap{"OTHER": true}), - } - ub := &Account{} - a := &Action{Balance: mb1} - ub.debitBalanceAction(a, false, false) - if len(ub.BalanceMap[utils.MetaVoice]) != 1 { - t.Error("Error adding minute bucket: ", ub.BalanceMap[utils.MetaVoice]) - } - a = &Action{Balance: mb2} - ub.debitBalanceAction(a, false, false) - if len(ub.BalanceMap[utils.MetaVoice]) != 1 || ub.BalanceMap[utils.MetaVoice][0].GetValue() != 20 { - t.Error("Error adding minute bucket: ", ub.BalanceMap[utils.MetaVoice]) - } - a = &Action{Balance: mb3} - ub.debitBalanceAction(a, false, false) - if len(ub.BalanceMap[utils.MetaVoice]) != 2 { - t.Error("Error adding minute bucket: ", ub.BalanceMap[utils.MetaVoice]) - } -} - -func TestAccountExecuteTriggeredActions(t *testing.T) { - ub := &Account{ - ID: "TEST_UB", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{Value: 100}}, - utils.MetaVoice: { - &Balance{Value: 10 * float64(time.Second), - Weight: 20, - DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{Weight: 10, - DestinationIDs: utils.StringMap{"RET": true}}}}, - UnitCounters: UnitCounters{ - utils.MetaMonetary: []*UnitCounter{ - {Counters: CounterFilters{ - &CounterFilter{Value: 1, - Filter: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary)}}}}}}, - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary)}, - ThresholdValue: 2, ThresholdType: utils.TriggerMaxEventCounter, - ActionsID: "TEST_ACTIONS"}}, - } - ub.countUnits(1, utils.MetaMonetary, new(CallCost), nil) - if ub.BalanceMap[utils.MetaMonetary][0].GetValue() != 110 || - ub.BalanceMap[utils.MetaVoice][0].GetValue() != 20*float64(time.Second) { - t.Error("Error executing triggered actions", - ub.BalanceMap[utils.MetaMonetary][0].GetValue(), - ub.BalanceMap[utils.MetaVoice][0].GetValue()) - } - // are set to executed - ub.countUnits(1, utils.MetaMonetary, nil, nil) - if ub.BalanceMap[utils.MetaMonetary][0].GetValue() != 110 || - ub.BalanceMap[utils.MetaVoice][0].GetValue() != 20*float64(time.Second) { - t.Error("Error executing triggered actions", - ub.BalanceMap[utils.MetaMonetary][0].GetValue(), ub.BalanceMap[utils.MetaVoice][0].GetValue()) - } - // we can reset them - ub.ResetActionTriggers(nil) - ub.countUnits(10, utils.MetaMonetary, nil, nil) - if ub.BalanceMap[utils.MetaMonetary][0].GetValue() != 120 || - ub.BalanceMap[utils.MetaVoice][0].GetValue() != 30*float64(time.Second) { - t.Error("Error executing triggered actions", - ub.BalanceMap[utils.MetaMonetary][0].GetValue(), - ub.BalanceMap[utils.MetaVoice][0].GetValue()) - } -} - -func TestAccountExecuteTriggeredActionsBalance(t *testing.T) { - ub := &Account{ - ID: "TEST_UB", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{ - Value: 100}}, - utils.MetaVoice: { - &Balance{ - Value: 10 * float64(time.Second), - Weight: 20, - DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{ - Weight: 10, - DestinationIDs: utils.StringMap{"RET": true}}}}, - UnitCounters: UnitCounters{ - utils.MetaMonetary: []*UnitCounter{ - {Counters: CounterFilters{ - &CounterFilter{Filter: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary)}, - Value: 1.0}}}}}, - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary)}, - ThresholdValue: 100, - ThresholdType: utils.TriggerMinEventCounter, - ActionsID: "TEST_ACTIONS"}}, - } - ub.countUnits(1, utils.MetaMonetary, nil, nil) - if ub.BalanceMap[utils.MetaMonetary][0].GetValue() != 110 || - ub.BalanceMap[utils.MetaVoice][0].GetValue() != 20*float64(time.Second) { - t.Error("Error executing triggered actions", - ub.BalanceMap[utils.MetaMonetary][0].GetValue(), - ub.BalanceMap[utils.MetaVoice][0].GetValue(), - len(ub.BalanceMap[utils.MetaMonetary])) - } -} - -func TestAccountExecuteTriggeredActionsOrder(t *testing.T) { - ub := &Account{ - ID: "TEST_UB_OREDER", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{Value: 100}}}, - UnitCounters: UnitCounters{ - utils.MetaMonetary: []*UnitCounter{ - {Counters: CounterFilters{ - &CounterFilter{Value: 1, - Filter: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary)}}}}}}, - ActionTriggers: ActionTriggers{ - &ActionTrigger{Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary)}, - ThresholdValue: 2, - ThresholdType: utils.TriggerMaxEventCounter, - ActionsID: "TEST_ACTIONS_ORDER"}}, - } - - ub.countUnits(1, utils.MetaMonetary, new(CallCost), nil) - if len(ub.BalanceMap[utils.MetaMonetary]) != 1 || - ub.BalanceMap[utils.MetaMonetary][0].GetValue() != 10 { - - t.Errorf("Error executing triggered actions in order %v", - ub.BalanceMap[utils.MetaMonetary][0].GetValue()) - } -} - -func TestAccountExecuteTriggeredDayWeek(t *testing.T) { - ub := &Account{ - ID: "TEST_UB", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{Value: 100}}, - utils.MetaVoice: { - &Balance{Value: 10, Weight: 20, DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{Weight: 10, DestinationIDs: utils.StringMap{"RET": true}}}}, - ActionTriggers: ActionTriggers{ - &ActionTrigger{UniqueID: "day_trigger", - Balance: &BalanceFilter{Type: utils.StringPointer(utils.MetaMonetary)}, - ThresholdValue: 10, ThresholdType: utils.TriggerMaxEventCounter, - ActionsID: "TEST_ACTIONS"}, - &ActionTrigger{UniqueID: "week_trigger", - Balance: &BalanceFilter{Type: utils.StringPointer(utils.MetaMonetary)}, - ThresholdValue: 100, ThresholdType: utils.TriggerMaxEventCounter, - ActionsID: "TEST_ACTIONS"}, - }, - } - ub.InitCounters() - if len(ub.UnitCounters) != 1 || len(ub.UnitCounters[utils.MetaMonetary][0].Counters) != 2 { - t.Error("Error initializing counters: ", ub.UnitCounters[utils.MetaMonetary][0].Counters[0]) - } - - ub.countUnits(1, utils.MetaMonetary, new(CallCost), nil) - if ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 1 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[1].Value != 1 { - t.Error("Error incrementing both counters", - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value, - ub.UnitCounters[utils.MetaMonetary][0].Counters[1].Value) - } - - // we can reset them - resetCountersAction(ub, &Action{ - Balance: &BalanceFilter{Type: utils.StringPointer(utils.MetaMonetary), - ID: utils.StringPointer("day_trigger")}}, nil, nil) - if ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 0 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[1].Value != 1 { - t.Error("Error reseting both counters", - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value, - ub.UnitCounters[utils.MetaMonetary][0].Counters[1].Value) - } -} - -func TestAccountExpActionTrigger(t *testing.T) { - ub := &Account{ - ID: "TEST_UB", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{Value: 100, - ExpirationDate: time.Date(2015, time.November, 9, 9, 48, 0, 0, time.UTC)}}, - utils.MetaVoice: { - &Balance{Value: 10 * float64(time.Second), Weight: 20, - DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{Weight: 10 * float64(time.Second), - DestinationIDs: utils.StringMap{"RET": true}}}}, - ActionTriggers: ActionTriggers{ - &ActionTrigger{ID: "check expired balances", Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary)}, - ThresholdValue: 10, ThresholdType: utils.TriggerBalanceExpired, - ActionsID: "TEST_ACTIONS"}, - }, - } - ub.ExecuteActionTriggers(nil) - if ub.BalanceMap[utils.MetaMonetary][0].IsExpiredAt(time.Now()) || - ub.BalanceMap[utils.MetaMonetary][0].GetValue() != 10 || // expired was cleaned - ub.BalanceMap[utils.MetaVoice][0].GetValue() != 20*float64(time.Second) || - ub.ActionTriggers[0].Executed != true { - t.Log(ub.BalanceMap[utils.MetaMonetary][0].IsExpiredAt(time.Now())) - t.Error("Error executing triggered actions", - ub.BalanceMap[utils.MetaMonetary][0].GetValue(), - ub.BalanceMap[utils.MetaVoice][0].GetValue(), - len(ub.BalanceMap[utils.MetaMonetary])) - } -} - -func TestAccountExpActionTriggerNotActivated(t *testing.T) { - ub := &Account{ - ID: "TEST_UB", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Value: 100}}, - utils.MetaVoice: { - &Balance{Value: 10, Weight: 20, - DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{Weight: 10, - DestinationIDs: utils.StringMap{"RET": true}}}}, - ActionTriggers: ActionTriggers{ - &ActionTrigger{ID: "check expired balances", - ActivationDate: time.Date(2116, 2, 5, 18, 0, 0, 0, time.UTC), - Balance: &BalanceFilter{Type: utils.StringPointer(utils.MetaMonetary)}, - ThresholdValue: 10, ThresholdType: utils.TriggerBalanceExpired, - ActionsID: "TEST_ACTIONS"}, - }, - } - ub.ExecuteActionTriggers(nil) - if ub.BalanceMap[utils.MetaMonetary][0].IsExpiredAt(time.Now()) || - ub.BalanceMap[utils.MetaMonetary][0].GetValue() != 100 || - ub.BalanceMap[utils.MetaVoice][0].GetValue() != 10 || - ub.ActionTriggers[0].Executed != false { - t.Log(ub.BalanceMap[utils.MetaMonetary][0].IsExpiredAt(time.Now())) - t.Error("Error executing triggered actions", ub.BalanceMap[utils.MetaMonetary][0].GetValue(), ub.BalanceMap[utils.MetaVoice][0].GetValue(), len(ub.BalanceMap[utils.MetaMonetary])) - } -} - -func TestAccountExpActionTriggerExpired(t *testing.T) { - ub := &Account{ - ID: "TEST_UB", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Value: 100}}, - utils.MetaVoice: {&Balance{Value: 10, Weight: 20, - DestinationIDs: utils.StringMap{"NAT": true}}, - &Balance{Weight: 10, DestinationIDs: utils.StringMap{"RET": true}}}}, - ActionTriggers: ActionTriggers{ - &ActionTrigger{ID: "check expired balances", - ExpirationDate: time.Date(2016, 2, 4, 18, 0, 0, 0, time.UTC), - Balance: &BalanceFilter{Type: utils.StringPointer(utils.MetaMonetary)}, - ThresholdValue: 10, ThresholdType: utils.TriggerBalanceExpired, - ActionsID: "TEST_ACTIONS"}, - }, - } - ub.ExecuteActionTriggers(nil) - if ub.BalanceMap[utils.MetaMonetary][0].IsExpiredAt(time.Now()) || - ub.BalanceMap[utils.MetaMonetary][0].GetValue() != 100 || - ub.BalanceMap[utils.MetaVoice][0].GetValue() != 10 || - len(ub.ActionTriggers) != 0 { - t.Log(ub.BalanceMap[utils.MetaMonetary][0].IsExpiredAt(time.Now())) - t.Error("Error executing triggered actions", - ub.BalanceMap[utils.MetaMonetary][0].GetValue(), - ub.BalanceMap[utils.MetaVoice][0].GetValue(), - len(ub.BalanceMap[utils.MetaMonetary])) - } -} - -func TestCleanExpired(t *testing.T) { - ub := &Account{ - ID: "TEST_UB_OREDER", - BalanceMap: map[string]Balances{utils.MetaMonetary: { - &Balance{ExpirationDate: time.Now().Add(10 * time.Second)}, - &Balance{ExpirationDate: time.Date(2013, 7, 18, 14, 33, 0, 0, time.UTC)}, - &Balance{ExpirationDate: time.Now().Add(10 * time.Second)}}, utils.MetaVoice: { - &Balance{ExpirationDate: time.Date(2013, 7, 18, 14, 33, 0, 0, time.UTC)}, - &Balance{ExpirationDate: time.Now().Add(10 * time.Second)}, - }}, - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - ExpirationDate: time.Date(2013, 7, 18, 14, 33, 0, 0, time.UTC), - }, - &ActionTrigger{ - ActivationDate: time.Date(2013, 7, 18, 14, 33, 0, 0, time.UTC), - }, - }, - } - ub.CleanExpiredStuff() - if len(ub.BalanceMap[utils.MetaMonetary]) != 2 { - t.Error("Error cleaning expired balances!") - } - if len(ub.BalanceMap[utils.MetaVoice]) != 1 { - t.Error("Error cleaning expired minute buckets!") - } - if len(ub.ActionTriggers) != 1 { - t.Error("Error cleaning expired action triggers!") - } -} - -func TestAccountUnitCounting(t *testing.T) { - ub := &Account{UnitCounters: UnitCounters{ - utils.MetaMonetary: []*UnitCounter{{ - Counters: CounterFilters{&CounterFilter{Value: 0}}}}}} - ub.countUnits(10, utils.MetaMonetary, &CallCost{}, nil) - if len(ub.UnitCounters[utils.MetaMonetary]) != 1 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 10 { - t.Error("Error counting units") - } - ub.countUnits(10, utils.MetaMonetary, &CallCost{}, nil) - if len(ub.UnitCounters[utils.MetaMonetary]) != 1 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 20 { - t.Error("Error counting units") - } -} - -func TestAccountUnitCountingOutbound(t *testing.T) { - ub := &Account{UnitCounters: UnitCounters{utils.MetaMonetary: []*UnitCounter{ - {Counters: CounterFilters{&CounterFilter{Value: 0}}}}}} - ub.countUnits(10, utils.MetaMonetary, new(CallCost), nil) - if len(ub.UnitCounters[utils.MetaMonetary]) != 1 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 10 { - t.Error("Error counting units") - } - ub.countUnits(10, utils.MetaMonetary, new(CallCost), nil) - if len(ub.UnitCounters[utils.MetaMonetary]) != 1 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 20 { - t.Error("Error counting units") - } - ub.countUnits(10, utils.MetaMonetary, new(CallCost), nil) - if len(ub.UnitCounters[utils.MetaMonetary]) != 1 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 30 { - t.Error("Error counting units") - } -} - -func TestAccountUnitCountingOutboundInbound(t *testing.T) { - ub := &Account{UnitCounters: UnitCounters{ - utils.MetaMonetary: []*UnitCounter{ - {Counters: CounterFilters{&CounterFilter{Value: 0}}}}}} - ub.countUnits(10, utils.MetaMonetary, new(CallCost), nil) - if len(ub.UnitCounters[utils.MetaMonetary]) != 1 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 10 { - t.Errorf("Error counting units: %+v", - ub.UnitCounters[utils.MetaMonetary][0].Counters[0]) - } - ub.countUnits(10, utils.MetaMonetary, new(CallCost), nil) - if len(ub.UnitCounters[utils.MetaMonetary]) != 1 || - ub.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 20 { - t.Error("Error counting units") - } -} - -func TestDebitShared(t *testing.T) { - cc := &CallCost{ - Tenant: "vdf", - Category: "0", - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 0, 0, time.UTC), - DurationIndex: 55 * time.Second, - RateInterval: &RateInterval{Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 2, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - deductConnectFee: true, - } - cd := &CallDescriptor{ - Tenant: cc.Tenant, - Category: cc.Category, - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rif := &Account{ID: "rif", BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Uuid: "moneya", Value: 0, SharedGroups: utils.NewStringMap("SG_TEST")}}, - }} - groupie := &Account{ID: "groupie", BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Uuid: "moneyc", Value: 130, SharedGroups: utils.NewStringMap("SG_TEST")}}, - }} - - sg := &SharedGroup{Id: "SG_TEST", MemberIds: utils.NewStringMap(rif.ID, groupie.ID), AccountParameters: map[string]*SharingParameters{"*any": {Strategy: STRATEGY_MINE_RANDOM}}} - - dm.SetAccount(groupie) - dm.SetSharedGroup(sg, utils.NonTransactional) - cc, err := rif.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if rif.BalanceMap[utils.MetaMonetary][0].GetValue() != 0 { - t.Errorf("Error debiting from shared group: %+v", rif.BalanceMap[utils.MetaMonetary][0]) - } - groupie, _ = dm.GetAccount("groupie") - if groupie.BalanceMap[utils.MetaMonetary][0].GetValue() != 10 { - t.Errorf("Error debiting from shared group: %+v", groupie.BalanceMap[utils.MetaMonetary][0]) - } - - if len(cc.Timespans) != 1 { - t.Errorf("Wrong number of timespans: %v", cc.Timespans) - } - if len(cc.Timespans[0].Increments) != 6 { - t.Errorf("Wrong number of increments: %v", cc.Timespans[0].Increments) - for index, incr := range cc.Timespans[0].Increments { - t.Errorf("I%d: %+v (%+v)", index, incr, incr.BalanceInfo) - } - } - if cc.Timespans[0].Increments[0].BalanceInfo.AccountID != "groupie" || - cc.Timespans[0].Increments[1].BalanceInfo.AccountID != "groupie" || - cc.Timespans[0].Increments[2].BalanceInfo.AccountID != "groupie" || - cc.Timespans[0].Increments[3].BalanceInfo.AccountID != "groupie" || - cc.Timespans[0].Increments[4].BalanceInfo.AccountID != "groupie" || - cc.Timespans[0].Increments[5].BalanceInfo.AccountID != "groupie" { - t.Error("Error setting balance id to increment: ", cc.Timespans[0].Increments[0]) - } -} - -func TestMaxDurationShared(t *testing.T) { - cc := &CallCost{ - Tenant: "vdf", - Category: "0", - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 0, 0, time.UTC), - DurationIndex: 55 * time.Second, - RateInterval: &RateInterval{ - Rating: &RIRate{Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 2, - RateIncrement: 10 * time.Second, - RateUnit: time.Second}}}}, - }, - }, - deductConnectFee: true, - } - cd := &CallDescriptor{ - Tenant: cc.Tenant, - Category: cc.Category, - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rif := &Account{ID: "rif", BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Uuid: "moneya", Value: 0, SharedGroups: utils.NewStringMap("SG_TEST")}}, - }} - groupie := &Account{ID: "groupie", BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Uuid: "moneyc", Value: 130, SharedGroups: utils.NewStringMap("SG_TEST")}}, - }} - - sg := &SharedGroup{Id: "SG_TEST", MemberIds: utils.NewStringMap(rif.ID, groupie.ID), AccountParameters: map[string]*SharingParameters{"*any": {Strategy: STRATEGY_MINE_RANDOM}}} - - dm.SetAccount(groupie) - dm.SetSharedGroup(sg, utils.NonTransactional) - duration, err := cd.getMaxSessionDuration(rif) - if err != nil { - t.Error("Error getting max session duration from shared group: ", err) - } - if duration != time.Minute { - t.Error("Wrong max session from shared group: ", duration) - } - -} - -func TestMaxDurationConnectFeeOnly(t *testing.T) { - cd := &CallDescriptor{ - Tenant: "cgrates.org", - Category: "call", - TimeStart: time.Date(2015, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2015, 9, 24, 10, 58, 1, 0, time.UTC), - Destination: "4444", - Subject: "dy", - Account: "dy", - ToR: utils.MetaVoice, - DurationIndex: 600, - } - rif := &Account{ID: "rif", BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Uuid: "moneya", Value: 0.2}}, - }} - - duration, err := cd.getMaxSessionDuration(rif) - if err != nil { - t.Error("Error getting max session duration: ", err) - } - if duration != 0 { - t.Error("Wrong max session: ", duration) - } - -} - -func TestDebitSMS(t *testing.T) { - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 0, 1, time.UTC), - ratingInfo: &RatingInfo{}, - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 100, - RateIncrement: 1, - RateUnit: time.Nanosecond}}}}, - }, - }, - ToR: utils.MetaSMS, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaSMS: { - &Balance{Uuid: "testm", - Value: 100, Weight: 5, - DestinationIDs: utils.StringMap{"NAT": true}}}, - utils.MetaMonetary: { - &Balance{Value: 21}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testm" { - t.Error("Error setting balance id to increment: ", cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaSMS][0].GetValue() != 99 || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 21 { - t.Log(cc.Timespans[0].Increments) - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaSMS][0].GetValue(), - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } -} - -func TestDebitGeneric(t *testing.T) { - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 0, 1, time.UTC), - ratingInfo: &RatingInfo{}, - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{ - GroupIntervalStart: 0, - Value: 100, - RateIncrement: 1, - RateUnit: time.Nanosecond, - }, - }, - }, - }, - }, - }, - ToR: utils.MetaGeneric, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaGeneric: { - &Balance{Uuid: "testm", Value: 100, Weight: 5, - DestinationIDs: utils.StringMap{"NAT": true}}}, - utils.MetaMonetary: {&Balance{Value: 21}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testm" { - t.Error("Error setting balance id to increment: ", - cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaGeneric][0].GetValue() != 99 || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 21 { - t.Log(cc.Timespans[0].Increments) - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaGeneric][0].GetValue(), - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } -} - -func TestDebitGenericBalance(t *testing.T) { - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 30, 0, time.UTC), - ratingInfo: &RatingInfo{}, - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 100, - RateIncrement: time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ - ID: "other", BalanceMap: map[string]Balances{ - utils.MetaGeneric: { - &Balance{Uuid: "testm", Value: 100, Weight: 5, - DestinationIDs: utils.StringMap{"NAT": true}, - Factor: ValueFactor{utils.MetaVoice: 60 * float64(time.Second)}}}, - utils.MetaMonetary: {&Balance{Value: 21}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testm" { - t.Error("Error setting balance id to increment: ", cc.Timespans[0].Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaGeneric][0].GetValue() != 99.49999 || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 21 { - t.Logf("%+v", cc.Timespans[0].Increments[0]) - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaGeneric][0].GetValue(), - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } -} - -func TestDebitGenericBalanceWithRatingSubject(t *testing.T) { - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 30, 0, time.UTC), - ratingInfo: &RatingInfo{}, - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 0, - RateIncrement: time.Second, - RateUnit: time.Second}}}}, - }, - }, - ToR: utils.MetaVoice, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaGeneric: { - &Balance{Uuid: "testm", Value: 100, - Weight: 5, DestinationIDs: utils.StringMap{"NAT": true}, - Factor: ValueFactor{utils.MetaVoice: 60 * float64(time.Second)}, - RatingSubject: "free"}}, - utils.MetaMonetary: {&Balance{Value: 21}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - if err != nil { - t.Error("Error debiting balance: ", err) - } - if cc.Timespans[0].Increments[0].BalanceInfo.Unit.UUID != "testm" { - t.Error("Error setting balance id to increment: ", cc.Timespans[0]) - } - if rifsBalance.BalanceMap[utils.MetaGeneric][0].GetValue() != 99.49999 || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 21 { - t.Logf("%+v", cc.Timespans[0].Increments[0]) - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaGeneric][0].GetValue(), - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } -} - -func TestDebitDataUnits(t *testing.T) { - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 48, 0, 80, time.UTC), - ratingInfo: &RatingInfo{}, - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, - Value: 2, RateIncrement: 1, - RateUnit: 1}, - &RGRate{GroupIntervalStart: 60, - Value: 1, - RateIncrement: 1, - RateUnit: 1}, - }, - }, - }, - }, - }, - ToR: utils.MetaData, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", - BalanceMap: map[string]Balances{ - utils.MetaData: { - &Balance{Uuid: "testm", Value: 100, - Weight: 5, - DestinationIDs: utils.StringMap{"NAT": true}}}, - utils.MetaMonetary: {&Balance{Value: 21}}, - }} - var err error - cc, err = rifsBalance.debitCreditBalance(cd, false, false, true) - // test rating information - ts := cc.Timespans[0] - if ts.MatchedSubject != "testm" || ts.MatchedPrefix != "0723" || - ts.MatchedDestId != "NAT" || ts.RatingPlanId != utils.MetaNone { - t.Errorf("Error setting rating info: %+v", ts.ratingInfo) - } - if err != nil { - t.Error("Error debiting balance: ", err) - } - if ts.Increments[0].BalanceInfo.Unit.UUID != "testm" { - t.Error("Error setting balance id to increment: ", ts.Increments[0]) - } - if rifsBalance.BalanceMap[utils.MetaData][0].GetValue() != 20 || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 21 { - t.Log(ts.Increments) - t.Error("Error extracting minutes from balance: ", - rifsBalance.BalanceMap[utils.MetaData][0].GetValue(), - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } -} - -func TestDebitDataMoney(t *testing.T) { - cc := &CallCost{ - Destination: "0723045326", - Timespans: []*TimeSpan{ - { - TimeStart: time.Date(2013, 9, 24, 10, 48, 0, 0, time.UTC), - TimeEnd: time.Date(2013, 9, 24, 10, 49, 20, 0, time.UTC), - ratingInfo: &RatingInfo{}, - DurationIndex: 0, - RateInterval: &RateInterval{ - Rating: &RIRate{ - Rates: RateGroups{ - &RGRate{GroupIntervalStart: 0, Value: 2, RateIncrement: time.Minute, RateUnit: time.Second}, - }, - }, - }, - }, - }, - ToR: utils.MetaData, - } - cd := &CallDescriptor{ - TimeStart: cc.Timespans[0].TimeStart, - TimeEnd: cc.Timespans[0].TimeEnd, - Destination: cc.Destination, - ToR: cc.ToR, - DurationIndex: cc.GetDuration(), - testCallcost: cc, - } - rifsBalance := &Account{ID: "other", BalanceMap: map[string]Balances{ - utils.MetaData: {&Balance{Uuid: "testm", Value: 0, Weight: 5, DestinationIDs: utils.StringMap{"NAT": true}}}, - utils.MetaMonetary: {&Balance{Value: 160}}, - }} - if _, err := rifsBalance.debitCreditBalance(cd, false, false, true); err != nil { - t.Error("Error debiting balance: ", err) - } - if rifsBalance.BalanceMap[utils.MetaData][0].GetValue() != 0 || - rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue() != 0 { - t.Error("Error extracting minutes from balance: ", rifsBalance.BalanceMap[utils.MetaData][0].GetValue(), rifsBalance.BalanceMap[utils.MetaMonetary][0].GetValue()) - } -} - -func TestAccountGetDefaultMoneyBalanceEmpty(t *testing.T) { - acc := &Account{} - defBal := acc.GetDefaultMoneyBalance() - if defBal == nil || len(acc.BalanceMap) != 1 || !defBal.IsDefault() { - t.Errorf("Bad default money balance: %+v", defBal) - } -} - -func TestAccountGetDefaultMoneyBalance(t *testing.T) { - acc := &Account{} - acc.BalanceMap = make(map[string]Balances) - tag := utils.MetaMonetary - acc.BalanceMap[tag] = append(acc.BalanceMap[tag], &Balance{Weight: 10}) - defBal := acc.GetDefaultMoneyBalance() - if defBal == nil || len(acc.BalanceMap[tag]) != 2 || !defBal.IsDefault() { - t.Errorf("Bad default money balance: %+v", defBal) - } -} - -func TestAccountInitCounters(t *testing.T) { - a := &Account{ - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - UniqueID: "TestTR1", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR11", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR2", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR3", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR4", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR5", - ThresholdType: utils.TriggerMaxBalance, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - }, - } - a.InitCounters() - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaMonetary][0].Counters) != 2 || - len(a.UnitCounters[utils.MetaVoice][0].Counters) != 1 || - len(a.UnitCounters[utils.MetaVoice][1].Counters) != 1 || - len(a.UnitCounters[utils.MetaSMS][0].Counters) != 1 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, c := range uc.Counters { - t.Logf("B: %+v", c) - } - } - } - t.Errorf("Error Initializing unit counters: %v", len(a.UnitCounters)) - } -} - -func TestAccountDoubleInitCounters(t *testing.T) { - a := &Account{ - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - UniqueID: "TestTR1", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR11", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR2", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR3", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR4", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR5", - ThresholdType: utils.TriggerMaxBalance, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - }, - } - a.InitCounters() - a.InitCounters() - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaMonetary][0].Counters) != 2 || - len(a.UnitCounters[utils.MetaVoice][0].Counters) != 1 || - len(a.UnitCounters[utils.MetaVoice][1].Counters) != 1 || - len(a.UnitCounters[utils.MetaSMS][0].Counters) != 1 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, c := range uc.Counters { - t.Logf("B: %+v", c) - } - } - } - t.Errorf("Error Initializing unit counters: %v", len(a.UnitCounters)) - } -} - -func TestAccountGetBalancesForPrefixMixed(t *testing.T) { - acc := &Account{ - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{ - Value: 10, - DestinationIDs: utils.StringMap{"NAT": true, "RET": false}, - }, - }, - }, - } - bcs := acc.getBalancesForPrefix("999123", "", utils.MetaMonetary, "", time.Now()) - if len(bcs) != 0 { - t.Error("error excluding on mixed balances") - } -} - -func TestAccountGetBalancesForPrefixAllExcl(t *testing.T) { - acc := &Account{ - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{ - Value: 10, - DestinationIDs: utils.StringMap{"NAT": false, "RET": false}, - }, - }, - }, - } - bcs := acc.getBalancesForPrefix("999123", "", utils.MetaMonetary, "", time.Now()) - if len(bcs) == 0 { - t.Error("error finding balance on all excluded") - } -} - -func TestAccountGetBalancesForPrefixMixedGood(t *testing.T) { - acc := &Account{ - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{ - Value: 10, - DestinationIDs: utils.StringMap{"NAT": true, "RET": false, "EXOTIC": true}, - }, - }, - }, - } - - bcs := acc.getBalancesForPrefix("999123", "", utils.MetaMonetary, "", time.Now()) - if len(bcs) == 0 { - t.Error("error finding on mixed balances good") - } -} - -func TestAccountGetBalancesForPrefixMixedBad(t *testing.T) { - acc := &Account{ - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{ - Value: 10, - DestinationIDs: utils.StringMap{"NAT": true, "RET": false, "EXOTIC": false}, - }, - }, - }, - } - bcs := acc.getBalancesForPrefix("999123", "", utils.MetaMonetary, "", time.Now()) - if len(bcs) != 0 { - t.Error("error excluding on mixed balances bad") - } -} - -func TestAccountNewAccountSummaryFromJSON(t *testing.T) { - if acnt, err := NewAccountSummaryFromJSON("null"); err != nil { - t.Error(err) - } else if acnt != nil { - t.Errorf("Expecting nil, received: %+v", acnt) - } -} - -func TestAccountAsAccountDigest(t *testing.T) { - acnt1 := &Account{ - ID: "cgrates.org:account1", - AllowNegative: true, - BalanceMap: map[string]Balances{ - utils.MetaSMS: {&Balance{ID: "sms1", Value: 14}}, - utils.MetaMMS: {&Balance{ID: "mms1", Value: 140}}, - utils.MetaData: {&Balance{ID: "data1", Value: 1204}}, - utils.MetaVoice: { - &Balance{ID: "voice1", Weight: 20, DestinationIDs: utils.StringMap{"NAT": true}, Value: 3600}, - &Balance{ID: "voice2", Weight: 10, DestinationIDs: utils.StringMap{"RET": true}, Value: 1200}, - }, - }, - } - expectacntSummary := &AccountSummary{ - Tenant: "cgrates.org", - ID: "account1", - BalanceSummaries: []*BalanceSummary{ - {ID: "data1", Type: utils.MetaData, Value: 1204, Disabled: false}, - {ID: "sms1", Type: utils.MetaSMS, Value: 14, Disabled: false}, - {ID: "mms1", Type: utils.MetaMMS, Value: 140, Disabled: false}, - {ID: "voice1", Type: utils.MetaVoice, Value: 3600, Disabled: false}, - {ID: "voice2", Type: utils.MetaVoice, Value: 1200, Disabled: false}, - }, - AllowNegative: true, - Disabled: false, - } - acntSummary := acnt1.AsAccountSummary() - // Since maps are unordered, slices will be too so we need to find element to compare - if !reflect.DeepEqual(expectacntSummary, acntSummary) { - t.Errorf("Expecting: %+v, received: %+v", utils.ToJSON(expectacntSummary), utils.ToJSON(acntSummary)) - } -} - -func TestAccountGetBalancesGetBalanceWithSameWeight(t *testing.T) { - acc := &Account{ - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{ - ID: "SpecialBalance1", - Value: 10, - Weight: 10.0, - }, - &Balance{ - ID: "SpecialBalance2", - Value: 10, - Weight: 10.0, - }, - }, - }, - } - bcs := acc.getBalancesForPrefix("", "", utils.MetaMonetary, "", time.Now()) - if len(bcs) != 2 && bcs[0].ID != "SpecialBalance1" && bcs[1].ID != "SpecialBalance2" { - t.Errorf("Unexpected order balances : %+v", utils.ToJSON(bcs)) - } -} - -func TestAccountGetBalancesForPrefix2(t *testing.T) { - acc := &Account{ - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{ - ID: "SpecialBalance1", - Value: 10, - Weight: 10.0, - }, - &Balance{ - ID: "SpecialBalance2", - Value: 10, - Weight: 20.0, - }, - }, - }, - } - bcs := acc.getBalancesForPrefix("", "", utils.MetaMonetary, "", time.Now()) - if len(bcs) != 2 && bcs[0].ID != "SpecialBalance2" && bcs[0].Weight != 20.0 { - t.Errorf("Unexpected order balances : %+v", utils.ToJSON(bcs)) - } -} - -func TestAccountGetMultipleBalancesForPrefixWithSameWeight(t *testing.T) { - acc := &Account{ - BalanceMap: map[string]Balances{ - utils.MetaMonetary: { - &Balance{ - ID: "SpecialBalance1", - Value: 10, - Weight: 10.0, - }, - &Balance{ - ID: "SpecialBalance2", - Value: 10, - Weight: 10.0, - }, - &Balance{ - ID: "SpecialBalance3", - Value: 10, - Weight: 10.0, - }, - &Balance{ - ID: "SpecialBalance4", - Value: 10, - Weight: 10.0, - }, - &Balance{ - ID: "SpecialBalance5", - Value: 10, - Weight: 10.0, - }, - }, - }, - } - bcs := acc.getBalancesForPrefix("", "", utils.MetaMonetary, "", time.Now()) - if len(bcs) != 5 && - bcs[0].ID != "SpecialBalance1" && bcs[1].ID != "SpecialBalance2" && - bcs[2].ID != "SpecialBalance3" && bcs[3].ID != "SpecialBalance4" && - bcs[4].ID != "SpecialBalance5" { - t.Errorf("Unexpected order balances : %+v", utils.ToJSON(bcs)) - } -} - -func TestAccountClone(t *testing.T) { - account := &Account{} - eOut := &Account{} - if rcv := account.Clone(); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %+v, received: %+v", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - account = &Account{ - ID: "testID", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Value: 10, Weight: 10}}}, - ActionTriggers: []*ActionTrigger{ - { - ID: "ActionTriggerID1", - }, - { - ID: "ActionTriggerID2", - }, - }, - AllowNegative: true, - Disabled: true, - } - eOut = &Account{ - ID: "testID", - BalanceMap: map[string]Balances{ - utils.MetaMonetary: {&Balance{Value: 10, Weight: 10}}}, - ActionTriggers: []*ActionTrigger{ - { - ID: "ActionTriggerID1", - }, - { - ID: "ActionTriggerID2", - }, - }, - AllowNegative: true, - Disabled: true, - } - - if rcv := account.Clone(); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %+v, received: %+v", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - -} - -func TestAccountGetBalanceWithID(t *testing.T) { - account := &Account{ - BalanceMap: map[string]Balances{ - "type1": {&Balance{ID: "test1", Value: 0.7}}, - "type2": {&Balance{ID: "test2", Value: 0.8}}, - }, - } - if rcv := account.GetBalanceWithID("type1", "test1"); rcv.Value != 0.7 { - t.Errorf("Expecting: 0.7, received: %+v", rcv) - } - if rcv := account.GetBalanceWithID("type2", "test2"); rcv.Value != 0.8 { - t.Errorf("Expecting: 0.8, received: %+v", rcv) - } - if rcv := account.GetBalanceWithID("unknown", "unknown"); rcv != nil { - t.Errorf("Expecting: nil, received: %+v", rcv) - } -} - -/*********************************** Benchmarks *******************************/ - -func BenchmarkGetSecondForPrefix(b *testing.B) { - b.StopTimer() - b1 := &Balance{Value: 10, Weight: 10, DestinationIDs: utils.StringMap{"NAT": true}} - b2 := &Balance{Value: 100, Weight: 20, DestinationIDs: utils.StringMap{"RET": true}} - - ub1 := &Account{ID: "other", BalanceMap: map[string]Balances{utils.MetaVoice: {b1, b2}, utils.MetaMonetary: {&Balance{Value: 21}}}} - cd := &CallDescriptor{ - Destination: "0723", - } - b.StartTimer() - for i := 0; i < b.N; i++ { - ub1.getCreditForPrefix(cd) - } -} - -func BenchmarkAccountStorageStoreRestore(b *testing.B) { - b1 := &Balance{Value: 10, Weight: 10, DestinationIDs: utils.StringMap{"NAT": true}} - b2 := &Balance{Value: 100, Weight: 20, DestinationIDs: utils.StringMap{"RET": true}} - rifsBalance := &Account{ID: "other", BalanceMap: map[string]Balances{utils.MetaVoice: {b1, b2}, utils.MetaMonetary: {&Balance{Value: 21}}}} - for i := 0; i < b.N; i++ { - dm.SetAccount(rifsBalance) - dm.GetAccount(rifsBalance.ID) - } -} - -func BenchmarkGetSecondsForPrefix(b *testing.B) { - b1 := &Balance{Value: 10, Weight: 10, DestinationIDs: utils.StringMap{"NAT": true}} - b2 := &Balance{Value: 100, Weight: 20, DestinationIDs: utils.StringMap{"RET": true}} - ub1 := &Account{ID: "OUT:CUSTOMER_1:rif", BalanceMap: map[string]Balances{utils.MetaVoice: {b1, b2}, utils.MetaMonetary: {&Balance{Value: 21}}}} - cd := &CallDescriptor{ - Destination: "0723", - } - for i := 0; i < b.N; i++ { - ub1.getCreditForPrefix(cd) - } -} diff --git a/engine/action.go b/engine/action.go deleted file mode 100644 index 27ce5240d..000000000 --- a/engine/action.go +++ /dev/null @@ -1,1028 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments -Copyright (C) ITsysCOM GmbH - -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 -*/ - -package engine - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "html/template" - "net" - "net/http" - "net/smtp" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/utils" - "github.com/cgrates/rpcclient" - "github.com/mitchellh/mapstructure" -) - -// Action will be filled for each tariff plan with the bonus value for received calls minutes. -type Action struct { - Id string - ActionType string - ExtraParameters string - Filter string - ExpirationString string // must stay as string because it can have relative values like 1month - Weight float64 - Balance *BalanceFilter - balanceValue float64 // balance value after action execution, used with cdrlog -} - -// Clone returns a clone of the action -func (a *Action) Clone() (cln *Action) { - if a == nil { - return - } - return &Action{ - Id: a.Id, - ActionType: a.ActionType, - ExtraParameters: a.ExtraParameters, - Filter: a.Filter, - ExpirationString: a.ExpirationString, - Weight: a.Weight, - Balance: a.Balance.Clone(), - } -} - -type actionTypeFunc func(*Account, *Action, Actions, interface{}) error - -func getActionFunc(typ string) (actionTypeFunc, bool) { - actionFuncMap := map[string]actionTypeFunc{ - utils.MetaLog: logAction, - utils.MetaResetTriggers: resetTriggersAction, - utils.CDRLog: cdrLogAction, - utils.MetaSetRecurrent: setRecurrentAction, - utils.MetaUnsetRecurrent: unsetRecurrentAction, - utils.MetaAllowNegative: allowNegativeAction, - utils.MetaDenyNegative: denyNegativeAction, - utils.MetaResetAccount: resetAccountAction, - utils.MetaTopUpReset: topupResetAction, - utils.MetaTopUp: topupAction, - utils.MetaDebitReset: debitResetAction, - utils.MetaDebit: debitAction, - utils.MetaResetCounters: resetCountersAction, - utils.MetaEnableAccount: enableAccountAction, - utils.MetaDisableAccount: disableAccountAction, - utils.MetaHTTPPost: callURL, - utils.HttpPostAsync: callURLAsync, - utils.MetaMailAsync: mailAsync, - utils.MetaSetDDestinations: setddestinations, - // utils.MetaRemoveAccount: removeAccountAction, - utils.MetaRemoveBalance: removeBalanceAction, - utils.MetaSetBalance: setBalanceAction, - utils.MetaTransferMonetaryDefault: transferMonetaryDefaultAction, - utils.MetaCgrRpc: cgrRPCAction, - utils.TopUpZeroNegative: topupZeroNegativeAction, - utils.SetExpiry: setExpiryAction, - utils.MetaPublishAccount: publishAccount, - utils.MetaRemoveSessionCosts: removeSessionCosts, - utils.MetaRemoveExpired: removeExpired, - utils.MetaPostEvent: postEvent, - utils.MetaCDRAccount: resetAccountCDR, - utils.MetaExport: export, - utils.MetaResetThreshold: resetThreshold, - utils.MetaResetStatQueue: resetStatQueue, - utils.MetaRemoteSetAccount: remoteSetAccount, - } - f, exists := actionFuncMap[typ] - return f, exists -} - -func logAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - switch { - case ub != nil: - body, _ := json.Marshal(ub) - utils.Logger.Info(fmt.Sprintf("LOG Account: %s", body)) - case extraData != nil: - body, _ := json.Marshal(extraData) - utils.Logger.Info(fmt.Sprintf("LOG ExtraData: %s", body)) - } - return -} - -func cdrLogAction(acc *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if len(config.CgrConfig().SchedulerCfg().CDRsConns) == 0 { - return fmt.Errorf("No connection with CDR Server") - } - defaultTemplate := map[string]config.RSRParsers{ - utils.ToR: config.NewRSRParsersMustCompile(utils.DynamicDataPrefix+utils.MetaAcnt+utils.NestingSep+utils.BalanceType, utils.InfieldSep), - utils.OriginHost: config.NewRSRParsersMustCompile("127.0.0.1", utils.InfieldSep), - utils.RequestType: config.NewRSRParsersMustCompile(utils.MetaNone, utils.InfieldSep), - utils.Tenant: config.NewRSRParsersMustCompile(utils.DynamicDataPrefix+utils.MetaAcnt+utils.NestingSep+utils.Tenant, utils.InfieldSep), - utils.AccountField: config.NewRSRParsersMustCompile(utils.DynamicDataPrefix+utils.MetaAcnt+utils.NestingSep+utils.AccountField, utils.InfieldSep), - utils.Subject: config.NewRSRParsersMustCompile(utils.DynamicDataPrefix+utils.MetaAcnt+utils.NestingSep+utils.AccountField, utils.InfieldSep), - utils.Cost: config.NewRSRParsersMustCompile(utils.DynamicDataPrefix+utils.MetaAct+utils.NestingSep+utils.ActionValue, utils.InfieldSep), - } - template := make(map[string]string) - // overwrite default template - if a.ExtraParameters != "" { - if err = json.Unmarshal([]byte(a.ExtraParameters), &template); err != nil { - return - } - for field, rsr := range template { - if defaultTemplate[field], err = config.NewRSRParsers(rsr, - config.CgrConfig().GeneralCfg().RSRSep); err != nil { - return - } - } - } - //In case that we have extra data we populate default templates - mapExtraData, _ := extraData.(map[string]interface{}) - for key, val := range mapExtraData { - if defaultTemplate[key], err = config.NewRSRParsers(utils.IfaceAsString(val), - config.CgrConfig().GeneralCfg().RSRSep); err != nil { - return - } - } - - // set stored cdr values - var cdrs []*CDR - for _, action := range acs { - if !utils.SliceHasMember([]string{utils.MetaDebit, utils.MetaDebitReset, utils.MetaSetBalance, utils.MetaTopUp, utils.MetaTopUpReset}, action.ActionType) || - action.Balance == nil { - continue // Only log specific actions - } - cdrLogProvider := newCdrLogProvider(acc, action) - cdr := &CDR{ - RunID: action.ActionType, - Source: utils.CDRLog, - SetupTime: time.Now(), - AnswerTime: time.Now(), - OriginID: utils.GenUUID(), - ExtraFields: make(map[string]string), - PreRated: true, - Usage: time.Duration(1), - } - cdr.CGRID = utils.Sha1(cdr.OriginID, cdr.OriginHost) - elem := reflect.ValueOf(cdr).Elem() - for key, rsrFlds := range defaultTemplate { - parsedValue, err := rsrFlds.ParseDataProvider(cdrLogProvider) - if err != nil { - return err - } - field := elem.FieldByName(key) - if field.IsValid() && field.CanSet() { - switch field.Kind() { - case reflect.Float64: - value, err := strconv.ParseFloat(parsedValue, 64) - if err != nil { - continue - } - field.SetFloat(value) - case reflect.String: - field.SetString(parsedValue) - case reflect.Int64: - value, err := strconv.ParseInt(parsedValue, 10, 64) - if err != nil { - continue - } - field.SetInt(value) - } - } else { // invalid fields go in extraFields of CDR - cdr.ExtraFields[key] = parsedValue - } - } - cdrs = append(cdrs, cdr) - var rply string - // After compute the CDR send it to CDR Server to be processed - if err := connMgr.Call(config.CgrConfig().SchedulerCfg().CDRsConns, nil, - utils.CDRsV1ProcessEvent, - &ArgV1ProcessEvent{ - Flags: []string{utils.ConcatenatedKey(utils.MetaChargers, "false")}, // do not try to get the chargers for cdrlog - CGREvent: *cdr.AsCGREvent(), - }, &rply); err != nil { - return err - } - } - b, _ := json.Marshal(cdrs) - a.ExpirationString = string(b) // testing purpose only - return -} - -func resetTriggersAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - ub.ResetActionTriggers(a) - return -} - -func setRecurrentAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - ub.SetRecurrent(a, true) - return -} - -func unsetRecurrentAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - ub.SetRecurrent(a, false) - return -} - -func allowNegativeAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - ub.AllowNegative = true - return -} - -func denyNegativeAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - ub.AllowNegative = false - return -} - -func resetAccountAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - return genericReset(ub) -} - -func topupResetAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - if ub.BalanceMap == nil { // Init the map since otherwise will get error if nil - ub.BalanceMap = make(map[string]Balances) - } - c := a.Clone() - genericMakeNegative(c) - err = genericDebit(ub, c, true) - a.balanceValue = c.balanceValue - return -} - -func topupAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - c := a.Clone() - genericMakeNegative(c) - err = genericDebit(ub, c, false) - a.balanceValue = c.balanceValue - return -} - -func debitResetAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - if ub.BalanceMap == nil { // Init the map since otherwise will get error if nil - ub.BalanceMap = make(map[string]Balances) - } - return genericDebit(ub, a, true) -} - -func debitAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - err = genericDebit(ub, a, false) - return -} - -func resetCountersAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if ub == nil { - return errors.New("nil account") - } - if ub.UnitCounters != nil { - ub.UnitCounters.resetCounters(a) - } - return -} - -func genericMakeNegative(a *Action) { - if a.Balance != nil && a.Balance.GetValue() > 0 { // only apply if not allready negative - a.Balance.SetValue(-a.Balance.GetValue()) - } -} - -func genericDebit(ub *Account, a *Action, reset bool) (err error) { - if ub == nil { - return errors.New("nil account") - } - if ub.BalanceMap == nil { - ub.BalanceMap = make(map[string]Balances) - } - return ub.debitBalanceAction(a, reset, false) -} - -func enableAccountAction(acc *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if acc == nil { - return errors.New("nil account") - } - acc.Disabled = false - return -} - -func disableAccountAction(acc *Account, a *Action, acs Actions, extraData interface{}) (err error) { - if acc == nil { - return errors.New("nil account") - } - acc.Disabled = true - return -} - -/*func enableDisableBalanceAction(ub *Account, sq *CDRStatsQueueTriggered, a *Action, acs Actions) (err error) { - if ub == nil { - return errors.New("nil account") - } - ub.enableDisableBalanceAction(a) - return -}*/ - -func genericReset(ub *Account) error { - for k := range ub.BalanceMap { - ub.BalanceMap[k] = Balances{&Balance{Value: 0}} - } - ub.InitCounters() - ub.ResetActionTriggers(nil) - return nil -} - -func getOneData(ub *Account, extraData interface{}) ([]byte, error) { - switch { - case ub != nil: - return json.Marshal(ub) - case extraData != nil: - return json.Marshal(extraData) - } - return nil, nil -} - -func callURL(ub *Account, a *Action, acs Actions, extraData interface{}) error { - body, err := getOneData(ub, extraData) - if err != nil { - return err - } - pstr, err := NewHTTPPoster(config.CgrConfig().GeneralCfg().ReplyTimeout, a.ExtraParameters, - utils.ContentJSON, config.CgrConfig().GeneralCfg().PosterAttempts) - if err != nil { - return err - } - err = pstr.PostValues(body, make(http.Header)) - if err != nil && config.CgrConfig().GeneralCfg().FailedPostsDir != utils.MetaNone { - AddFailedPost(a.ExtraParameters, utils.MetaHTTPjson, utils.ActionsPoster+utils.HierarchySep+a.ActionType, body, make(map[string]interface{})) - err = nil - } - return err -} - -// Does not block for posts, no error reports -func callURLAsync(ub *Account, a *Action, acs Actions, extraData interface{}) error { - body, err := getOneData(ub, extraData) - if err != nil { - return err - } - pstr, err := NewHTTPPoster(config.CgrConfig().GeneralCfg().ReplyTimeout, a.ExtraParameters, - utils.ContentJSON, config.CgrConfig().GeneralCfg().PosterAttempts) - if err != nil { - return err - } - go func() { - err := pstr.PostValues(body, make(http.Header)) - if err != nil && config.CgrConfig().GeneralCfg().FailedPostsDir != utils.MetaNone { - AddFailedPost(a.ExtraParameters, utils.MetaHTTPjson, utils.ActionsPoster+utils.HierarchySep+a.ActionType, body, make(map[string]interface{})) - } - }() - return nil -} - -// Mails the balance hitting the threshold towards predefined list of addresses -func mailAsync(ub *Account, a *Action, acs Actions, extraData interface{}) error { - cgrCfg := config.CgrConfig() - params := strings.Split(a.ExtraParameters, string(utils.CSVSep)) - if len(params) == 0 { - return errors.New("Unconfigured parameters for mail action") - } - toAddrs := strings.Split(params[0], string(utils.FallbackSep)) - toAddrStr := "" - for idx, addr := range toAddrs { - if idx != 0 { - toAddrStr += ", " - } - toAddrStr += addr - } - var message []byte - if ub != nil { - balJsn, err := json.Marshal(ub) - if err != nil { - return err - } - message = []byte(fmt.Sprintf("To: %s\r\nSubject: [CGR Notification] Threshold hit on Balance: %s\r\n\r\nTime: \r\n\t%s\r\n\r\nBalance:\r\n\t%s\r\n\r\nYours faithfully,\r\nCGR Balance Monitor\r\n", toAddrStr, ub.ID, time.Now(), balJsn)) - } - auth := smtp.PlainAuth("", cgrCfg.MailerCfg().MailerAuthUser, cgrCfg.MailerCfg().MailerAuthPass, strings.Split(cgrCfg.MailerCfg().MailerServer, ":")[0]) // We only need host part, so ignore port - go func() { - for i := 0; i < 5; i++ { // Loop so we can increase the success rate on best effort - if err := smtp.SendMail(cgrCfg.MailerCfg().MailerServer, auth, cgrCfg.MailerCfg().MailerFromAddr, toAddrs, message); err == nil { - break - } else if i == 4 { - if ub != nil { - utils.Logger.Warning(fmt.Sprintf(" WARNING: Failed emailing, params: [%s], error: [%s], BalanceId: %s", a.ExtraParameters, err.Error(), ub.ID)) - } - break - } - time.Sleep(time.Duration(i) * time.Minute) - } - }() - return nil -} - -func setddestinations(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - var ddcDestID string - for _, bchain := range ub.BalanceMap { - for _, b := range bchain { - for destID := range b.DestinationIDs { - if strings.HasPrefix(destID, utils.MetaDDC) { - ddcDestID = destID - break - } - } - if ddcDestID != "" { - break - } - } - if ddcDestID != "" { - break - } - } - if ddcDestID != "" { - destinations := utils.NewStringSet(nil) - for _, statID := range strings.Split(a.ExtraParameters, utils.InfieldSep) { - if statID == utils.EmptyString { - continue - } - var sts StatQueue - if err = connMgr.Call(config.CgrConfig().RalsCfg().StatSConns, nil, utils.StatSv1GetStatQueue, - &utils.TenantIDWithAPIOpts{ - TenantID: &utils.TenantID{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: statID, - }, - }, &sts); err != nil { - return - } - ddcIface, has := sts.SQMetrics[utils.MetaDDC] - if !has { - continue - } - ddcMetric := ddcIface.(*StatDDC) - - // make slice from prefixes - // Review here prefixes - for p := range ddcMetric.FieldValues { - destinations.Add(p) - } - } - - newDest := &Destination{Id: ddcDestID, Prefixes: destinations.AsSlice()} - oldDest, err := dm.GetDestination(ddcDestID, true, true, utils.NonTransactional) - if err != nil { - return err - } - // update destid in storage - if err = dm.SetDestination(newDest, utils.NonTransactional); err != nil { - return err - } - if err = dm.CacheDataFromDB(utils.DestinationPrefix, []string{ddcDestID}, true); err != nil { - return err - } - - if err == nil && oldDest != nil { - if err = dm.UpdateReverseDestination(oldDest, newDest, utils.NonTransactional); err != nil { - return err - } - } - } else { - return utils.ErrNotFound - } - return nil -} - -func removeBalanceAction(ub *Account, a *Action, acs Actions, extraData interface{}) error { - if ub == nil { - return fmt.Errorf("nil account for %s action", utils.ToJSON(a)) - } - if _, exists := ub.BalanceMap[a.Balance.GetType()]; !exists { - return utils.ErrNotFound - } - bChain := ub.BalanceMap[a.Balance.GetType()] - found := false - for i := 0; i < len(bChain); i++ { - if bChain[i].MatchFilter(a.Balance, false, false) { - // delete without preserving order - bChain[i] = bChain[len(bChain)-1] - bChain = bChain[:len(bChain)-1] - i-- - found = true - } - } - ub.BalanceMap[a.Balance.GetType()] = bChain - if !found { - return utils.ErrNotFound - } - return nil -} - -func setBalanceAction(ub *Account, a *Action, acs Actions, extraData interface{}) error { - if ub == nil { - return fmt.Errorf("nil account for %s action", utils.ToJSON(a)) - } - return ub.setBalanceAction(a) -} - -func transferMonetaryDefaultAction(ub *Account, a *Action, acs Actions, extraData interface{}) error { - if ub == nil { - utils.Logger.Err("*transfer_monetary_default called without account") - return utils.ErrAccountNotFound - } - if _, exists := ub.BalanceMap[utils.MetaMonetary]; !exists { - return utils.ErrNotFound - } - defaultBalance := ub.GetDefaultMoneyBalance() - bChain := ub.BalanceMap[utils.MetaMonetary] - for _, balance := range bChain { - if balance.Uuid != defaultBalance.Uuid && - balance.ID != defaultBalance.ID && // extra caution - balance.MatchFilter(a.Balance, false, false) { - if balance.Value > 0 { - defaultBalance.Value += balance.Value - balance.Value = 0 - } - } - } - return nil -} - -// RPCRequest used by rpc action -type RPCRequest struct { - Address string - Transport string - Method string - Attempts int - Async bool - Params map[string]interface{} -} - -/* -<< .Object.Property >> - -Property can be a attribute or a method both used without () -Please also note the initial dot . - -Currently there are following objects that can be used: - -Account - the account that this action is called on -Action - the action with all it's attributs -Actions - the list of actions in the current action set -Sq - CDRStatsQueueTriggered object - -We can actually use everythiong that go templates offer. You can read more here: https://golang.org/pkg/text/template/ -*/ -func cgrRPCAction(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - // parse template - tmpl := template.New("extra_params") - tmpl.Delims("<<", ">>") - if tmpl, err = tmpl.Parse(a.ExtraParameters); err != nil { - utils.Logger.Err(fmt.Sprintf("error parsing *cgr_rpc template: %s", err.Error())) - return - } - var buf bytes.Buffer - if err = tmpl.Execute(&buf, struct { - Account *Account - Action *Action - Actions Actions - ExtraData interface{} - }{ub, a, acs, extraData}); err != nil { - utils.Logger.Err(fmt.Sprintf("error executing *cgr_rpc template %s:", err.Error())) - return - } - var req RPCRequest - if err = json.Unmarshal(buf.Bytes(), &req); err != nil { - return - } - var params *utils.RpcParams - if params, err = utils.GetRpcParams(req.Method); err != nil { - return - } - var client rpcclient.ClientConnector - if req.Address == utils.MetaInternal { - client = params.Object.(rpcclient.ClientConnector) - } else if client, err = rpcclient.NewRPCClient(utils.TCP, req.Address, false, "", "", "", - req.Attempts, 0, config.CgrConfig().GeneralCfg().ConnectTimeout, - config.CgrConfig().GeneralCfg().ReplyTimeout, req.Transport, - nil, false, nil); err != nil { - return - } - in, out := params.InParam, params.OutParam - //utils.Logger.Info("Params: " + utils.ToJSON(req.Params)) - //p, err := utils.FromMapStringInterfaceValue(req.Params, in) - if err = mapstructure.Decode(req.Params, in); err != nil { - utils.Logger.Info("<*cgr_rpc> err: " + err.Error()) - return - } - if in == nil { - utils.Logger.Info(fmt.Sprintf("<*cgr_rpc> nil params err: req.Params: %+v params: %+v", req.Params, params)) - return utils.ErrParserError - } - utils.Logger.Info(fmt.Sprintf("<*cgr_rpc> calling: %s with: %s and result %v", req.Method, utils.ToJSON(in), out)) - if !req.Async { - err = client.Call(req.Method, in, out) - utils.Logger.Info(fmt.Sprintf("<*cgr_rpc> result: %s err: %v", utils.ToJSON(out), err)) - return - } - go func() { - err := client.Call(req.Method, in, out) - utils.Logger.Info(fmt.Sprintf("<*cgr_rpc> result: %s err: %v", utils.ToJSON(out), err)) - }() - return -} - -func topupZeroNegativeAction(ub *Account, a *Action, acs Actions, extraData interface{}) error { - if ub == nil { - return errors.New("nil account") - } - if ub.BalanceMap == nil { - ub.BalanceMap = make(map[string]Balances) - } - return ub.debitBalanceAction(a, false, true) -} - -func setExpiryAction(ub *Account, a *Action, acs Actions, extraData interface{}) error { - if ub == nil { - return errors.New("nil account") - } - balanceType := a.Balance.GetType() - for _, b := range ub.BalanceMap[balanceType] { - if b.MatchFilter(a.Balance, false, true) { - b.ExpirationDate = a.Balance.GetExpirationDate() - } - } - return nil -} - -// publishAccount will publish the account as well as each balance received to ThresholdS -func publishAccount(ub *Account, a *Action, acs Actions, extraData interface{}) error { - if ub == nil { - return errors.New("nil account") - } - ub.Publish() - return nil -} - -// Actions used to store actions according to weight -type Actions []*Action - -func (apl Actions) Len() int { - return len(apl) -} - -func (apl Actions) Swap(i, j int) { - apl[i], apl[j] = apl[j], apl[i] -} - -// we need higher weights earlyer in the list -func (apl Actions) Less(j, i int) bool { - return apl[i].Weight < apl[j].Weight -} - -// Sort used to implement sort interface -func (apl Actions) Sort() { - sort.Sort(apl) -} - -// Clone returns a clone from object -func (apl Actions) Clone() (interface{}, error) { - if apl == nil { - return nil, nil - } - cln := make(Actions, len(apl)) - for i, action := range apl { - cln[i] = action.Clone() - } - return cln, nil -} - -// newCdrLogProvider constructs a DataProvider -func newCdrLogProvider(acnt *Account, action *Action) (dP utils.DataProvider) { - dP = &cdrLogProvider{acnt: acnt, action: action, cache: utils.MapStorage{}} - return -} - -// cdrLogProvider implements utils.DataProvider so we can pass it to filters -type cdrLogProvider struct { - acnt *Account - action *Action - cache utils.MapStorage -} - -// String is part of utils.DataProvider interface -// when called, it will display the already parsed values out of cache -func (cdrP *cdrLogProvider) String() string { - return utils.ToJSON(cdrP) -} - -// FieldAsInterface is part of utils.DataProvider interface -func (cdrP *cdrLogProvider) FieldAsInterface(fldPath []string) (data interface{}, err error) { - if data, err = cdrP.cache.FieldAsInterface(fldPath); err == nil || - err != utils.ErrNotFound { // item found in cache - return - } - err = nil // cancel previous err - if len(fldPath) == 2 { - switch fldPath[0] { - case utils.MetaAcnt: - switch fldPath[1] { - case utils.AccountID: - data = cdrP.acnt.ID - case utils.Tenant: - tntAcnt := new(utils.TenantAccount) // Init with empty values - if cdrP.acnt != nil { - if tntAcnt, err = utils.NewTAFromAccountKey(cdrP.acnt.ID); err != nil { - return - } - } - data = tntAcnt.Tenant - case utils.AccountField: - tntAcnt := new(utils.TenantAccount) // Init with empty values - if cdrP.acnt != nil { - if tntAcnt, err = utils.NewTAFromAccountKey(cdrP.acnt.ID); err != nil { - return - } - } - data = tntAcnt.Account - case utils.BalanceType: - data = cdrP.action.Balance.GetType() - case utils.BalanceUUID: - data = cdrP.action.Balance.CreateBalance().Uuid - case utils.BalanceID: - data = cdrP.action.Balance.CreateBalance().ID - case utils.BalanceValue: - data = strconv.FormatFloat(cdrP.action.balanceValue, 'f', -1, 64) - case utils.DestinationIDs: - data = cdrP.action.Balance.CreateBalance().DestinationIDs.String() - case utils.ExtraParameters: - data = cdrP.action.ExtraParameters - case utils.RatingSubject: - data = cdrP.action.Balance.CreateBalance().RatingSubject - case utils.Category: - data = cdrP.action.Balance.Categories.String() - case utils.SharedGroups: - data = cdrP.action.Balance.SharedGroups.String() - } - case utils.MetaAct: - switch fldPath[1] { - case utils.ActionID: - data = cdrP.action.Id - case utils.ActionType: - data = cdrP.action.ActionType - case utils.ActionValue: - data = strconv.FormatFloat(cdrP.action.Balance.CreateBalance().GetValue(), 'f', -1, 64) - } - } - } else { - data = fldPath[0] - } - cdrP.cache.Set(fldPath, data) - return -} - -// FieldAsString is part of utils.DataProvider interface -func (cdrP *cdrLogProvider) FieldAsString(fldPath []string) (data string, err error) { - var valIface interface{} - valIface, err = cdrP.FieldAsInterface(fldPath) - if err != nil { - return - } - return utils.IfaceAsString(valIface), nil -} - -// RemoteHost is part of utils.DataProvider interface -func (cdrP *cdrLogProvider) RemoteHost() net.Addr { - return utils.LocalAddr() -} - -func removeSessionCosts(_ *Account, action *Action, _ Actions, _ interface{}) error { // FiltersID;inlineFilter - tenant := config.CgrConfig().GeneralCfg().DefaultTenant - smcFilter := new(utils.SMCostFilter) - for _, fltrID := range strings.Split(action.ExtraParameters, utils.InfieldSep) { - if len(fltrID) == 0 { - continue - } - fltr, err := dm.GetFilter(tenant, fltrID, true, true, utils.NonTransactional) - if err != nil { - utils.Logger.Warning(fmt.Sprintf("<%s> Error: %s for filter: %s in action: <%s>", - utils.Actions, err.Error(), fltrID, utils.MetaRemoveSessionCosts)) - continue - } - for _, rule := range fltr.Rules { - smcFilter, err = utils.AppendToSMCostFilter(smcFilter, rule.Type, rule.Element, rule.Values, config.CgrConfig().GeneralCfg().DefaultTimezone) - if err != nil { - utils.Logger.Warning(fmt.Sprintf("<%s> %s in action: <%s>", utils.Actions, err.Error(), utils.MetaRemoveSessionCosts)) - } - } - } - return cdrStorage.RemoveSMCosts(smcFilter) -} - -func removeExpired(acc *Account, action *Action, _ Actions, extraData interface{}) error { - if acc == nil { - return fmt.Errorf("nil account for %s action", utils.ToJSON(action)) - } - - bChain, exists := acc.BalanceMap[action.Balance.GetType()] - if !exists { - return utils.ErrNotFound - } - - found := false - for i := 0; i < len(bChain); i++ { - if bChain[i].IsExpiredAt(time.Now()) { - // delete without preserving order - bChain[i] = bChain[len(bChain)-1] - bChain = bChain[:len(bChain)-1] - i-- - found = true - } - } - acc.BalanceMap[action.Balance.GetType()] = bChain - if !found { - return utils.ErrNotFound - } - return nil -} - -func postEvent(ub *Account, a *Action, acs Actions, extraData interface{}) error { - body, err := json.Marshal(extraData) - if err != nil { - return err - } - pstr, err := NewHTTPPoster(config.CgrConfig().GeneralCfg().ReplyTimeout, a.ExtraParameters, - utils.ContentJSON, config.CgrConfig().GeneralCfg().PosterAttempts) - if err != nil { - return err - } - err = pstr.PostValues(body, make(http.Header)) - if err != nil && config.CgrConfig().GeneralCfg().FailedPostsDir != utils.MetaNone { - AddFailedPost(a.ExtraParameters, utils.MetaHTTPjson, utils.ActionsPoster+utils.HierarchySep+a.ActionType, body, make(map[string]interface{})) - err = nil - } - return err -} - -// resetAccountCDR resets the account out of values from CDR -func resetAccountCDR(ub *Account, action *Action, acts Actions, _ interface{}) error { - if ub == nil { - return errors.New("nil account") - } - if cdrStorage == nil { - return fmt.Errorf("nil cdrStorage for %s action", utils.ToJSON(action)) - } - account := ub.GetID() - filter := &utils.CDRsFilter{ - Accounts: []string{account}, - NotCosts: []float64{-1}, - OrderBy: fmt.Sprintf("%s%sdesc", utils.OrderID, utils.InfieldSep), - Paginator: utils.Paginator{Limit: utils.IntPointer(1)}, - } - cdrs, _, err := cdrStorage.GetCDRs(filter, false) - if err != nil { - return err - } - cd := cdrs[0].CostDetails - if cd == nil { - return errors.New("nil CostDetails") - } - acs := cd.AccountSummary - if acs == nil { - return errors.New("nil AccountSummary") - } - for _, bsum := range acs.BalanceSummaries { - if bsum == nil { - continue - } - if err := ub.setBalanceAction(&Action{ - Balance: &BalanceFilter{ - Uuid: &bsum.UUID, - ID: &bsum.ID, - Type: &bsum.Type, - Value: &utils.ValueFormula{Static: bsum.Value}, - Disabled: &bsum.Disabled, - }, - }); err != nil { - utils.Logger.Warning(fmt.Sprintf("<%s> Error %s setting balance %s for account: %s", utils.Actions, err, bsum.UUID, account)) - } - } - return nil -} - -func export(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - var cgrEv *utils.CGREvent - switch { - case ub != nil: - cgrEv = &utils.CGREvent{ - Tenant: utils.NewTenantID(ub.ID).Tenant, - ID: utils.GenUUID(), - Event: map[string]interface{}{ - utils.AccountField: ub.ID, - utils.EventType: utils.AccountUpdate, - utils.EventSource: utils.AccountService, - utils.AllowNegative: ub.AllowNegative, - utils.Disabled: ub.Disabled, - utils.BalanceMap: ub.BalanceMap, - utils.UnitCounters: ub.UnitCounters, - utils.ActionTriggers: ub.ActionTriggers, - utils.UpdateTime: ub.UpdateTime, - }, - - APIOpts: map[string]interface{}{ - utils.MetaEventType: utils.AccountUpdate, - }, - } - case extraData != nil: - ev, canCast := extraData.(*utils.CGREvent) - if !canCast { - return - } - cgrEv = ev // only export CGREvents - default: - return // nothing to post - } - args := &utils.CGREventWithEeIDs{ - EeIDs: strings.Split(a.ExtraParameters, utils.InfieldSep), - CGREvent: cgrEv, - } - var rply map[string]map[string]interface{} - return connMgr.Call(config.CgrConfig().ApierCfg().EEsConns, nil, - utils.EeSv1ProcessEvent, args, &rply) -} - -func resetThreshold(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - args := &utils.TenantIDWithAPIOpts{ - TenantID: utils.NewTenantID(a.ExtraParameters), - } - var rply string - return connMgr.Call(config.CgrConfig().SchedulerCfg().ThreshSConns, nil, - utils.ThresholdSv1ResetThreshold, args, &rply) -} - -func resetStatQueue(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - args := &utils.TenantIDWithAPIOpts{ - TenantID: utils.NewTenantID(a.ExtraParameters), - } - var rply string - return connMgr.Call(config.CgrConfig().SchedulerCfg().StatSConns, nil, - utils.StatSv1ResetStatQueue, args, &rply) -} - -func remoteSetAccount(ub *Account, a *Action, acs Actions, extraData interface{}) (err error) { - client := &http.Client{Transport: httpPstrTransport} - var resp *http.Response - req := new(bytes.Buffer) - if err = json.NewEncoder(req).Encode(ub); err != nil { - return - } - if resp, err = client.Post(a.ExtraParameters, "application/json", req); err != nil { - return - } - acc := new(Account) - err = json.NewDecoder(resp.Body).Decode(acc) - if err != nil { - return - } - if len(acc.BalanceMap) != 0 { - *ub = *acc - } - return -} diff --git a/engine/responder.go b/engine/responder.go index b149669de..81f5743cd 100644 --- a/engine/responder.go +++ b/engine/responder.go @@ -19,360 +19,14 @@ along with this program. If not, see package engine import ( - "fmt" "reflect" "strings" - "sync" - "time" - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/guardian" "github.com/cgrates/cgrates/utils" ) type Responder struct { - ShdChan *utils.SyncedChan - Timeout time.Duration - Timezone string - MaxComputedUsage map[string]time.Duration - maxComputedUsageMutex sync.RWMutex // used for MaxComputedUsage reload -} - -// SetMaxComputedUsage sets MaxComputedUsage, used for config reload (is thread safe) -func (rs *Responder) SetMaxComputedUsage(mx map[string]time.Duration) { - rs.maxComputedUsageMutex.Lock() - rs.MaxComputedUsage = make(map[string]time.Duration) - for k, v := range mx { - rs.MaxComputedUsage[k] = v - } - rs.maxComputedUsageMutex.Unlock() -} - -// usageAllowed checks requested usage against configured MaxComputedUsage -func (rs *Responder) usageAllowed(tor string, reqUsage time.Duration) (allowed bool) { - rs.maxComputedUsageMutex.RLock() - mcu, has := rs.MaxComputedUsage[tor] - if !has { - mcu = rs.MaxComputedUsage[utils.MetaAny] - } - rs.maxComputedUsageMutex.RUnlock() - if reqUsage <= mcu { - allowed = true - } - return -} - -/* -RPC method that provides the external RPC interface for getting the rating information. -*/ -func (rs *Responder) GetCost(arg *CallDescriptorWithAPIOpts, reply *CallCost) (err error) { - // RPC caching - if arg.CgrID != utils.EmptyString && config.CgrConfig().CacheCfg().Partitions[utils.CacheRPCResponses].Limit != 0 { - cacheKey := utils.ConcatenatedKey(utils.ResponderGetCost, arg.CgrID) - refID := guardian.Guardian.GuardIDs("", - config.CgrConfig().GeneralCfg().LockingTimeout, cacheKey) // RPC caching needs to be atomic - defer guardian.Guardian.UnguardIDs(refID) - - if itm, has := Cache.Get(utils.CacheRPCResponses, cacheKey); has { - cachedResp := itm.(*utils.CachedRPCResponse) - if cachedResp.Error == nil { - *reply = *cachedResp.Result.(*CallCost) - } - return cachedResp.Error - } - defer Cache.Set(utils.CacheRPCResponses, cacheKey, - &utils.CachedRPCResponse{Result: reply, Error: err}, - nil, true, utils.NonTransactional) - } - // end of RPC caching - if arg.Tenant == "" { - arg.Tenant = config.CgrConfig().GeneralCfg().DefaultTenant - } - if arg.Category == "" { - arg.Category = config.CgrConfig().GeneralCfg().DefaultCategory - } - if arg.Subject == "" { - arg.Subject = arg.Account - } - if !rs.usageAllowed(arg.ToR, arg.GetDuration()) { - return utils.ErrMaxUsageExceeded - } - r, e := guardian.Guardian.Guard(func() (interface{}, error) { - return arg.GetCost() - }, config.CgrConfig().GeneralCfg().LockingTimeout, utils.AccountPrefix+arg.GetAccountKey()) - if r != nil { - *reply = *r.(*CallCost) - } - if e != nil { - return e - } - return -} - -// GetCostOnRatingPlans is used by RouteS to calculate the cost -// Receive a list of RatingPlans and pick the first without error -func (rs *Responder) GetCostOnRatingPlans(arg *utils.GetCostOnRatingPlansArgs, reply *map[string]interface{}) (err error) { - tnt := arg.Tenant - if tnt == utils.EmptyString { - tnt = config.CgrConfig().GeneralCfg().DefaultTenant - } - for _, rp := range arg.RatingPlanIDs { // loop through RatingPlans until we find one without errors - rPrfl := &RatingProfile{ - Id: utils.ConcatenatedKey(utils.MetaOut, - tnt, utils.MetaTmp, arg.Subject), - RatingPlanActivations: RatingPlanActivations{ - &RatingPlanActivation{ - ActivationTime: arg.SetupTime, - RatingPlanId: rp, - }, - }, - } - var cc *CallCost - if _, errGuard := guardian.Guardian.Guard(func() (_ interface{}, errGuard error) { // prevent cache data concurrency - - // force cache set so it can be picked by calldescriptor for cost calculation - if errGuard := Cache.Set(utils.CacheRatingProfilesTmp, rPrfl.Id, rPrfl, nil, - true, utils.NonTransactional); errGuard != nil { - return nil, errGuard - } - cd := &CallDescriptor{ - Category: utils.MetaTmp, - Tenant: tnt, - Subject: arg.Subject, - Account: arg.Account, - Destination: arg.Destination, - TimeStart: arg.SetupTime, - TimeEnd: arg.SetupTime.Add(arg.Usage), - DurationIndex: arg.Usage, - } - cc, err = cd.GetCost() - if errGuard := Cache.Remove(utils.CacheRatingProfilesTmp, rPrfl.Id, - true, utils.NonTransactional); errGuard != nil { // Remove here so we don't overload memory - return nil, errGuard - } - return - - }, config.CgrConfig().GeneralCfg().LockingTimeout, utils.ConcatenatedKey(utils.CacheRatingProfilesTmp, rPrfl.Id)); errGuard != nil { - return errGuard - } - - if err != nil { - if err != utils.ErrNotFound { - return err - } - continue - } - *reply = map[string]interface{}{ - utils.Cost: cc.Cost, - utils.RatingPlanID: rp, - } - return nil - } - return -} - -func (rs *Responder) Debit(arg *CallDescriptorWithAPIOpts, reply *CallCost) (err error) { - // RPC caching - if arg.Tenant == utils.EmptyString { - arg.Tenant = config.CgrConfig().GeneralCfg().DefaultTenant - } - if arg.CgrID != utils.EmptyString && config.CgrConfig().CacheCfg().Partitions[utils.CacheRPCResponses].Limit != 0 { - cacheKey := utils.ConcatenatedKey(utils.ResponderDebit, arg.CgrID) - refID := guardian.Guardian.GuardIDs("", - config.CgrConfig().GeneralCfg().LockingTimeout, cacheKey) // RPC caching needs to be atomic - defer guardian.Guardian.UnguardIDs(refID) - - if itm, has := Cache.Get(utils.CacheRPCResponses, cacheKey); has { - cachedResp := itm.(*utils.CachedRPCResponse) - if cachedResp.Error == nil { - *reply = *cachedResp.Result.(*CallCost) - } - return cachedResp.Error - } - defer Cache.Set(utils.CacheRPCResponses, cacheKey, - &utils.CachedRPCResponse{Result: reply, Error: err}, - nil, true, utils.NonTransactional) - } - // end of RPC caching - - if arg.Subject == "" { - arg.Subject = arg.Account - } - if !rs.usageAllowed(arg.ToR, arg.GetDuration()) { - err = utils.ErrMaxUsageExceeded - return - } - var r *CallCost - if r, err = arg.Debit(); err != nil { - return - } - if r != nil { - *reply = *r - } - return -} - -func (rs *Responder) MaxDebit(arg *CallDescriptorWithAPIOpts, reply *CallCost) (err error) { - // RPC caching - if arg.Tenant == utils.EmptyString { - arg.Tenant = config.CgrConfig().GeneralCfg().DefaultTenant - } - if arg.CgrID != utils.EmptyString && config.CgrConfig().CacheCfg().Partitions[utils.CacheRPCResponses].Limit != 0 { - cacheKey := utils.ConcatenatedKey(utils.ResponderMaxDebit, arg.CgrID) - refID := guardian.Guardian.GuardIDs("", - config.CgrConfig().GeneralCfg().LockingTimeout, cacheKey) // RPC caching needs to be atomic - defer guardian.Guardian.UnguardIDs(refID) - - if itm, has := Cache.Get(utils.CacheRPCResponses, cacheKey); has { - cachedResp := itm.(*utils.CachedRPCResponse) - if cachedResp.Error == nil { - *reply = *cachedResp.Result.(*CallCost) - } - return cachedResp.Error - } - defer Cache.Set(utils.CacheRPCResponses, cacheKey, - &utils.CachedRPCResponse{Result: reply, Error: err}, - nil, true, utils.NonTransactional) - } - // end of RPC caching - if arg.Subject == "" { - arg.Subject = arg.Account - } - if !rs.usageAllowed(arg.ToR, arg.GetDuration()) { - err = utils.ErrMaxUsageExceeded - return - } - var r *CallCost - if r, err = arg.MaxDebit(); err != nil { - return - } - if r != nil { - *reply = *r - } - return -} - -func (rs *Responder) RefundIncrements(arg *CallDescriptorWithAPIOpts, reply *Account) (err error) { - // RPC caching - if arg.Tenant == utils.EmptyString { - arg.Tenant = config.CgrConfig().GeneralCfg().DefaultTenant - } - if arg.CgrID != utils.EmptyString && config.CgrConfig().CacheCfg().Partitions[utils.CacheRPCResponses].Limit != 0 { - cacheKey := utils.ConcatenatedKey(utils.ResponderRefundIncrements, arg.CgrID) - refID := guardian.Guardian.GuardIDs("", - config.CgrConfig().GeneralCfg().LockingTimeout, cacheKey) // RPC caching needs to be atomic - defer guardian.Guardian.UnguardIDs(refID) - - if itm, has := Cache.Get(utils.CacheRPCResponses, cacheKey); has { - cachedResp := itm.(*utils.CachedRPCResponse) - if cachedResp.Error == nil { - *reply = *cachedResp.Result.(*Account) - } - return cachedResp.Error - } - defer Cache.Set(utils.CacheRPCResponses, cacheKey, - &utils.CachedRPCResponse{Result: reply, Error: err}, - nil, true, utils.NonTransactional) - } - // end of RPC caching - - if arg.Subject == "" { - arg.Subject = arg.Account - } - if !rs.usageAllowed(arg.ToR, arg.GetDuration()) { - err = utils.ErrMaxUsageExceeded - return - } - var acnt *Account - if acnt, err = arg.RefundIncrements(); err != nil { - return - } - if acnt != nil { - *reply = *acnt - } - return -} - -func (rs *Responder) RefundRounding(arg *CallDescriptorWithAPIOpts, reply *float64) (err error) { - // RPC caching - if arg.Tenant == utils.EmptyString { - arg.Tenant = config.CgrConfig().GeneralCfg().DefaultTenant - } - if arg.CgrID != utils.EmptyString && config.CgrConfig().CacheCfg().Partitions[utils.CacheRPCResponses].Limit != 0 { - cacheKey := utils.ConcatenatedKey(utils.ResponderRefundRounding, arg.CgrID) - refID := guardian.Guardian.GuardIDs("", - config.CgrConfig().GeneralCfg().LockingTimeout, cacheKey) // RPC caching needs to be atomic - defer guardian.Guardian.UnguardIDs(refID) - - if itm, has := Cache.Get(utils.CacheRPCResponses, cacheKey); has { - cachedResp := itm.(*utils.CachedRPCResponse) - if cachedResp.Error == nil { - *reply = *cachedResp.Result.(*float64) - } - return cachedResp.Error - } - defer Cache.Set(utils.CacheRPCResponses, cacheKey, - &utils.CachedRPCResponse{Result: reply, Error: err}, - nil, true, utils.NonTransactional) - } - - if arg.Subject == "" { - arg.Subject = arg.Account - } - if !rs.usageAllowed(arg.ToR, arg.GetDuration()) { - err = utils.ErrMaxUsageExceeded - return - } - err = arg.RefundRounding() - return -} - -func (rs *Responder) GetMaxSessionTime(arg *CallDescriptorWithAPIOpts, reply *time.Duration) (err error) { - if arg.Tenant == utils.EmptyString { - arg.Tenant = config.CgrConfig().GeneralCfg().DefaultTenant - } - if arg.Subject == "" { - arg.Subject = arg.Account - } - if !rs.usageAllowed(arg.ToR, arg.GetDuration()) { - return utils.ErrMaxUsageExceeded - } - *reply, err = arg.GetMaxSessionDuration() - return -} - -func (rs *Responder) GetMaxSessionTimeOnAccounts(arg *utils.GetMaxSessionTimeOnAccountsArgs, - reply *map[string]interface{}) (err error) { - var maxDur time.Duration - tnt := arg.Tenant - if tnt == utils.EmptyString { - tnt = config.CgrConfig().GeneralCfg().DefaultTenant - } - for _, anctID := range arg.AccountIDs { - cd := &CallDescriptor{ - Category: utils.MetaRoutes, - Tenant: tnt, - Subject: arg.Subject, - Account: anctID, - Destination: arg.Destination, - TimeStart: arg.SetupTime, - TimeEnd: arg.SetupTime.Add(arg.Usage), - DurationIndex: arg.Usage, - } - if maxDur, err = cd.GetMaxSessionDuration(); err != nil { - utils.Logger.Warning( - fmt.Sprintf("<%s> ignoring cost for account: %s, err: %s", - utils.Responder, anctID, err.Error())) - } else { - *reply = map[string]interface{}{ - utils.CapMaxUsage: maxDur, - utils.Cost: 0.0, - utils.AccountField: anctID, - } - return nil - } - } - return + ShdChan *utils.SyncedChan } func (rs *Responder) Shutdown(arg *utils.TenantWithAPIOpts, reply *string) (err error) { diff --git a/services/apierv1.go b/services/apierv1.go index b27f83538..aadc192c6 100644 --- a/services/apierv1.go +++ b/services/apierv1.go @@ -34,35 +34,32 @@ import ( func NewAPIerSv1Service(cfg *config.CGRConfig, dm *DataDBService, storDB *StorDBService, filterSChan chan *engine.FilterS, server *cores.Server, - responderService *ResponderService, internalAPIerSv1Chan chan rpcclient.ClientConnector, connMgr *engine.ConnManager, anz *AnalyzerService, srvDep map[string]*sync.WaitGroup) *APIerSv1Service { return &APIerSv1Service{ - connChan: internalAPIerSv1Chan, - cfg: cfg, - dm: dm, - storDB: storDB, - filterSChan: filterSChan, - server: server, - responderService: responderService, - connMgr: connMgr, - APIerSv1Chan: make(chan *v1.APIerSv1, 1), - anz: anz, - srvDep: srvDep, + connChan: internalAPIerSv1Chan, + cfg: cfg, + dm: dm, + storDB: storDB, + filterSChan: filterSChan, + server: server, + connMgr: connMgr, + APIerSv1Chan: make(chan *v1.APIerSv1, 1), + anz: anz, + srvDep: srvDep, } } // APIerSv1Service implements Service interface type APIerSv1Service struct { sync.RWMutex - cfg *config.CGRConfig - dm *DataDBService - storDB *StorDBService - filterSChan chan *engine.FilterS - server *cores.Server - responderService *ResponderService - connMgr *engine.ConnManager + cfg *config.CGRConfig + dm *DataDBService + storDB *StorDBService + filterSChan chan *engine.FilterS + server *cores.Server + connMgr *engine.ConnManager api *v1.APIerSv1 connChan chan rpcclient.ClientConnector @@ -92,8 +89,6 @@ func (apiService *APIerSv1Service) Start() (err error) { apiService.storDB.RegisterSyncChan(storDBChan) stordb := <-storDBChan - respChan := make(chan *engine.Responder, 1) - apiService.responderService.RegisterSyncChan(apiService.ServiceName(), respChan) apiService.Lock() defer apiService.Unlock() @@ -105,9 +100,6 @@ func (apiService *APIerSv1Service) Start() (err error) { FilterS: filterS, ConnMgr: apiService.connMgr, StorDBChan: storDBChan, - - Responder: apiService.responderService.GetResponder(), // if already started use it - ResponderChan: respChan, // if not wait in listenAndServe } go apiService.api.ListenAndServe(apiService.stopChan) @@ -137,7 +129,6 @@ func (apiService *APIerSv1Service) Shutdown() (err error) { close(apiService.stopChan) apiService.api = nil <-apiService.connChan - apiService.responderService.UnregisterSyncChan(apiService.ServiceName()) apiService.Unlock() return } diff --git a/utils/apitpdata.go b/utils/apitpdata.go index 3e13dc22e..3ed5e7e7c 100755 --- a/utils/apitpdata.go +++ b/utils/apitpdata.go @@ -172,19 +172,6 @@ type TPAction struct { Weight float64 // Action's weight } -type AttrGetAccount struct { - Tenant string - Account string -} - -type AttrGetAccounts struct { - Tenant string - AccountIDs []string - Offset int // Set the item offset - Limit int // Limit number of items retrieved - Filter map[string]bool -} - type AttrGetAccountsCount struct { Tenant string } @@ -261,7 +248,6 @@ func (fltr *AttrGetCdrs) AsCDRsFilter(timezone string) (cdrFltr *CDRsFilter, err type AttrLoadTpFromFolder struct { FolderPath string // Take files from folder absolute path DryRun bool // Do not write to database but parse only - Validate bool // Run structural checks on data APIOpts map[string]interface{} Caching *string } diff --git a/utils/consts.go b/utils/consts.go index 0fb52c401..bce04377d 100755 --- a/utils/consts.go +++ b/utils/consts.go @@ -1288,17 +1288,12 @@ const ( APIerSv1LoadTariffPlanFromFolder = "APIerSv1.LoadTariffPlanFromFolder" APIerSv1ExportToFolder = "APIerSv1.ExportToFolder" APIerSv1GetCost = "APIerSv1.GetCost" - APIerSv1SetBalance = "APIerSv1.SetBalance" APIerSv1GetFilter = "APIerSv1.GetFilter" APIerSv1GetFilterIndexes = "APIerSv1.GetFilterIndexes" APIerSv1RemoveFilterIndexes = "APIerSv1.RemoveFilterIndexes" APIerSv1RemoveFilter = "APIerSv1.RemoveFilter" APIerSv1SetFilter = "APIerSv1.SetFilter" APIerSv1GetFilterIDs = "APIerSv1.GetFilterIDs" - APIerSv1GetRatingProfile = "APIerSv1.GetRatingProfile" - APIerSv1RemoveRatingProfile = "APIerSv1.RemoveRatingProfile" - APIerSv1SetRatingProfile = "APIerSv1.SetRatingProfile" - APIerSv1GetRatingProfileIDs = "APIerSv1.GetRatingProfileIDs" APIerSv1SetDataDBVersions = "APIerSv1.SetDataDBVersions" APIerSv1SetStorDBVersions = "APIerSv1.SetStorDBVersions" APIerSv1GetActions = "APIerSv1.GetActions" @@ -1373,39 +1368,17 @@ const ( APIerSv1RemoveTPDestinationRate = "APIerSv1.RemoveTPDestinationRate" APIerSv1ImportTariffPlanFromFolder = "APIerSv1.ImportTariffPlanFromFolder" APIerSv1ExportTPToFolder = "APIerSv1.ExportTPToFolder" - APIerSv1LoadRatingPlan = "APIerSv1.LoadRatingPlan" - APIerSv1LoadRatingProfile = "APIerSv1.LoadRatingProfile" - APIerSv1LoadAccountActions = "APIerSv1.LoadAccountActions" APIerSv1SetActions = "APIerSv1.SetActions" - APIerSv1AddTriggeredAction = "APIerSv1.AddTriggeredAction" - APIerSv1GetAccountActionTriggers = "APIerSv1.GetAccountActionTriggers" - APIerSv1AddAccountActionTriggers = "APIerSv1.AddAccountActionTriggers" - APIerSv1ResetAccountActionTriggers = "APIerSv1.ResetAccountActionTriggers" - APIerSv1SetAccountActionTriggers = "APIerSv1.SetAccountActionTriggers" - APIerSv1RemoveAccountActionTriggers = "APIerSv1.RemoveAccountActionTriggers" - APIerSv1GetScheduledActions = "APIerSv1.GetScheduledActions" - APIerSv1RemoveActionTiming = "APIerSv1.RemoveActionTiming" APIerSv1ComputeReverseDestinations = "APIerSv1.ComputeReverseDestinations" - APIerSv1ComputeAccountActionPlans = "APIerSv1.ComputeAccountActionPlans" APIerSv1SetDestination = "APIerSv1.SetDestination" APIerSv1GetDataCost = "APIerSv1.GetDataCost" APIerSv1ReplayFailedPosts = "APIerSv1.ReplayFailedPosts" - APIerSv1RemoveAccount = "APIerSv1.RemoveAccount" - APIerSv1DebitUsage = "APIerSv1.DebitUsage" APIerSv1GetCacheStats = "APIerSv1.GetCacheStats" APIerSv1ReloadCache = "APIerSv1.ReloadCache" - APIerSv1GetActionTriggers = "APIerSv1.GetActionTriggers" - APIerSv1SetActionTrigger = "APIerSv1.SetActionTrigger" - APIerSv1RemoveActionPlan = "APIerSv1.RemoveActionPlan" APIerSv1RemoveActions = "APIerSv1.RemoveActions" - APIerSv1RemoveBalances = "APIerSv1.RemoveBalances" APIerSv1GetLoadHistory = "APIerSv1.GetLoadHistory" APIerSv1GetLoadIDs = "APIerSv1.GetLoadIDs" APIerSv1GetLoadTimes = "APIerSv1.GetLoadTimes" - APIerSv1ExecuteScheduledActions = "APIerSv1.ExecuteScheduledActions" - APIerSv1GetSharedGroup = "APIerSv1.GetSharedGroup" - APIerSv1RemoveActionTrigger = "APIerSv1.RemoveActionTrigger" - APIerSv1GetAccount = "APIerSv1.GetAccount" APIerSv1GetAttributeProfileIDsCount = "APIerSv1.GetAttributeProfileIDsCount" APIerSv1GetMaxUsage = "APIerSv1.GetMaxUsage" APIerSv1GetTPActionProfile = "APIerSv1.GetTPActionProfile" @@ -1439,34 +1412,25 @@ const ( // APIerSv2 APIs const ( - APIerSv2 = "APIerSv2" - APIerSv2LoadTariffPlanFromFolder = "APIerSv2.LoadTariffPlanFromFolder" - APIerSv2GetCDRs = "APIerSv2.GetCDRs" - APIerSv2GetAccount = "APIerSv2.GetAccount" - APIerSv2GetAccounts = "APIerSv2.GetAccounts" - APIerSv2SetAccount = "APIerSv2.SetAccount" - APIerSv2CountCDRs = "APIerSv2.CountCDRs" - APIerSv2SetBalance = "APIerSv2.SetBalance" - APIerSv2SetActions = "APIerSv2.SetActions" - APIerSv2RemoveTPTiming = "APIerSv2.RemoveTPTiming" - APIerSv2GetTPDestination = "APIerSv2.GetTPDestination" - APIerSv2SetTPDestination = "APIerSv2.SetTPDestination" - APIerSv2RemoveTPDestination = "APIerSv2.RemoveTPDestination" - APIerSv2GetTPDestinationIDs = "APIerSv2.GetTPDestinationIDs" - APIerSv2GetTPTiming = "APIerSv2.GetTPTiming" - APIerSv2SetTPTiming = "APIerSv2.SetTPTiming" - APIerSv2SetAccountActionTriggers = "APIerSv2.SetAccountActionTriggers" - APIerSv2GetAccountActionTriggers = "APIerSv2.GetAccountActionTriggers" - APIerSv2SetActionPlan = "APIerSv2.SetActionPlan" - APIerSv2GetActions = "APIerSv2.GetActions" - APIerSv2GetDestinations = "APIerSv2.GetDestinations" - APIerSv2GetCacheStats = "APIerSv2.GetCacheStats" - APIerSv2ExecuteAction = "APIerSv2.ExecuteAction" - APIerSv2ResetAccountActionTriggers = "APIerSv2.ResetAccountActionTriggers" - APIerSv2RemoveActions = "APIerSv2.RemoveActions" - APIerSv2ExportCdrsToFile = "APIerSv2.ExportCdrsToFile" - APIerSv2GetAccountsCount = "APIerSv2.GetAccountsCount" - APIerSv2GetActionsCount = "APIerSv2.GetActionsCount" + APIerSv2 = "APIerSv2" + APIerSv2LoadTariffPlanFromFolder = "APIerSv2.LoadTariffPlanFromFolder" + APIerSv2GetCDRs = "APIerSv2.GetCDRs" + APIerSv2CountCDRs = "APIerSv2.CountCDRs" + APIerSv2SetBalance = "APIerSv2.SetBalance" + APIerSv2SetActions = "APIerSv2.SetActions" + APIerSv2RemoveTPTiming = "APIerSv2.RemoveTPTiming" + APIerSv2GetTPDestination = "APIerSv2.GetTPDestination" + APIerSv2SetTPDestination = "APIerSv2.SetTPDestination" + APIerSv2RemoveTPDestination = "APIerSv2.RemoveTPDestination" + APIerSv2GetTPDestinationIDs = "APIerSv2.GetTPDestinationIDs" + APIerSv2GetTPTiming = "APIerSv2.GetTPTiming" + APIerSv2SetTPTiming = "APIerSv2.SetTPTiming" + APIerSv2GetActions = "APIerSv2.GetActions" + APIerSv2GetDestinations = "APIerSv2.GetDestinations" + APIerSv2GetCacheStats = "APIerSv2.GetCacheStats" + APIerSv2ExecuteAction = "APIerSv2.ExecuteAction" + APIerSv2RemoveActions = "APIerSv2.RemoveActions" + APIerSv2ExportCdrsToFile = "APIerSv2.ExportCdrsToFile" ) const ( @@ -1487,12 +1451,6 @@ const ( ConfigSv1SetConfigFromJSON = "ConfigSv1.SetConfigFromJSON" ) -const ( - RALsV1 = "RALsV1" - RALsV1GetRatingPlansCost = "RALsV1.GetRatingPlansCost" - RALsV1Ping = "RALsV1.Ping" -) - const ( RateSv1 = "RateSv1" RateSv1CostForEvent = "RateSv1.CostForEvent" @@ -1740,15 +1698,6 @@ const ( CDRsV2ProcessEvent = "CDRsV2.ProcessEvent" ) -// Scheduler -const ( - SchedulerSv1 = "SchedulerSv1" - SchedulerSv1Ping = "SchedulerSv1.Ping" - SchedulerSv1Reload = "SchedulerSv1.Reload" - SchedulerSv1ExecuteActions = "SchedulerSv1.ExecuteActions" - SchedulerSv1ExecuteActionPlans = "SchedulerSv1.ExecuteActionPlans" -) - // EEs const ( EeSv1 = "EeSv1"