/
action_plan.go
490 lines (453 loc) · 14 KB
/
action_plan.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
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 <http://www.gnu.org/licenses/>
*/
package engine
import (
"fmt"
"sort"
"time"
"github.com/cgrates/cgrates/config"
"github.com/cgrates/cgrates/guardian"
"github.com/cgrates/cgrates/utils"
"github.com/gorhill/cronexpr"
)
const (
FORMAT = "2006-1-2 15:04:05 MST"
)
type ActionTiming struct {
Uuid string
Timing *RateInterval
ActionsID string
ExtraData interface{}
Weight float64
actions Actions
accountIDs utils.StringMap // copy of action plans accounts
actionPlanID string // the id of the belonging action plan (info only)
stCache time.Time // cached time of the next start
}
// Tasks converts an ActionTiming into multiple Tasks
func (at *ActionTiming) Tasks() (tsks []*Task) {
if len(at.accountIDs) == 0 {
return []*Task{
&Task{
Uuid: at.Uuid,
ActionsID: at.ActionsID,
}}
}
tsks = make([]*Task, len(at.accountIDs))
i := 0
for acntID := range at.accountIDs {
tsks[i] = &Task{
Uuid: at.Uuid,
ActionsID: at.ActionsID,
AccountID: acntID,
}
i++
}
return
}
type ActionPlan struct {
Id string // informative purpose only
AccountIDs utils.StringMap
ActionTimings []*ActionTiming
}
func (apl *ActionPlan) RemoveAccountID(accID string) (found bool) {
if _, found = apl.AccountIDs[accID]; found {
delete(apl.AccountIDs, accID)
}
return
}
// Clone clones *ActionPlan
func (apl *ActionPlan) Clone() (interface{}, error) {
cln := &ActionPlan{
Id: apl.Id,
AccountIDs: apl.AccountIDs.Clone(),
}
if apl.ActionTimings != nil {
cln.ActionTimings = make([]*ActionTiming, len(apl.ActionTimings))
for i, act := range apl.ActionTimings {
cln.ActionTimings[i] = act.Clone()
}
}
return cln, nil
}
// Clone clones ActionTiming
func (at *ActionTiming) Clone() (cln *ActionTiming) {
if at == nil {
return
}
cln = &ActionTiming{
Uuid: at.Uuid,
ActionsID: at.ActionsID,
Weight: at.Weight,
ExtraData: at.ExtraData,
Timing: at.Timing.Clone(),
}
return
}
func (at *ActionTiming) GetNextStartTime(now time.Time) (t time.Time) {
if !at.stCache.IsZero() {
return at.stCache
}
i := at.Timing
if i == nil || i.Timing == nil {
return
}
// Normalize
if i.Timing.StartTime == "" {
i.Timing.StartTime = "00:00:00"
}
if len(i.Timing.Years) > 0 && len(i.Timing.Months) == 0 {
i.Timing.Months = append(i.Timing.Months, 1)
}
if len(i.Timing.Months) > 0 && len(i.Timing.MonthDays) == 0 {
i.Timing.MonthDays = append(i.Timing.MonthDays, 1)
}
at.stCache = cronexpr.MustParse(i.Timing.CronString()).Next(now)
return at.stCache
}
// To be deleted after the above solution proves reliable
func (at *ActionTiming) GetNextStartTimeOld(now time.Time) (t time.Time) {
if !at.stCache.IsZero() {
return at.stCache
}
i := at.Timing
if i == nil {
return
}
// Normalize
if i.Timing.StartTime == "" {
i.Timing.StartTime = "00:00:00"
}
if len(i.Timing.Years) > 0 && len(i.Timing.Months) == 0 {
i.Timing.Months = append(i.Timing.Months, 1)
}
if len(i.Timing.Months) > 0 && len(i.Timing.MonthDays) == 0 {
i.Timing.MonthDays = append(i.Timing.MonthDays, 1)
}
y, m, d := now.Date()
z, _ := now.Zone()
if i.Timing.StartTime != utils.ASAP {
l := fmt.Sprintf("%d-%d-%d %s %s", y, m, d, i.Timing.StartTime, z)
var err error
t, err = time.Parse(FORMAT, l)
if err != nil {
utils.Logger.Err(fmt.Sprintf("Cannot parse action plan's StartTime %v", l))
at.stCache = t
return
}
if now.After(t) || now.Equal(t) { // Set it to next day this time
t = t.AddDate(0, 0, 1)
}
}
// weekdays
if i.Timing.WeekDays != nil && len(i.Timing.WeekDays) > 0 {
i.Timing.WeekDays.Sort()
if t.IsZero() {
t = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), 0, now.Location())
}
for j := 0; j < 8; j++ {
n := t.AddDate(0, 0, j)
for _, wd := range i.Timing.WeekDays {
if n.Weekday() == wd && (n.Equal(now) || n.After(now)) {
at.stCache = n
t = n
return
}
}
}
}
// monthdays
if i.Timing.MonthDays != nil && len(i.Timing.MonthDays) > 0 {
i.Timing.MonthDays.Sort()
year := t.Year()
month := t
x := sort.SearchInts(i.Timing.MonthDays, t.Day())
d = i.Timing.MonthDays[0]
if x < len(i.Timing.MonthDays) {
if i.Timing.MonthDays[x] == t.Day() {
if t.Equal(now) || t.After(now) {
goto MONTHS
}
if x+1 < len(i.Timing.MonthDays) { // today was found in the list, jump to the next grater day
d = i.Timing.MonthDays[x+1]
} else { // jump to next month
//not using now to make sure the next month has the the 1 date
//(if today is 31) next month may not have it
tmp := time.Date(year, month.Month(), 1, 0, 0, 0, 0, time.Local)
month = tmp.AddDate(0, 1, 0)
}
} else { // today was not found in the list, x is the first greater day
d = i.Timing.MonthDays[x]
}
}
h, m, s := t.Clock()
t = time.Date(month.Year(), month.Month(), d, h, m, s, 0, time.Local)
}
MONTHS:
if i.Timing.Months != nil && len(i.Timing.Months) > 0 {
i.Timing.Months.Sort()
year := t.Year()
x := sort.Search(len(i.Timing.Months), func(x int) bool { return i.Timing.Months[x] >= t.Month() })
m = i.Timing.Months[0]
if x < len(i.Timing.Months) {
if i.Timing.Months[x] == t.Month() {
if t.Equal(now) || t.After(now) {
goto YEARS
}
if x+1 < len(i.Timing.Months) { // this month was found in the list so jump to next available month
m = i.Timing.Months[x+1]
// reset the monthday
t = time.Date(t.Year(), t.Month(), i.Timing.MonthDays[0], t.Hour(), t.Minute(), t.Second(), 0, t.Location())
} else { // jump to next year
//not using now to make sure the next year has the the 1 date
//(if today is 31) next month may not have it
tmp := time.Date(year, 1, 1, 0, 0, 0, 0, time.Local)
year = tmp.AddDate(1, 0, 0).Year()
}
} else { // this month was not found in the list, x is the first greater month
m = i.Timing.Months[x]
// reset the monthday
t = time.Date(t.Year(), t.Month(), i.Timing.MonthDays[0], t.Hour(), t.Minute(), t.Second(), 0, t.Location())
}
}
h, min, s := t.Clock()
t = time.Date(year, m, t.Day(), h, min, s, 0, time.Local)
} else {
if now.After(t) {
t = t.AddDate(0, 1, 0)
}
}
YEARS:
if i.Timing.Years != nil && len(i.Timing.Years) > 0 {
i.Timing.Years.Sort()
x := sort.Search(len(i.Timing.Years), func(x int) bool { return i.Timing.Years[x] >= t.Year() })
y = i.Timing.Years[0]
if x < len(i.Timing.Years) {
if i.Timing.Years[x] == now.Year() {
if t.Equal(now) || t.After(now) {
h, m, s := t.Clock()
t = time.Date(now.Year(), t.Month(), t.Day(), h, m, s, 0, time.Local)
at.stCache = t
return
}
if x+1 < len(i.Timing.Years) { // this year was found in the list so jump to next available year
y = i.Timing.Years[x+1]
// reset the month
if i.Timing.Months != nil {
t = time.Date(t.Year(), i.Timing.Months[0], t.Day(), t.Hour(), t.Minute(), t.Second(), 0, t.Location())
}
// reset the monthday
t = time.Date(t.Year(), t.Month(), i.Timing.MonthDays[0], t.Hour(), t.Minute(), t.Second(), 0, t.Location())
}
} else { // this year was not found in the list, x is the first greater year
y = i.Timing.Years[x]
// reset the month/monthday
t = time.Date(t.Year(), i.Timing.Months[0], i.Timing.MonthDays[0], t.Hour(), t.Minute(), t.Second(), 0, t.Location())
}
}
h, min, s := t.Clock()
t = time.Date(y, t.Month(), t.Day(), h, min, s, 0, time.Local)
} else {
if now.After(t) {
t = t.AddDate(1, 0, 0)
}
}
at.stCache = t
return
}
func (at *ActionTiming) ResetStartTimeCache() {
at.stCache = time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC)
}
func (at *ActionTiming) SetActions(as Actions) {
at.actions = as
}
func (at *ActionTiming) SetAccountIDs(accIDs utils.StringMap) {
at.accountIDs = accIDs
}
func (at *ActionTiming) RemoveAccountID(acntID string) (found bool) {
if _, found = at.accountIDs[acntID]; found {
delete(at.accountIDs, acntID)
}
return
}
func (at *ActionTiming) GetAccountIDs() utils.StringMap {
return at.accountIDs
}
func (at *ActionTiming) SetActionPlanID(id string) {
at.actionPlanID = id
}
func (at *ActionTiming) GetActionPlanID() string {
return at.actionPlanID
}
func (at *ActionTiming) getActions() (as []*Action, err error) {
if at.actions == nil {
at.actions, err = dm.GetActions(at.ActionsID, false, utils.NonTransactional)
}
at.actions.Sort()
return at.actions, err
}
// Execute will execute all actions in an action plan
// Reports on success/fail via channel if != nil
func (at *ActionTiming) Execute(successActions, failedActions chan *Action) (err error) {
at.ResetStartTimeCache()
aac, err := at.getActions()
if err != nil {
utils.Logger.Err(fmt.Sprintf("Failed to get actions for %s: %s", at.ActionsID, err))
return
}
var partialyExecuted bool
for accID := range at.accountIDs {
_, err = guardian.Guardian.Guard(func() (interface{}, error) {
acc, err := dm.GetAccount(accID)
if err != nil {
utils.Logger.Warning(fmt.Sprintf("Could not get account id: %s. Skipping!", accID))
return 0, err
}
transactionFailed := false
removeAccountActionFound := false
for _, a := range aac {
// check action filter
if len(a.Filter) > 0 {
matched, err := acc.matchActionFilter(a.Filter)
//log.Print("Checkng: ", a.Filter, matched)
if err != nil {
return 0, err
}
if !matched {
continue
}
}
if a.Balance == nil {
a.Balance = &BalanceFilter{}
}
if a.ExpirationString != "" { // if it's *unlimited then it has to be zero time
if expDate, parseErr := utils.ParseTimeDetectLayout(a.ExpirationString,
config.CgrConfig().GeneralCfg().DefaultTimezone); parseErr == nil {
a.Balance.ExpirationDate = &time.Time{}
*a.Balance.ExpirationDate = expDate
}
}
actionFunction, exists := getActionFunc(a.ActionType)
if !exists {
// do not allow the action plan to be rescheduled
at.Timing = nil
utils.Logger.Err(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType))
partialyExecuted = true
transactionFailed = true
break
}
if err := actionFunction(acc, a, aac, at.ExtraData); err != nil {
utils.Logger.Err(fmt.Sprintf("Error executing action %s: %v!", a.ActionType, err))
partialyExecuted = true
transactionFailed = true
if failedActions != nil {
go func() { failedActions <- a }()
}
break
}
if successActions != nil {
go func() { successActions <- a }()
}
if a.ActionType == utils.REMOVE_ACCOUNT {
removeAccountActionFound = true
}
}
if !transactionFailed && !removeAccountActionFound {
dm.SetAccount(acc)
}
return 0, nil
}, config.CgrConfig().GeneralCfg().LockingTimeout, utils.ACCOUNT_PREFIX+accID)
}
//reset the error in case that the account is not found
err = nil
if len(at.accountIDs) == 0 { // action timing executing without accounts
for _, a := range aac {
if expDate, parseErr := utils.ParseTimeDetectLayout(a.ExpirationString,
config.CgrConfig().GeneralCfg().DefaultTimezone); (a.Balance == nil || a.Balance.EmptyExpirationDate()) &&
parseErr == nil && !expDate.IsZero() {
a.Balance.ExpirationDate = &time.Time{}
*a.Balance.ExpirationDate = expDate
}
actionFunction, exists := getActionFunc(a.ActionType)
if !exists {
// do not allow the action plan to be rescheduled
at.Timing = nil
utils.Logger.Err(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType))
partialyExecuted = true
if failedActions != nil {
go func() { failedActions <- a }()
}
break
}
if err := actionFunction(nil, a, aac, at.ExtraData); err != nil {
utils.Logger.Err(fmt.Sprintf("Error executing accountless action %s: %v!", a.ActionType, err))
partialyExecuted = true
if failedActions != nil {
go func() { failedActions <- a }()
}
break
}
if successActions != nil {
go func() { successActions <- a }()
}
}
}
if err != nil {
utils.Logger.Warning(fmt.Sprintf("Error executing action plan: %v", err))
return err
}
if partialyExecuted {
return utils.ErrPartiallyExecuted
}
return
}
func (at *ActionTiming) IsASAP() bool {
if at.Timing == nil {
return false
}
return at.Timing.Timing.StartTime == utils.ASAP
}
// Structure to store actions according to execution time and weight
type ActionTimingPriorityList []*ActionTiming
func (atpl ActionTimingPriorityList) Len() int {
return len(atpl)
}
func (atpl ActionTimingPriorityList) Swap(i, j int) {
atpl[i], atpl[j] = atpl[j], atpl[i]
}
func (atpl ActionTimingPriorityList) Less(i, j int) bool {
if atpl[i].GetNextStartTime(time.Now()).Equal(atpl[j].GetNextStartTime(time.Now())) {
// higher weights earlyer in the list
return atpl[i].Weight > atpl[j].Weight
}
return atpl[i].GetNextStartTime(time.Now()).Before(atpl[j].GetNextStartTime(time.Now()))
}
func (atpl ActionTimingPriorityList) Sort() {
sort.Sort(atpl)
}
// Structure to store actions according to weight
type ActionTimingWeightOnlyPriorityList []*ActionTiming
func (atpl ActionTimingWeightOnlyPriorityList) Len() int {
return len(atpl)
}
func (atpl ActionTimingWeightOnlyPriorityList) Swap(i, j int) {
atpl[i], atpl[j] = atpl[j], atpl[i]
}
func (atpl ActionTimingWeightOnlyPriorityList) Less(i, j int) bool {
return atpl[i].Weight > atpl[j].Weight
}
func (atpl ActionTimingWeightOnlyPriorityList) Sort() {
sort.Sort(atpl)
}