notifier

package
v0.80.66 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2019 License: GPL-3.0 Imports: 9 Imported by: 0

Documentation

Overview

Package notifier contains the main functionality for the Statping Notification system

Example Notifier

Below is an example of a Notifier with multiple Form values to custom your inputs. Place your notifier go file into the /notifiers/ directory and follow the example below.

type ExampleNotifier struct {
	*Notification
}

var example = &ExampleNotifier{&Notification{
	Method:      "example",
	Title:       "Example Notifier",
	Description: "This is an example of a notifier for Statping!",
	Author:      "Hunter Long",
	AuthorUrl:   "https://github.com/hunterlong",
	Delay:       time.Duration(3 * time.Second),
	Limits:      7,
	Form: []NotificationForm{{
		Type:        "text",
		Title:       "Host",
		Placeholder: "Insert your Host here.",
		DbField:     "host",
		SmallText:   "this is where you would put the host",
	}, {
		Type:        "text",
		Title:       "Username",
		Placeholder: "Insert your Username here.",
		DbField:     "username",
	}, {
		Type:        "password",
		Title:       "Password",
		Placeholder: "Insert your Password here.",
		DbField:     "password",
	}, {
		Type:        "number",
		Title:       "Port",
		Placeholder: "Insert your Port here.",
		DbField:     "port",
	}, {
		Type:        "text",
		Title:       "API Key",
		Placeholder: "Insert your API Key here",
		DbField:     "api_key",
	}, {
		Type:        "text",
		Title:       "API Secret",
		Placeholder: "Insert your API Secret here",
		DbField:     "api_secret",
	}, {
		Type:        "text",
		Title:       "Var 1",
		Placeholder: "Insert your Var1 here",
		DbField:     "var1",
	}, {
		Type:        "text",
		Title:       "Var2",
		Placeholder: "Var2 goes here",
		DbField:     "var2",
	}},
}}

Load the Notifier

Include the init() function with AddNotifier and your notification struct. This is ran on start of Statping and will automatically create a new row in the database so the end user can save their own values.

func init() {
	AddNotifier(example)
}

Required Methods for Notifier Interface

Below are the required methods to have your notifier implement the Notifier interface. The Send method will be where you would include the logic for your notification.

// REQUIRED
func (n *ExampleNotifier) Send(msg interface{}) error {
	message := msg.(string)
	fmt.Printf("i received this string: %v\n", message)
	return nil
}

// REQUIRED
func (n *ExampleNotifier) Select() *Notification {
	return n.Notification
}

// REQUIRED
func (n *ExampleNotifier) OnSave() error {
	msg := fmt.Sprintf("received on save trigger")
	n.AddQueue(msg)
	return errors.New("onsave triggered")
}

Basic Events for Notifier

You must include OnSuccess and OnFailure methods for your notifier. Anytime a service is online or offline these methods will be ran with the service corresponding to it.

// REQUIRED - BASIC EVENT
func (n *ExampleNotifier) OnSuccess(s *types.Service) {
	msg := fmt.Sprintf("received a count trigger for service: %v\n", s.Name)
	n.AddQueue(msg)
}

// REQUIRED - BASIC EVENT
func (n *ExampleNotifier) OnFailure(s *types.Service, f *types.Failure) {
	msg := fmt.Sprintf("received a failure trigger for service: %v\n", s.Name)
	n.AddQueue(msg)
}

Additional Events

You can implement your notifier to different types of events that are triggered. Checkout the wiki to see more details and examples of how to build your own notifier.

More info on: https://github.com/hunterlong/statping/wiki/Notifiers

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// AllCommunications holds all the loaded notifiers
	AllCommunications []types.AllNotifiers
)
View Source
var ExampleService = &types.Service{
	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,
	Expected:       types.NewNullString("test example"),
	LastResponse:   "<html>this is an example response</html>",
	CreatedAt:      time.Now().Add(-24 * time.Hour),
}

ExampleService can be used for the OnTest() method for notifiers

Functions

func AddNotifiers added in v0.80.65

func AddNotifiers(notifiers ...Notifier) error

AddNotifier accept a Notifier interface to be added into the array

func OnDeletedService

func OnDeletedService(s *types.Service)

OnDeletedService is triggered when a service is deleted - ServiceEvents interface

func OnDeletedUser

func OnDeletedUser(u *types.User)

OnDeletedUser is triggered when a new user is deleted - UserEvents interface

func OnFailure

func OnFailure(s *types.Service, f *types.Failure)

OnFailure will be triggered when a service is failing - BasicEvents interface

Example

Add a new message into the queue OnFailure

msg := fmt.Sprintf("received a failing service: %v\n", service.Name)
example.AddQueue("example", msg)
Output:

func OnNewNotifier

func OnNewNotifier(n *Notification)

OnNewNotifier is triggered when a new notifier is loaded

func OnNewService

func OnNewService(s *types.Service)

OnNewService is triggered when a new service is created - ServiceEvents interface

func OnNewUser

func OnNewUser(u *types.User)

OnNewUser is triggered when a new user is created - UserEvents interface

func OnSave

func OnSave(method string)

OnSave will trigger a notifier when it has been saved - Notifier interface

func OnStart

func OnStart(c *types.Core)

OnStart is triggered when the Statping service has started

func OnSuccess

func OnSuccess(s *types.Service)

OnSuccess will be triggered when a service is successful - BasicEvents interface

Example

Add a new message into the queue OnSuccess

msg := fmt.Sprintf("received a count trigger for service: %v\n", service.Name)
example.AddQueue("example", msg)
Output:

func OnUpdatedCore

func OnUpdatedCore(c *types.Core)

OnUpdatedCore is triggered when the CoreApp settings are saved - CoreEvents interface

func OnUpdatedNotifier

func OnUpdatedNotifier(n *Notification)

OnUpdatedNotifier is triggered when a notifier has been updated

func OnUpdatedService

func OnUpdatedService(s *types.Service)

OnUpdatedService is triggered when a service is updated - ServiceEvents interface

func OnUpdatedUser

func OnUpdatedUser(u *types.User)

OnUpdatedUser is triggered when a new user is updated - UserEvents interface

func Queue

func Queue(n Notifier)

Queue is the FIFO go routine to send notifications when objects are triggered

func SelectNotifier

func SelectNotifier(method string) (*Notification, Notifier, error)

SelectNotifier returns the Notification struct from the database

func SetDB

func SetDB(d *gorm.DB, zone float32)

SetDB is called by core to inject the database for a notifier to use

Types

type BasicEvents

type BasicEvents interface {
	OnSuccess(*types.Service)                 // OnSuccess is triggered when a service is successful
	OnFailure(*types.Service, *types.Failure) // OnFailure is triggered when a service is failing
}

BasicEvents includes the most minimal events, failing and successful service triggers

type CoreEvents

type CoreEvents interface {
	OnUpdatedCore(*types.Core)
	OnStart(*types.Core)
}

CoreEvents are events for the main Core app

type HTTPRouter

type HTTPRouter interface {
	OnGET() error
	OnPOST() error
}

HTTPRouter interface will allow your notifier to accept http GET/POST requests

type Notification

type Notification struct {
	Id        int64              `gorm:"primary_key;column:id" json:"id"`
	Method    string             `gorm:"column:method" json:"method"`
	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"`
	Enabled   types.NullBool     `gorm:"column:enabled;type:boolean;default:false" json:"enabled"`
	Limits    int                `gorm:"not null;column:limits" json:"limits"`
	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"`
	Form      []NotificationForm `gorm:"-" json:"form"`

	Title       string        `gorm:"-" json:"title"`
	Description string        `gorm:"-" json:"description"`
	Author      string        `gorm:"-" json:"author"`
	AuthorUrl   string        `gorm:"-" json:"author_url"`
	Icon        string        `gorm:"-" json:"icon"`
	Delay       time.Duration `gorm:"-" json:"delay,string"`
	Queue       []*QueueData  `gorm:"-" json:"-"`
	Running     chan bool     `gorm:"-" json:"-"`
	// contains filtered or unexported fields
}

Notification contains all the fields for a Statping Notifier.

Example

Create a new notifier that includes a form for the end user to insert their own values

// Create a new variable for your Notifier
example = &ExampleNotifier{&Notification{
	Method:      "Example",
	Title:       "Example Notifier",
	Description: "Example Notifier can hold many different types of fields for a customized look.",
	Author:      "Hunter Long",
	AuthorUrl:   "https://github.com/hunterlong",
	Delay:       time.Duration(1500 * time.Millisecond),
	Limits:      7,
	Form: []NotificationForm{{
		Type:        "text",
		Title:       "Host",
		Placeholder: "Insert your Host here.",
		DbField:     "host",
		SmallText:   "you can also use SmallText to insert some helpful hints under this input",
	}, {
		Type:        "text",
		Title:       "API Key",
		Placeholder: "Include some type of API key here",
		DbField:     "api_key",
	}},
}}

// AddNotifier accepts a Notifier to load into the Statping Notification system
err := AddNotifiers(example)
fmt.Println(err)
Output:

<nil>

func Init

func Init(n Notifier) (*Notification, error)

Init accepts the Notifier interface to initialize the notifier

func SelectNotification

func SelectNotification(n Notifier) (*Notification, error)

SelectNotification returns the Notification struct from the database

func Update

func Update(n Notifier, notif *Notification) (*Notification, error)

Update will update the notification into the database

func (*Notification) AddQueue

func (n *Notification) AddQueue(uid string, msg interface{})

AddQueue will add any type of interface (json, string, struct, etc) into the Notifiers queue

Example

Add any type of interface to the AddQueue function to be ran in the queue

msg := fmt.Sprintf("this is a failing message as a string passing into AddQueue function")
example.AddQueue("example", msg)
queue := example.Queue
fmt.Printf("Example has %v items in the queue", len(queue))
Output:

INFO: Notifier 'Example' added new item (example) to the queue. (2 queued)
Example has 2 items in the queue

func (*Notification) AfterFind added in v0.79.9

func (n *Notification) AfterFind() (err error)

AfterFind for Notification will set the timezone

func (*Notification) CanTest

func (n *Notification) CanTest() bool

CanTest returns true if the notifier implements the OnTest interface

Example

Implement the Test interface to give your notifier testing abilities

testable := example.CanTest()
fmt.Print(testable)
Output:

true

func (*Notification) GetValue

func (n *Notification) GetValue(dbField string) string

GetValue returns the database value of a accept DbField value.

func (*Notification) IsRunning

func (n *Notification) IsRunning() bool

IsRunning will return true if the notifier is currently running a queue

func (*Notification) LastSent

func (n *Notification) LastSent() time.Duration

LastSent returns a time.Duration of the last sent notification for the notifier

Example

LastSent will return the time.Duration of the last sent message

last := example.LastSent()
fmt.Printf("Last message was sent %v seconds ago", last.Seconds())
Output:

Last message was sent 0 seconds ago

func (*Notification) Logs

func (n *Notification) Logs() []*NotificationLog

Logs returns an array of the notifiers logs

Example

Logs will return a slice of previously sent items from your notifier

logs := example.Logs()
fmt.Printf("Example has %v items in the log", len(logs))
Output:

Example has 0 items in the log

func (*Notification) ResetQueue

func (n *Notification) ResetQueue()

ResetQueue will clear the notifiers Queue

func (*Notification) ResetUniqueQueue

func (n *Notification) ResetUniqueQueue(uid string) []*QueueData

ResetQueue will clear the notifiers Queue for a service

func (*Notification) SentLast

func (n *Notification) SentLast(since time.Time) int

SentLast accept a time.Time and returns the amount of sent notifications within your time to current

func (*Notification) SentLastHour

func (n *Notification) SentLastHour() int

SentLastHour returns the total amount of notifications sent in last 1 hour

Example

SentLastHour will return he amount of notifications sent in last 1 hour

lastHour := example.SentLastHour()
fmt.Printf("%v notifications sent in the last hour", lastHour)
Output:

0 notifications sent in the last hour

func (*Notification) SentLastMinute

func (n *Notification) SentLastMinute() int

SentLastMinute returns the total amount of notifications sent in last 1 minute

Example

SentLastMinute will return he amount of notifications sent in last 1 minute

lastMinute := example.SentLastMinute()
fmt.Printf("%v notifications sent in the last minute", lastMinute)
Output:

0 notifications sent in the last minute

func (*Notification) WithinLimits

func (n *Notification) WithinLimits() (bool, error)

WithinLimits returns true if the notifier is within its sending limits

Example

SentLastHour will return he amount of notifications sent in last 1 hour

ok, err := example.WithinLimits()
if err != nil {
	panic(err)
}
if ok {
	fmt.Printf("Example notifier is still within its sending limits")
}
Output:

Example notifier is still within its sending limits

type NotificationForm

type NotificationForm struct {
	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
	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
}

NotificationForm contains the HTML fields for each variable/input you want the notifier to accept.

type NotificationLog

type NotificationLog struct {
	Message   string          `json:"message"`
	Time      utils.Timestamp `json:"time"`
	Timestamp time.Time       `json:"timestamp"`
}

NotificationLog contains the normalized message from previously sent notifications

type Notifier

type Notifier interface {
	OnSave() error          // OnSave is triggered when the notifier is saved
	Send(interface{}) error // OnSave is triggered when the notifier is saved
	Select() *Notification  // Select returns the *Notification for a notifier
}

Notifier interface is required to create a new Notifier

type NotifierEvents

type NotifierEvents interface {
	OnNewNotifier(*Notification)
	OnUpdatedNotifier(*Notification)
}

NotifierEvents are events for other Notifiers

type QueueData

type QueueData struct {
	Id   string
	Data interface{}
}

QueueData is the struct for the messaging queue with service

type ServiceEvents

type ServiceEvents interface {
	OnNewService(*types.Service)
	OnUpdatedService(*types.Service)
	OnDeletedService(*types.Service)
}

ServiceEvents are events for Services

type Tester

type Tester interface {
	OnTest() error
}

Tester interface will include a function to Test users settings before saving

type UserEvents

type UserEvents interface {
	OnNewUser(*types.User)
	OnUpdatedUser(*types.User)
	OnDeletedUser(*types.User)
}

UserEvents are events for Users

Jump to

Keyboard shortcuts

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