github.com/Tyktechnologies/tyk@v2.9.5+incompatible/gateway/monitor.go (about) 1 package gateway 2 3 import ( 4 "time" 5 6 "github.com/TykTechnologies/tyk/config" 7 "github.com/TykTechnologies/tyk/user" 8 ) 9 10 type Monitor struct{} 11 12 func (Monitor) Enabled() bool { 13 return config.Global().Monitor.EnableTriggerMonitors 14 } 15 16 func (Monitor) Fire(sessionData *user.SessionState, key string, triggerLimit, usagePercentage float64) { 17 em := config.EventMessage{ 18 Type: EventTriggerExceeded, 19 Meta: EventTriggerExceededMeta{ 20 EventMetaDefault: EventMetaDefault{Message: "Quota trigger reached"}, 21 OrgID: sessionData.OrgID, 22 Key: key, 23 TriggerLimit: int64(triggerLimit), 24 UsagePercentage: int64(usagePercentage), 25 }, 26 TimeStamp: time.Now().String(), 27 } 28 29 go MonitoringHandler.HandleEvent(em) 30 } 31 32 func (m Monitor) Check(sessionData *user.SessionState, key string) { 33 if !m.Enabled() { 34 return 35 } 36 37 if m.checkLimit(sessionData, key, sessionData.QuotaMax, sessionData.QuotaRemaining, sessionData.QuotaRenews) { 38 return 39 } 40 41 for _, ac := range sessionData.GetAccessRights() { 42 if ac.Limit == nil { 43 continue 44 } 45 46 if m.checkLimit(sessionData, key, ac.Limit.QuotaMax, ac.Limit.QuotaRemaining, ac.Limit.QuotaRenews) { 47 return 48 } 49 } 50 } 51 52 func (m Monitor) checkLimit(sessionData *user.SessionState, key string, quotaMax, quotaRemaining, quotaRenews int64) bool { 53 if quotaMax <= 0 { 54 return false 55 } 56 57 remainder := quotaMax - quotaRemaining 58 usagePerc := (float64(remainder) / float64(quotaMax)) * 100.0 59 60 log.Debug("Perc is: ", usagePerc) 61 renewalDate := time.Unix(quotaRenews, 0) 62 63 log.Debug("Now is: ", time.Now()) 64 log.Debug("Renewal is: ", renewalDate) 65 if time.Now().After(renewalDate) { 66 // Make sure that renewal is still in the future, If renewal is in the past, 67 // then the quota can expire and will auto-renew 68 log.Debug("Renewal date is in the past, skipping") 69 return false 70 } 71 72 if config.Global().Monitor.GlobalTriggerLimit > 0.0 && usagePerc >= config.Global().Monitor.GlobalTriggerLimit { 73 log.Info("Firing...") 74 m.Fire(sessionData, key, config.Global().Monitor.GlobalTriggerLimit, usagePerc) 75 return true 76 } 77 78 for _, triggerLimit := range sessionData.Monitor.TriggerLimits { 79 if usagePerc >= triggerLimit && triggerLimit != config.Global().Monitor.GlobalTriggerLimit { 80 log.Info("Firing...") 81 m.Fire(sessionData, key, triggerLimit, usagePerc) 82 return true 83 } 84 } 85 86 return false 87 }