statping/types/notifications/struct.go

276 lines
9.3 KiB
Go
Raw Normal View History

2018-12-04 05:57:11 +00:00
// Statping
2018-08-16 06:22:20 +00:00
// Copyright (C) 2018. Hunter Long and the project contributors
// Written by Hunter Long <info@socialeck.com> and the project contributors
//
2018-12-04 04:17:29 +00:00
// https://github.com/hunterlong/statping
2018-08-16 06:22:20 +00:00
//
// The licenses for most software and other practical works are designed
// to take away your freedom to share and change the works. By contrast,
// the GNU General Public License is intended to guarantee your freedom to
// share and change all versions of a program--to make sure it remains free
// software for all its users.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2020-03-04 10:29:00 +00:00
package notifications
2018-07-10 12:05:20 +00:00
import (
"encoding/json"
"errors"
"fmt"
2020-02-22 23:52:05 +00:00
"github.com/hunterlong/statping/database"
2020-03-04 10:29:00 +00:00
"github.com/hunterlong/statping/types/null"
"github.com/hunterlong/statping/types/services"
2018-12-04 04:17:29 +00:00
"github.com/hunterlong/statping/utils"
"reflect"
2018-07-10 12:05:20 +00:00
"time"
)
var (
2018-12-04 05:57:11 +00:00
// db holds the Statping database connection
2020-03-04 10:29:00 +00:00
db database.Database
log = utils.Log.WithField("type", "notifier")
AllCommunications []Notifier
2018-07-10 12:05:20 +00:00
)
2018-12-04 05:57:11 +00:00
// Notification contains all the fields for a Statping Notifier.
2018-07-10 12:05:20 +00:00
type Notification struct {
Id int64 `gorm:"primary_key;column:id" json:"id"`
Method string `gorm:"column:method" json:"method"`
2018-11-06 09:03:21 +00:00
Host string `gorm:"not null;column:host" json:"host,omitempty"`
Port int `gorm:"not null;column:port" json:"port,omitempty"`
Username string `gorm:"not null;column:username" json:"username,omitempty"`
Password string `gorm:"not null;column:password" json:"password,omitempty"`
Var1 string `gorm:"not null;column:var1" json:"var1,omitempty"`
Var2 string `gorm:"not null;column:var2" json:"var2,omitempty"`
ApiKey string `gorm:"not null;column:api_key" json:"api_key,omitempty"`
ApiSecret string `gorm:"not null;column:api_secret" json:"api_secret,omitempty"`
2020-03-04 10:29:00 +00:00
Enabled null.NullBool `gorm:"column:enabled;type:boolean;default:false" json:"enabled"`
2018-11-06 09:03:21 +00:00
Limits int `gorm:"not null;column:limits" json:"limits"`
2018-11-08 06:23:24 +00:00
Removable bool `gorm:"column:removable" json:"removeable"`
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
2018-11-06 09:03:21 +00:00
Form []NotificationForm `gorm:"-" json:"form"`
2018-11-08 06:23:24 +00:00
logs []*NotificationLog `gorm:"-" json:"logs"`
2018-11-06 09:03:21 +00:00
Title string `gorm:"-" json:"title"`
Description string `gorm:"-" json:"description"`
2018-11-08 06:23:24 +00:00
Author string `gorm:"-" json:"author"`
AuthorUrl string `gorm:"-" json:"author_url"`
Icon string `gorm:"-" json:"icon"`
2018-11-08 10:50:06 +00:00
Delay time.Duration `gorm:"-" json:"delay,string"`
Queue []*QueueData `gorm:"-" json:"-"`
Running chan bool `gorm:"-" json:"-"`
2018-11-08 06:23:24 +00:00
testable bool `gorm:"-" json:"testable"`
2020-03-04 10:29:00 +00:00
Notifier
2018-07-10 12:05:20 +00:00
}
// QueueData is the struct for the messaging queue with service
type QueueData struct {
2019-03-04 17:18:50 +00:00
Id string
Data interface{}
}
2018-10-06 04:10:11 +00:00
// NotificationForm contains the HTML fields for each variable/input you want the notifier to accept.
2018-07-10 12:05:20 +00:00
type NotificationForm struct {
2018-11-08 06:23:24 +00:00
Type string `json:"type"` // the html input type (text, password, email)
Title string `json:"title"` // include a title for ease of use
Placeholder string `json:"placeholder"` // add a placeholder for the input
DbField string `json:"field"` // true variable key for input
SmallText string `json:"small_text"` // insert small text under a html input
Required bool `json:"required"` // require this input on the html form
2018-11-25 03:56:09 +00:00
IsHidden bool `json:"hidden"` // hide this form element from end user
IsList bool `json:"list"` // make this form element a comma separated list
IsSwitch bool `json:"switch"` // make the notifier a boolean true/false switch
}
2018-10-06 04:10:11 +00:00
// NotificationLog contains the normalized message from previously sent notifications
2018-07-17 09:18:20 +00:00
type NotificationLog struct {
2018-11-08 06:23:24 +00:00
Message string `json:"message"`
Time utils.Timestamp `json:"time"`
Timestamp time.Time `json:"timestamp"`
2018-07-17 09:18:20 +00:00
}
2018-09-12 04:14:22 +00:00
// SetDB is called by core to inject the database for a notifier to use
2020-02-22 23:52:05 +00:00
func SetDB(d database.Database) {
2018-09-12 04:14:22 +00:00
db = d
}
2018-10-06 04:10:11 +00:00
// asNotification accepts a Notifier and returns a Notification struct
2018-10-06 03:35:53 +00:00
func asNotification(n Notifier) *Notification {
return n.Select()
}
2018-10-06 04:10:11 +00:00
// normalizeType will accept multiple interfaces and converts it into a string for logging
func normalizeType(ty interface{}) string {
switch v := ty.(type) {
case int, int32, int64:
return fmt.Sprintf("%v", v)
case float32, float64:
return fmt.Sprintf("%v", v)
case string:
return v
case []byte:
return string(v)
case []string:
return fmt.Sprintf("%v", v)
case interface{}, map[string]interface{}:
j, _ := json.Marshal(v)
return string(j)
default:
return fmt.Sprintf("%v", v)
}
}
2018-09-12 04:14:22 +00:00
// Log will record a new notification into memory and will show the logs on the settings page
func (n *Notification) makeLog(msg interface{}) {
2018-07-17 09:18:20 +00:00
log := &NotificationLog{
Message: normalizeType(msg),
Time: utils.Timestamp(utils.Now()),
Timestamp: utils.Now(),
2018-07-17 09:18:20 +00:00
}
2018-09-12 04:14:22 +00:00
n.logs = append(n.logs, log)
2018-07-17 09:18:20 +00:00
}
2018-09-12 04:14:22 +00:00
// Logs returns an array of the notifiers logs
2018-07-17 09:18:20 +00:00
func (n *Notification) Logs() []*NotificationLog {
2018-09-12 04:14:22 +00:00
return reverseLogs(n.logs)
2018-07-17 09:18:20 +00:00
}
2018-09-12 04:14:22 +00:00
// reverseLogs will reverse the notifier's logs to be time desc
2018-07-17 09:18:20 +00:00
func reverseLogs(input []*NotificationLog) []*NotificationLog {
if len(input) == 0 {
return input
}
return append(reverseLogs(input[1:]), input[0])
}
2018-09-12 04:14:22 +00:00
// SelectNotification returns the Notification struct from the database
func SelectNotification(n Notifier) (*Notification, error) {
notifier := n.Select()
err := db.Model(&Notification{}).Where("method = ?", notifier.Method).Scan(&notifier)
2020-01-26 21:01:43 +00:00
return notifier, err.Error()
}
2018-09-12 04:14:22 +00:00
// insertDatabase will create a new record into the database for the notifier
2019-11-06 03:35:01 +00:00
func insertDatabase(n Notifier) (int64, error) {
noti := n.Select()
noti.Limits = 3
2020-03-04 10:29:00 +00:00
err := noti.Create()
if err != nil {
return 0, err
}
2020-03-04 10:29:00 +00:00
return noti.Id, err
}
2018-09-12 04:14:22 +00:00
// SelectNotifier returns the Notification struct from the database
func SelectNotifier(method string) (*Notification, Notifier, error) {
for _, comm := range AllCommunications {
n, ok := comm.(Notifier)
if !ok {
2018-10-07 04:48:33 +00:00
return nil, nil, fmt.Errorf("incorrect notification type: %v", reflect.TypeOf(n).String())
}
notifier := n.Select()
if notifier.Method == method {
return notifier, comm.(Notifier), nil
2018-07-12 06:53:18 +00:00
}
}
2019-11-06 03:35:01 +00:00
return nil, nil, errors.New("cannot find notifier")
}
2018-10-06 04:10:11 +00:00
// Queue is the FIFO go routine to send notifications when objects are triggered
2020-03-04 10:29:00 +00:00
func Queue(notifer Notifier) {
n := notifer.Select()
rateLimit := n.Delay
CheckNotifier:
for {
select {
2020-03-04 10:29:00 +00:00
case <-n.Running:
break CheckNotifier
case <-time.After(rateLimit):
2020-03-04 10:29:00 +00:00
if len(n.Queue) > 0 {
ok, _ := n.WithinLimits()
if ok {
2020-03-04 10:29:00 +00:00
msg := n.Queue[0]
err := notifer.Send(msg.Data)
if err != nil {
2020-03-04 10:29:00 +00:00
log.WithFields(utils.ToFields(n, msg)).Error(fmt.Sprintf("Notifier '%v' had an error: %v", n.Method, err))
2019-10-25 15:13:32 +00:00
} else {
2020-03-04 10:29:00 +00:00
log.WithFields(utils.ToFields(n, msg)).Debug(fmt.Sprintf("Notifier '%v' sent outgoing message (%v) %v left in queue.", n.Method, msg.Id, len(n.Queue)))
}
2020-03-04 10:29:00 +00:00
n.makeLog(msg.Data)
if len(n.Queue) > 1 {
n.Queue = n.Queue[1:]
2018-12-19 18:19:14 +00:00
} else {
2020-03-04 10:29:00 +00:00
n.Queue = nil
2018-12-19 18:19:14 +00:00
}
2020-03-04 10:29:00 +00:00
rateLimit = n.Delay
}
}
}
continue
}
}
2018-09-12 04:14:22 +00:00
// install will check the database for the notification, if its not inserted it will insert a new record for it
func install(n Notifier) error {
2020-03-04 10:29:00 +00:00
_, err := insertDatabase(n)
if err != nil {
log.Errorln(err)
return err
2018-09-12 04:14:22 +00:00
}
2018-09-15 05:07:17 +00:00
2020-03-04 10:29:00 +00:00
log.WithFields(utils.ToFields(n)).
Debugln(fmt.Sprintf("Checking if notifier '%v' is installed", n.Select().Method))
2018-07-17 09:18:20 +00:00
2020-03-04 10:29:00 +00:00
return nil
2018-07-10 12:05:20 +00:00
}
2018-09-12 04:14:22 +00:00
// isEnabled returns true if the notifier is enabled
func isEnabled(n interface{}) bool {
2018-11-06 12:12:17 +00:00
notifier := n.(Notifier).Select()
return notifier.Enabled.Bool
2018-07-10 12:05:20 +00:00
}
2018-10-06 04:10:11 +00:00
// inLimits will return true if the notifier is within sending limits
func inLimits(n interface{}) bool {
notifier := n.(Notifier).Select()
ok, _ := notifier.WithinLimits()
return ok
}
2018-07-14 02:37:39 +00:00
2018-10-06 04:10:11 +00:00
// WithinLimits returns true if the notifier is within its sending limits
2018-10-07 04:48:33 +00:00
func (n *Notification) WithinLimits() (bool, error) {
if n.SentLastMinute() == 0 {
return true, nil
}
2018-10-07 04:48:33 +00:00
if n.SentLastMinute() >= n.Limits {
return false, fmt.Errorf("notifier sent %v out of %v in last minute", n.SentLastMinute(), n.Limits)
}
2018-10-07 04:48:33 +00:00
if n.LastSent().Seconds() == 0 {
return true, nil
}
2018-10-07 04:48:33 +00:00
if n.Delay.Seconds() >= n.LastSent().Seconds() {
return false, fmt.Errorf("notifiers delay (%v) is greater than last message sent (%v)", n.Delay.Seconds(), n.LastSent().Seconds())
}
return true, nil
2018-07-10 12:05:20 +00:00
}
2019-12-18 11:36:29 +00:00
// ExampleService can be used for the OnTest() method for notifiers
2020-03-04 10:29:00 +00:00
var ExampleService = &services.Service{
2019-12-18 11:36:29 +00:00
Id: 1,
Name: "Interpol - All The Rage Back Home",
Domain: "https://www.youtube.com/watch?v=-u6DvRyyKGU",
ExpectedStatus: 200,
Interval: 30,
Type: "http",
Method: "GET",
Timeout: 20,
LastStatusCode: 404,
2020-03-04 10:29:00 +00:00
Expected: null.NewNullString("test example"),
2019-12-18 11:36:29 +00:00
LastResponse: "<html>this is an example response</html>",
CreatedAt: utils.Now().Add(-24 * time.Hour),
2019-12-18 11:36:29 +00:00
}