statping: github.com/hunterlong/statping/core/notifier Index | Examples | Files

package notifier

import "github.com/hunterlong/statping/core/notifier"

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

Package Files

audit.go doc.go events.go interfaces.go notifiers.go

Variables

var (
    // AllCommunications holds all the loaded notifiers
    AllCommunications []types.AllNotifiers
)

func AddNotifier Uses

func AddNotifier(n Notifier) error

AddNotifier accept a Notifier interface to be added into the array

Add a Notifier to the AddQueue function to insert it into the system

Code:

err := AddNotifier(example)
fmt.Println(err)

Output:

<nil>

func Load Uses

func Load() []types.AllNotifiers

Load is called by core to add all the notifier into memory

func OnDeletedService Uses

func OnDeletedService(s *types.Service)

OnDeletedService is triggered when a service is deleted - ServiceEvents interface

func OnDeletedUser Uses

func OnDeletedUser(u *types.User)

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

func OnFailure Uses

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

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

Add a new message into the queue OnFailure

Code:

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

func OnNewNotifier Uses

func OnNewNotifier(n *Notification)

OnNewNotifier is triggered when a new notifier is loaded

func OnNewService Uses

func OnNewService(s *types.Service)

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

func OnNewUser Uses

func OnNewUser(u *types.User)

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

func OnSave Uses

func OnSave(method string)

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

func OnStart Uses

func OnStart(c *types.Core)

OnStart is triggered when the Statping service has started

func OnSuccess Uses

func OnSuccess(s *types.Service)

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

Add a new message into the queue OnSuccess

Code:

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

func OnUpdatedCore Uses

func OnUpdatedCore(c *types.Core)

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

func OnUpdatedNotifier Uses

func OnUpdatedNotifier(n *Notification)

OnUpdatedNotifier is triggered when a notifier has been updated

func OnUpdatedService Uses

func OnUpdatedService(s *types.Service)

OnUpdatedService is triggered when a service is updated - ServiceEvents interface

func OnUpdatedUser Uses

func OnUpdatedUser(u *types.User)

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

func Queue Uses

func Queue(n Notifier)

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

func SelectNotifier Uses

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

SelectNotifier returns the Notification struct from the database

func SetDB Uses

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

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

type BasicEvents Uses

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 Uses

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

CoreEvents are events for the main Core app

type HTTPRouter Uses

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

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

type Notification Uses

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:"-"`
    Online      bool          `gorm:"-" json:"online"`
    // contains filtered or unexported fields
}

Notification contains all the fields for a Statping Notifier.

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

Code:

// 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 := AddNotifier(example)
fmt.Println(err)

Output:

<nil>

func Init Uses

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

Init accepts the Notifier interface to initialize the notifier

func SelectNotification Uses

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

SelectNotification returns the Notification struct from the database

func Update Uses

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

Update will update the notification into the database

func (*Notification) AddQueue Uses

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

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

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

Code:

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:

Example has 2 items in the queue

func (*Notification) AfterFind Uses

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

AfterFind for Notification will set the timezone

func (*Notification) CanTest Uses

func (n *Notification) CanTest() bool

CanTest returns true if the notifier implements the OnTest interface

Implement the Test interface to give your notifier testing abilities

Code:

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

Output:

false

func (*Notification) GetValue Uses

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

GetValue returns the database value of a accept DbField value.

func (*Notification) IsRunning Uses

func (n *Notification) IsRunning() bool

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

func (*Notification) LastSent Uses

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

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

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

Code:

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 Uses

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

Logs returns an array of the notifiers logs

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

Code:

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 Uses

func (n *Notification) ResetQueue()

ResetQueue will clear the notifiers Queue

func (*Notification) ResetUniqueQueue Uses

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

ResetQueue will clear the notifiers Queue for a service

func (*Notification) SentLast Uses

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 Uses

func (n *Notification) SentLastHour() int

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

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

Code:

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

Output:

0 notifications sent in the last hour

func (*Notification) SentLastMinute Uses

func (n *Notification) SentLastMinute() int

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

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

Code:

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

Output:

0 notifications sent in the last minute

func (*Notification) WithinLimits Uses

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

WithinLimits returns true if the notifier is within its sending limits

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

Code:

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 Uses

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 Uses

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 Uses

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 Uses

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

NotifierEvents are events for other Notifiers

type QueueData Uses

type QueueData struct {
    Id   string
    Data interface{}
}

QueueData is the struct for the messaging queue with service

type ServiceEvents Uses

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

ServiceEvents are events for Services

type Tester Uses

type Tester interface {
    OnTest() error
}

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

type UserEvents Uses

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

UserEvents are events for Users

Package notifier imports 9 packages (graph) and is imported by 4 packages. Updated 2019-03-17. Refresh now. Tools for package owners.