comments - godoc in dev folder - cleaned

pull/78/head
Hunter Long 2018-10-05 23:38:33 -07:00
parent 892331ead6
commit 622e57cf1b
19 changed files with 1923 additions and 63 deletions

View File

@ -29,11 +29,6 @@ import (
"time" "time"
) )
const (
BRAKER = "=============================================================================="
POINT = " "
)
// CatchCLI will run functions based on the commands sent to Statup // CatchCLI will run functions based on the commands sent to Statup
func CatchCLI(args []string) error { func CatchCLI(args []string) error {
dir := utils.Directory dir := utils.Directory
@ -42,8 +37,6 @@ func CatchCLI(args []string) error {
LoadDotEnvs() LoadDotEnvs()
switch args[0] { switch args[0] {
case "seed":
handlers.DesktopInit(ipAddress, port)
case "app": case "app":
handlers.DesktopInit(ipAddress, port) handlers.DesktopInit(ipAddress, port)
case "version": case "version":

View File

@ -17,7 +17,6 @@ package core
import ( import (
"fmt" "fmt"
"github.com/ararog/timeago"
"github.com/hunterlong/statup/types" "github.com/hunterlong/statup/types"
"github.com/hunterlong/statup/utils" "github.com/hunterlong/statup/utils"
"time" "time"
@ -31,34 +30,41 @@ type CheckinHit struct {
*types.CheckinHit *types.CheckinHit
} }
// String will return a Checkin API string
func (c *Checkin) String() string { func (c *Checkin) String() string {
return c.ApiKey return c.ApiKey
} }
// ReturnCheckin converts *types.Checking to *core.Checkin
func ReturnCheckin(s *types.Checkin) *Checkin { func ReturnCheckin(s *types.Checkin) *Checkin {
return &Checkin{Checkin: s} return &Checkin{Checkin: s}
} }
// ReturnCheckinHit converts *types.CheckinHit to *core.CheckinHit
func ReturnCheckinHit(h *types.CheckinHit) *CheckinHit { func ReturnCheckinHit(h *types.CheckinHit) *CheckinHit {
return &CheckinHit{CheckinHit: h} return &CheckinHit{CheckinHit: h}
} }
// SelectCheckin will find a Checkin based on the API supplied
func SelectCheckin(api string) *Checkin { func SelectCheckin(api string) *Checkin {
var checkin Checkin var checkin Checkin
checkinDB().Where("api_key = ?", api).First(&checkin) checkinDB().Where("api_key = ?", api).First(&checkin)
return &checkin return &checkin
} }
// Period will return the duration of the Checkin interval
func (u *Checkin) Period() time.Duration { func (u *Checkin) Period() time.Duration {
duration, _ := time.ParseDuration(fmt.Sprintf("%vs", u.Interval)) duration, _ := time.ParseDuration(fmt.Sprintf("%vs", u.Interval))
return duration return duration
} }
// Grace will return the duration of the Checkin Grace Period (after service hasn't responded, wait a bit for a response)
func (u *Checkin) Grace() time.Duration { func (u *Checkin) Grace() time.Duration {
duration, _ := time.ParseDuration(fmt.Sprintf("%vs", u.GracePeriod)) duration, _ := time.ParseDuration(fmt.Sprintf("%vs", u.GracePeriod))
return duration return duration
} }
// Expected returns the duration of when the serviec should receive a checkin
func (u *Checkin) Expected() time.Duration { func (u *Checkin) Expected() time.Duration {
last := u.Last().CreatedAt last := u.Last().CreatedAt
now := time.Now() now := time.Now()
@ -67,18 +73,21 @@ func (u *Checkin) Expected() time.Duration {
return sub return sub
} }
// Last returns the last CheckinHit for a Checkin
func (u *Checkin) Last() CheckinHit { func (u *Checkin) Last() CheckinHit {
var hit CheckinHit var hit CheckinHit
checkinHitsDB().Where("checkin = ?", u.Id).Last(&hit) checkinHitsDB().Where("checkin = ?", u.Id).Last(&hit)
return hit return hit
} }
// Hits returns all of the CheckinHits for a given Checkin
func (u *Checkin) Hits() []CheckinHit { func (u *Checkin) Hits() []CheckinHit {
var checkins []CheckinHit var checkins []CheckinHit
checkinHitsDB().Where("checkin = ?", u.Id).Order("id DESC").Find(&checkins) checkinHitsDB().Where("checkin = ?", u.Id).Order("id DESC").Find(&checkins)
return checkins return checkins
} }
// Create will create a new Checkin
func (u *Checkin) Create() (int64, error) { func (u *Checkin) Create() (int64, error) {
u.ApiKey = utils.RandomString(7) u.ApiKey = utils.RandomString(7)
row := checkinDB().Create(&u) row := checkinDB().Create(&u)
@ -89,6 +98,7 @@ func (u *Checkin) Create() (int64, error) {
return u.Id, row.Error return u.Id, row.Error
} }
// Update will update a Checkin
func (u *Checkin) Update() (int64, error) { func (u *Checkin) Update() (int64, error) {
row := checkinDB().Update(&u) row := checkinDB().Update(&u)
if row.Error != nil { if row.Error != nil {
@ -98,6 +108,7 @@ func (u *Checkin) Update() (int64, error) {
return u.Id, row.Error return u.Id, row.Error
} }
// Create will create a new successful CheckinHit
func (u *CheckinHit) Create() (int64, error) { func (u *CheckinHit) Create() (int64, error) {
if u.CreatedAt.IsZero() { if u.CreatedAt.IsZero() {
u.CreatedAt = time.Now() u.CreatedAt = time.Now()
@ -110,27 +121,11 @@ func (u *CheckinHit) Create() (int64, error) {
return u.Id, row.Error return u.Id, row.Error
} }
func SelectCheckinApi(api string) *Checkin { // RecheckCheckinFailure will check if a Service Checkin has been reported yet
var checkin *Checkin
checkinDB().Where("api = ?", api).Find(&checkin)
return checkin
}
func (c *Checkin) CreateHit() (int64, error) {
c.CreatedAt = time.Now()
row := checkinDB().Create(c)
if row.Error != nil {
utils.Log(2, row.Error)
return 0, row.Error
}
return c.Id, row.Error
}
func (c *Checkin) RecheckCheckinFailure(guard chan struct{}) { func (c *Checkin) RecheckCheckinFailure(guard chan struct{}) {
between := time.Now().Sub(time.Now()).Seconds() between := time.Now().Sub(time.Now()).Seconds()
if between > float64(c.Interval) { if between > float64(c.Interval) {
fmt.Println("rechecking every 15 seconds!") fmt.Println("rechecking every 15 seconds!")
c.CreateFailure()
time.Sleep(15 * time.Second) time.Sleep(15 * time.Second)
guard <- struct{}{} guard <- struct{}{}
c.RecheckCheckinFailure(guard) c.RecheckCheckinFailure(guard)
@ -139,17 +134,3 @@ func (c *Checkin) RecheckCheckinFailure(guard chan struct{}) {
} }
<-guard <-guard
} }
func (f *Checkin) CreateFailure() {
}
func (f *Checkin) Ago() string {
got, _ := timeago.TimeAgoWithTime(time.Now(), time.Now())
return got
}
func (f *CheckinHit) Ago() string {
got, _ := timeago.TimeAgoWithTime(time.Now(), time.Now())
return got
}

View File

@ -25,6 +25,7 @@ import (
"os" "os"
) )
// ErrorResponse is used for HTTP errors to show to user
type ErrorResponse struct { type ErrorResponse struct {
Error string Error string
} }

View File

@ -43,6 +43,7 @@ func init() {
CoreApp = NewCore() CoreApp = NewCore()
} }
// NewCore return a new *core.Core struct
func NewCore() *Core { func NewCore() *Core {
CoreApp = new(Core) CoreApp = new(Core)
CoreApp.Core = new(types.Core) CoreApp.Core = new(types.Core)
@ -50,6 +51,7 @@ func NewCore() *Core {
return CoreApp return CoreApp
} }
// ToCore will convert *core.Core to *types.Core
func (c *Core) ToCore() *types.Core { func (c *Core) ToCore() *types.Core {
return c.Core return c.Core
} }
@ -64,6 +66,7 @@ func InitApp() {
go DatabaseMaintence() go DatabaseMaintence()
} }
// insertNotifierDB inject the Statup database instance to the Notifier package
func insertNotifierDB() error { func insertNotifierDB() error {
if DbSession == nil { if DbSession == nil {
err := Configs.Connect(false, utils.Directory) err := Configs.Connect(false, utils.Directory)

View File

@ -77,6 +77,7 @@ func (s *Service) HitsBetween(t1, t2 time.Time, group string, column string) *go
return DbSession.Model(&types.Hit{}).Select(selector).Where("service = ? AND created_at BETWEEN ? AND ?", s.Id, t1.Format(types.TIME_DAY), t2.Format(types.TIME_DAY)).Order("timeframe asc", false).Group("timeframe") return DbSession.Model(&types.Hit{}).Select(selector).Where("service = ? AND created_at BETWEEN ? AND ?", s.Id, t1.Format(types.TIME_DAY), t2.Format(types.TIME_DAY)).Order("timeframe asc", false).Group("timeframe")
} }
// CloseDB will close the database connection if available
func CloseDB() { func CloseDB() {
if DbSession != nil { if DbSession != nil {
DbSession.DB().Close() DbSession.DB().Close()
@ -88,36 +89,43 @@ func (db *DbConfig) Close() error {
return DbSession.DB().Close() return DbSession.DB().Close()
} }
// AfterFind for Service will set the timezone
func (s *Service) AfterFind() (err error) { func (s *Service) AfterFind() (err error) {
s.CreatedAt = utils.Timezoner(s.CreatedAt, CoreApp.Timezone) s.CreatedAt = utils.Timezoner(s.CreatedAt, CoreApp.Timezone)
return return
} }
// AfterFind for Hit will set the timezone
func (s *Hit) AfterFind() (err error) { func (s *Hit) AfterFind() (err error) {
s.CreatedAt = utils.Timezoner(s.CreatedAt, CoreApp.Timezone) s.CreatedAt = utils.Timezoner(s.CreatedAt, CoreApp.Timezone)
return return
} }
// AfterFind for Failure will set the timezone
func (f *Failure) AfterFind() (err error) { func (f *Failure) AfterFind() (err error) {
f.CreatedAt = utils.Timezoner(f.CreatedAt, CoreApp.Timezone) f.CreatedAt = utils.Timezoner(f.CreatedAt, CoreApp.Timezone)
return return
} }
// AfterFind for USer will set the timezone
func (u *User) AfterFind() (err error) { func (u *User) AfterFind() (err error) {
u.CreatedAt = utils.Timezoner(u.CreatedAt, CoreApp.Timezone) u.CreatedAt = utils.Timezoner(u.CreatedAt, CoreApp.Timezone)
return return
} }
// AfterFind for Checkin will set the timezone
func (s *Checkin) AfterFind() (err error) { func (s *Checkin) AfterFind() (err error) {
s.CreatedAt = utils.Timezoner(s.CreatedAt, CoreApp.Timezone) s.CreatedAt = utils.Timezoner(s.CreatedAt, CoreApp.Timezone)
return return
} }
// AfterFind for CheckinHit will set the timezone
func (s *CheckinHit) AfterFind() (err error) { func (s *CheckinHit) AfterFind() (err error) {
s.CreatedAt = utils.Timezoner(s.CreatedAt, CoreApp.Timezone) s.CreatedAt = utils.Timezoner(s.CreatedAt, CoreApp.Timezone)
return return
} }
// BeforeCreate for Hit will set CreatedAt to UTC
func (u *Hit) BeforeCreate() (err error) { func (u *Hit) BeforeCreate() (err error) {
if u.CreatedAt.IsZero() { if u.CreatedAt.IsZero() {
u.CreatedAt = time.Now().UTC() u.CreatedAt = time.Now().UTC()
@ -125,6 +133,7 @@ func (u *Hit) BeforeCreate() (err error) {
return return
} }
// BeforeCreate for Failure will set CreatedAt to UTC
func (u *Failure) BeforeCreate() (err error) { func (u *Failure) BeforeCreate() (err error) {
if u.CreatedAt.IsZero() { if u.CreatedAt.IsZero() {
u.CreatedAt = time.Now().UTC() u.CreatedAt = time.Now().UTC()
@ -132,6 +141,7 @@ func (u *Failure) BeforeCreate() (err error) {
return return
} }
// BeforeCreate for User will set CreatedAt to UTC
func (u *User) BeforeCreate() (err error) { func (u *User) BeforeCreate() (err error) {
if u.CreatedAt.IsZero() { if u.CreatedAt.IsZero() {
u.CreatedAt = time.Now().UTC() u.CreatedAt = time.Now().UTC()
@ -139,6 +149,7 @@ func (u *User) BeforeCreate() (err error) {
return return
} }
// BeforeCreate for Service will set CreatedAt to UTC
func (u *Service) BeforeCreate() (err error) { func (u *Service) BeforeCreate() (err error) {
if u.CreatedAt.IsZero() { if u.CreatedAt.IsZero() {
u.CreatedAt = time.Now().UTC() u.CreatedAt = time.Now().UTC()
@ -146,6 +157,7 @@ func (u *Service) BeforeCreate() (err error) {
return return
} }
// BeforeCreate for Checkin will set CreatedAt to UTC
func (u *Checkin) BeforeCreate() (err error) { func (u *Checkin) BeforeCreate() (err error) {
if u.CreatedAt.IsZero() { if u.CreatedAt.IsZero() {
u.CreatedAt = time.Now().UTC() u.CreatedAt = time.Now().UTC()
@ -153,6 +165,7 @@ func (u *Checkin) BeforeCreate() (err error) {
return return
} }
// BeforeCreate for CheckinHit will set CreatedAt to UTC
func (u *CheckinHit) BeforeCreate() (err error) { func (u *CheckinHit) BeforeCreate() (err error) {
if u.CreatedAt.IsZero() { if u.CreatedAt.IsZero() {
u.CreatedAt = time.Now().UTC() u.CreatedAt = time.Now().UTC()
@ -223,6 +236,7 @@ func (db *DbConfig) Connect(retry bool, location string) error {
return err return err
} }
// waitForDb will sleep for 5 seconds and try to connect to the database again
func (db *DbConfig) waitForDb() error { func (db *DbConfig) waitForDb() error {
time.Sleep(5 * time.Second) time.Sleep(5 * time.Second)
return db.Connect(true, utils.Directory) return db.Connect(true, utils.Directory)
@ -361,12 +375,3 @@ func (db *DbConfig) MigrateDatabase() error {
utils.Log(1, "Statup Database Migrated") utils.Log(1, "Statup Database Migrated")
return tx.Commit().Error return tx.Commit().Error
} }
func (c *DbConfig) Clean() *DbConfig {
if os.Getenv("DB_PORT") != "" {
if c.DbConn == "postgres" {
c.DbHost = c.DbHost + ":" + os.Getenv("DB_PORT")
}
}
return c
}

View File

@ -28,10 +28,6 @@ func injectDatabase() {
Configs.Connect(false, utils.Directory) Configs.Connect(false, utils.Directory)
} }
func GenerateSeed() {
}
func ExportIndexHTML() string { func ExportIndexHTML() string {
source.Assets() source.Assets()
injectDatabase() injectDatabase()

View File

@ -139,6 +139,7 @@ func InsertSampleHits() error {
return nil return nil
} }
// insertSampleCore will create a new Core for the seed
func insertSampleCore() error { func insertSampleCore() error {
core := &types.Core{ core := &types.Core{
Name: "Statup Sample Data", Name: "Statup Sample Data",
@ -154,6 +155,7 @@ func insertSampleCore() error {
return query.Error return query.Error
} }
// insertSampleUsers will create 2 admin users for a seed database
func insertSampleUsers() { func insertSampleUsers() {
u2 := ReturnUser(&types.User{ u2 := ReturnUser(&types.User{
Username: "testadmin", Username: "testadmin",
@ -308,6 +310,7 @@ func InsertLargeSampleData() error {
return nil return nil
} }
// insertFailureRecords will create failures for 15 services from seed
func insertFailureRecords(since time.Time, amount int64) { func insertFailureRecords(since time.Time, amount int64) {
for i := int64(14); i <= 15; i++ { for i := int64(14); i <= 15; i++ {
service := SelectService(i) service := SelectService(i)
@ -328,6 +331,7 @@ func insertFailureRecords(since time.Time, amount int64) {
} }
} }
// insertHitRecords will create successful Hit records for 15 services
func insertHitRecords(since time.Time, amount int64) { func insertHitRecords(since time.Time, amount int64) {
for i := int64(1); i <= 15; i++ { for i := int64(1); i <= 15; i++ {
service := SelectService(i) service := SelectService(i)

View File

@ -31,10 +31,12 @@ type Service struct {
*types.Service *types.Service
} }
// Select will return the *types.Service struct for Service
func (s *Service) Select() *types.Service { func (s *Service) Select() *types.Service {
return s.Service return s.Service
} }
// ReturnService will convert *types.Service to *core.Service
func ReturnService(s *types.Service) *Service { func ReturnService(s *types.Service) *Service {
return &Service{s} return &Service{s}
} }
@ -49,6 +51,7 @@ func SelectService(id int64) *Service {
return nil return nil
} }
// Checkins will return a slice of Checkins for a Service
func (s *Service) Checkins() []*Checkin { func (s *Service) Checkins() []*Checkin {
var checkin []*Checkin var checkin []*Checkin
checkinDB().Where("service = ?", s.Id).Find(&checkin) checkinDB().Where("service = ?", s.Id).Find(&checkin)
@ -168,10 +171,12 @@ func (s *Service) SmallText() string {
} }
} }
// DowntimeText will return the amount of downtime for a service based on the duration
func (s *Service) DowntimeText() string { func (s *Service) DowntimeText() string {
return fmt.Sprintf("%v has been offline for %v", s.Name, utils.DurationReadable(s.Downtime())) return fmt.Sprintf("%v has been offline for %v", s.Name, utils.DurationReadable(s.Downtime()))
} }
// Dbtimestamp will return a SQL query for grouping by date
func Dbtimestamp(group string, column string) string { func Dbtimestamp(group string, column string) string {
seconds := 60 seconds := 60
if group == "second" { if group == "second" {
@ -207,6 +212,7 @@ func (s *Service) Downtime() time.Duration {
return since return since
} }
// GraphDataRaw will return all the hits between 2 times for a Service
func GraphDataRaw(service types.ServiceInterface, start, end time.Time, group string, column string) *DateScanObj { func GraphDataRaw(service types.ServiceInterface, start, end time.Time, group string, column string) *DateScanObj {
var d []DateScan var d []DateScan
model := service.(*Service).HitsBetween(start, end, group, column) model := service.(*Service).HitsBetween(start, end, group, column)
@ -228,6 +234,7 @@ func GraphDataRaw(service types.ServiceInterface, start, end time.Time, group st
return &DateScanObj{d} return &DateScanObj{d}
} }
// ToString will convert the DateScanObj into a JSON string for the charts to render
func (d *DateScanObj) ToString() string { func (d *DateScanObj) ToString() string {
data, err := json.Marshal(d.Array) data, err := json.Marshal(d.Array)
if err != nil { if err != nil {

1857
dev/COVERAGE.html Normal file

File diff suppressed because one or more lines are too long

2
dev/LINT.md Normal file
View File

@ -0,0 +1,2 @@
0 problems (0 errors) (0 warnings)

3
dev/README.md Normal file
View File

@ -0,0 +1,3 @@
- - -
Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md)

View File

@ -1,4 +1,4 @@
// Package handlers holds all the HTTP requests and routes. All HTTP related // Package handlers contains the HTTP server along with the requests and routes. All HTTP related
// functions are in this package. // functions are in this package.
// //
// More info on: https://github.com/hunterlong/statup // More info on: https://github.com/hunterlong/statup

View File

@ -63,7 +63,8 @@ func RunHTTPServer(ip string, port int) error {
return httpServer.ListenAndServe() return httpServer.ListenAndServe()
} }
// IsAuthenticated returns true if the HTTP request is authenticated // IsAuthenticated returns true if the HTTP request is authenticated. You can set the environment variable GO_ENV=test
// to bypass the admin authenticate to the dashboard features.
func IsAuthenticated(r *http.Request) bool { func IsAuthenticated(r *http.Request) bool {
if os.Getenv("GO_ENV") == "test" { if os.Getenv("GO_ENV") == "test" {
return true return true

View File

@ -119,7 +119,6 @@ func TestServiceChartHandler(t *testing.T) {
Router().ServeHTTP(rr, req) Router().ServeHTTP(rr, req)
body := rr.Body.String() body := rr.Body.String()
assert.Equal(t, 200, rr.Code) assert.Equal(t, 200, rr.Code)
t.Log(body)
assert.Contains(t, body, "var ctx_1") assert.Contains(t, body, "var ctx_1")
assert.Contains(t, body, "var ctx_2") assert.Contains(t, body, "var ctx_2")
assert.Contains(t, body, "var ctx_3") assert.Contains(t, body, "var ctx_3")

View File

@ -30,6 +30,7 @@ var (
router *mux.Router router *mux.Router
) )
// Router returns all of the routes used in Statup
func Router() *mux.Router { func Router() *mux.Router {
dir := utils.Directory dir := utils.Directory
r := mux.NewRouter() r := mux.NewRouter()

View File

@ -29,10 +29,6 @@ import (
"time" "time"
) )
type Service struct {
*types.Service
}
func renderServiceChartHandler(w http.ResponseWriter, r *http.Request) { func renderServiceChartHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) vars := mux.Vars(r)
fields := parseGet(r) fields := parseGet(r)

View File

@ -3,5 +3,7 @@
// to see a full example of a notifier with all events, visit Statup's // to see a full example of a notifier with all events, visit Statup's
// notifier example code: https://github.com/hunterlong/statup/wiki/Notifier-Example // notifier example code: https://github.com/hunterlong/statup/wiki/Notifier-Example
// //
// More info on: https://github.com/hunterlong/statup // This package shouldn't contain any exports, to see how notifiers work
// visit the core/notifier package at: https://godoc.org/github.com/hunterlong/statup/core/notifier
// and learn how to create your own custom notifier.
package notifiers package notifiers

View File

@ -24,8 +24,8 @@ import (
) )
var ( var (
SLACK_URL string SLACK_URL string
slackMessage = `{"text":"this is a test from the slack notifier!"}` slackTestMessage = `{"text":"this is a test from the slack notifier!"}`
) )
func init() { func init() {
@ -96,7 +96,7 @@ func TestSlackNotifier(t *testing.T) {
}) })
t.Run("slack Send", func(t *testing.T) { t.Run("slack Send", func(t *testing.T) {
err := slacker.Send(slackMessage) err := slacker.Send(slackTestMessage)
assert.Nil(t, err) assert.Nil(t, err)
assert.Len(t, slacker.Queue, 3) assert.Len(t, slacker.Queue, 3)
}) })

View File

@ -70,3 +70,12 @@ func TestCopyToPluginFailed(t *testing.T) {
assert.Nil(t, DeleteAllAssets(dir)) assert.Nil(t, DeleteAllAssets(dir))
assert.False(t, UsingAssets(dir)) assert.False(t, UsingAssets(dir))
} }
func ExampleSaveAsset() {
data := []byte("alert('helloooo')")
SaveAsset(data, "js", "test.js")
}
func ExampleOpenAsset() {
OpenAsset("js", "main.js")
}