pull/10/head
Hunter Long 2018-06-28 19:24:31 -07:00
parent ca53f6c9cd
commit 08b4781367
19 changed files with 138 additions and 63 deletions

2
.env
View File

@ -1,7 +1,7 @@
###########################
## Database Information #
###########################
DB_CONNECTION=postgres
DB_CONN=postgres
DB_HOST=0.0.0.0
DB_PORT=5432
DB_USER=root

3
.gitignore vendored
View File

@ -11,4 +11,5 @@ dart-sass
.sass-cache
public
assets
cmd.sh
cmd.sh
*.log

View File

@ -3,6 +3,7 @@ package main
import (
"fmt"
"github.com/GeertJohan/go.rice"
"github.com/hunterlong/statup/log"
"io/ioutil"
"os"
"os/exec"
@ -15,7 +16,7 @@ var (
func CopyToPublic(box *rice.Box, folder, file string) {
base, err := box.String(file)
if err != nil {
fmt.Println(err)
log.Send(2, err)
}
ioutil.WriteFile("assets/"+folder+"/"+file, []byte(base), 0644)
}
@ -24,7 +25,7 @@ func MakePublicFolder(folder string) {
if _, err := os.Stat(folder); os.IsNotExist(err) {
err = os.MkdirAll(folder, 0755)
if err != nil {
fmt.Println(err)
log.Send(2, err)
}
}
}
@ -32,14 +33,14 @@ func MakePublicFolder(folder string) {
func CompileSASS() {
cmdBin := os.Getenv("SASS")
shell := os.Getenv("BASH_ENV")
fmt.Println("Compiling SASS into /css/base.css...")
log.Send(1, fmt.Sprintf("Compiling SASS into /css/base.css..."))
command := fmt.Sprintf("%v %v %v", cmdBin, "assets/scss/base.scss", "assets/css/base.css")
testCmd := exec.Command(shell, command)
_, err := testCmd.Output()
if err != nil {
fmt.Println(err)
}
fmt.Println("SASS Compiling is complete!")
log.Send(1, "SASS Compiling is complete!")
}
func hasAssets() bool {
@ -62,18 +63,19 @@ func SaveAsset(data, file string) {
}
func OpenAsset(file string) string {
dat, _ := ioutil.ReadFile("assets/" + file)
dat, err := ioutil.ReadFile("assets/" + file)
log.Send(2, err)
return string(dat)
}
func CreateAllAssets() {
fmt.Println("Creating folder 'assets' in current directory..")
log.Send(1, "Creating folder 'assets' in current directory..")
MakePublicFolder("assets")
MakePublicFolder("assets/js")
MakePublicFolder("assets/css")
MakePublicFolder("assets/scss")
MakePublicFolder("assets/emails")
fmt.Println("Inserting scss, css, emails, and javascript files into assets..")
log.Send(1, "Inserting scss, css, emails, and javascript files into assets..")
CopyToPublic(scssBox, "scss", "base.scss")
CopyToPublic(scssBox, "scss", "variables.scss")
CopyToPublic(emailBox, "emails", "error.html")
@ -84,7 +86,7 @@ func CreateAllAssets() {
CopyToPublic(jsBox, "js", "jquery-3.3.1.slim.min.js")
CopyToPublic(jsBox, "js", "main.js")
CopyToPublic(jsBox, "js", "setup.js")
fmt.Println("Compiling CSS from SCSS style...")
log.Send(1, "Compiling CSS from SCSS style...")
CompileSASS()
fmt.Println("Statup assets have been inserted")
log.Send(1, "Statup assets have been inserted")
}

View File

@ -2,6 +2,7 @@ package main
import (
"fmt"
"github.com/hunterlong/statup/log"
"io/ioutil"
"net/http"
"regexp"
@ -10,6 +11,7 @@ import (
func CheckServices() {
services, _ = SelectAllServices()
log.Send(1, fmt.Sprintf("Loaded %v Services", len(services)))
for _, v := range services {
obj := v
go obj.StartCheckins()
@ -23,7 +25,8 @@ func (s *Service) CheckQueue() {
if s.Interval < 1 {
s.Interval = 1
}
fmt.Printf(" Service: %v | Online: %v | Latency: %0.0fms\n", s.Name, s.Online, (s.Latency * 1000))
msg := fmt.Sprintf("Service: %v | Online: %v | Latency: %0.0fms", s.Name, s.Online, (s.Latency * 1000))
log.Send(0, msg)
time.Sleep(time.Duration(s.Interval) * time.Second)
}
@ -86,6 +89,7 @@ func (s *Service) Failure(issue string) {
data := FailureData{
Issue: issue,
}
log.Send(1, fmt.Sprintf("Service %v Failing: %v", s.Name, issue))
s.CreateFailure(data)
SendFailureEmail(s)
OnFailure(s)

View File

@ -3,6 +3,7 @@ package main
import (
"fmt"
"github.com/ararog/timeago"
"github.com/hunterlong/statup/log"
"time"
)
@ -28,6 +29,7 @@ func (u *Checkin) Create() (int64, error) {
u.CreatedAt = time.Now()
uuid, err := dbSession.Collection("checkins").Insert(u)
if uuid == nil {
log.Send(2, err)
return 0, err
}
fmt.Println("new checkin: ", uuid)

30
cli.go
View File

@ -2,8 +2,8 @@ package main
import (
"fmt"
"github.com/hunterlong/statup/log"
"github.com/joho/godotenv"
"os"
"time"
)
@ -22,34 +22,40 @@ func CatchCLI(args []string) {
RenderBoxes()
configs, err = LoadConfig()
if err != nil {
logger(3, "config.yml file not found")
log.Send(3, "config.yml file not found")
}
setupMode = true
mainProcess()
time.Sleep(10 * time.Second)
indexSource := ExportIndexHTML()
SaveFile("./index.html", []byte(indexSource))
fmt.Println("Exported Statup index page: 'index.html'")
err = SaveFile("./index.html", []byte(indexSource))
if err != nil {
log.Send(2, err)
}
log.Send(1, "Exported Statup index page: 'index.html'")
case "help":
HelpEcho()
case "update":
fmt.Println("Sorry updating isn't available yet!")
case "run":
fmt.Println("Running 1 time and saving to database...")
log.Send(1, "Running 1 time and saving to database...")
var err error
configs, err = LoadConfig()
if err != nil {
logger(3, "config.yml file not found")
log.Send(3, "config.yml file not found")
}
err = DbConnection(configs.Connection)
if err != nil {
throw(err)
log.Send(3, err)
}
core, err = SelectCore()
if err != nil {
fmt.Println("Core database was not found, Statup is not setup yet.")
}
services, _ = SelectAllServices()
services, err = SelectAllServices()
if err != nil {
log.Send(3, err)
}
for _, s := range services {
out := s.Check()
fmt.Printf(" Service %v | URL: %v | Latency: %0.0fms | Online: %v\n", out.Name, out.Domain, (out.Latency * 1000), out.Online)
@ -59,15 +65,13 @@ func CatchCLI(args []string) {
fmt.Println("Statup Environment Variables")
envs, err := godotenv.Read(".env")
if err != nil {
fmt.Println("No .env file found in current directory.")
os.Exit(1)
log.Send(3, "No .env file found in current directory.")
}
for k, e := range envs {
fmt.Printf("%v=%v\n", k, e)
}
default:
fmt.Println("Statup does not have the command you entered.")
os.Exit(1)
log.Send(3, "Statup does not have the command you entered.")
}
}
@ -77,6 +81,8 @@ func HelpEcho() {
fmt.Printf("Commands:\n")
fmt.Println(" statup - Main command to run Statup server")
fmt.Println(" statup version - Returns the current version of Statup")
fmt.Println(" statup run - Check all service 1 time and then quit")
fmt.Println(" statup env - Show all environment variables being used for Statup")
fmt.Println(" statup export - Exports the index page as a static HTML for pushing")
fmt.Println(" to Github Pages or your own FTP server. Export will")
fmt.Println(" create 'index.html' in the current directory.")

View File

@ -1,6 +1,7 @@
package main
import (
"github.com/hunterlong/statup/log"
"github.com/hunterlong/statup/types"
"time"
)
@ -43,9 +44,10 @@ func Create(c *types.Communication) (int64, error) {
c.CreatedAt = time.Now()
uuid, err := dbSession.Collection("communication").Insert(c)
if err != nil {
panic(err)
log.Send(3, err)
}
if uuid == nil {
log.Send(2, err)
return 0, err
}
c.Id = uuid.(int64)

View File

@ -38,7 +38,7 @@ func (c Core) SassVars() string {
if !useAssets {
return ""
}
return OpenAsset("scss/variables.scss")
return OpenAsset("scss/_variables.scss")
}
func (c Core) BaseSASS() string {

View File

@ -4,10 +4,10 @@ import (
"bytes"
"crypto/tls"
"fmt"
"github.com/hunterlong/statup/log"
"github.com/hunterlong/statup/types"
"gopkg.in/gomail.v2"
"html/template"
"log"
"time"
)
@ -64,6 +64,7 @@ func Send(em *types.Email) {
m.SetHeader("Subject", em.Subject)
m.SetBody("text/html", source)
if err := emailQue.Mailer.DialAndSend(m); err != nil {
log.Send(2, err)
fmt.Println(err)
}
emailQue.LastSent++
@ -103,7 +104,7 @@ func EmailTemplate(tmpl string, data interface{}) string {
}
var tpl bytes.Buffer
if err := t.Execute(&tpl, data); err != nil {
log.Println(err)
log.Send(2, err)
}
result := tpl.String()
return result

View File

@ -2,6 +2,7 @@ package main
import (
"github.com/ararog/timeago"
"github.com/hunterlong/statup/log"
"time"
)
@ -72,6 +73,7 @@ func CountFailures() uint64 {
col := dbSession.Collection("failures").Find()
amount, err := col.Count()
if err != nil {
log.Send(2, err)
return 0
}
return amount

View File

@ -1,6 +1,7 @@
package main
import (
"github.com/hunterlong/statup/log"
"time"
"upper.io/db.v3"
)
@ -24,6 +25,7 @@ func (s *Service) CreateHit(d HitData) (int64, error) {
}
uuid, err := hitCol().Insert(h)
if uuid == nil {
log.Send(2, err)
return 0, err
}
return uuid.(int64), err

56
log/log.go Normal file
View File

@ -0,0 +1,56 @@
package log
import (
"github.com/fatih/color"
lg "log"
"os"
//"github.com/mkideal/log/logger"
)
var (
logFile *os.File
logLevel int
)
func init() {
var err error
logFile, err = os.OpenFile("statup.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
lg.Fatalf("error opening file: %v", err)
}
lg.SetOutput(logFile)
logEnv := os.Getenv("LOG")
if logEnv == "fatal" {
logLevel = 3
} else if logEnv == "debug" {
logLevel = 2
} else if logEnv == "info" {
logLevel = 1
} else {
logLevel = 0
}
}
func Panic(err interface{}) {
panic(err)
}
func Send(level int, err interface{}) {
switch level {
case 3:
lg.Printf("ERROR: %v\n", err)
color.Red("ERROR: %v\n", err)
os.Exit(2)
case 2:
lg.Printf("WARNING: %v\n", err)
color.Yellow("WARNING: %v\n", err)
case 1:
lg.Printf("INFO: %v\n", err)
color.Blue("INFO: %v\n", err)
case 0:
lg.Printf("%v\n", err)
color.White("%v\n", err)
}
}

32
main.go
View File

@ -6,6 +6,7 @@ import (
"github.com/GeertJohan/go.rice"
"github.com/go-yaml/yaml"
"github.com/gorilla/sessions"
"github.com/hunterlong/statup/log"
"github.com/hunterlong/statup/plugin"
"github.com/joho/godotenv"
"golang.org/x/crypto/bcrypt"
@ -16,7 +17,6 @@ import (
plg "plugin"
"strconv"
"strings"
"github.com/fatih/color"
)
var (
@ -32,6 +32,7 @@ var (
emailBox *rice.Box
setupMode bool
allPlugins []plugin.PluginActions
logFile *os.File
)
const (
@ -105,25 +106,8 @@ func LoadDotEnvs() {
}
}
func logger(level int, err interface{}) {
switch level {
case 3:
color.Red("ERROR: %v\n", err)
os.Exit(2)
case 2:
color.Yellow("WARNING: %v\n", err)
case 1:
color.Blue("INFO: %v\n", err)
case 0:
color.White("%v\n", err)
}
}
func main() {
defer logFile.Close()
if len(os.Args) >= 2 {
CatchCLI(os.Args)
os.Exit(0)
@ -136,7 +120,7 @@ func main() {
configs, err = LoadConfig()
if err != nil {
logger(1, "config.yml file not found - starting in setup mode")
log.Send(1, "config.yml file not found - starting in setup mode")
setupMode = true
RunHTTPServer()
}
@ -157,7 +141,7 @@ func mainProcess() {
RunDatabaseUpgrades()
core, err = SelectCore()
if err != nil {
logger(1, "Core database was not found, Statup is not setup yet.")
log.Send(1, "Core database was not found, Statup is not setup yet.")
RunHTTPServer()
}
@ -195,7 +179,7 @@ func LoadPlugins() {
files, err := ioutil.ReadDir("./plugins")
if err != nil {
fmt.Printf("Plugins directory was not found. Error: %v\n", err)
log.Send(1, fmt.Sprintf("Plugins directory was not found. Error: %v\n", err))
return
}
for _, f := range files {
@ -208,7 +192,7 @@ func LoadPlugins() {
}
plug, err := plg.Open("plugins/" + f.Name())
if err != nil {
fmt.Printf("Plugin '%v' could not load correctly.\n", f.Name())
log.Send(2, fmt.Sprintf("Plugin '%v' could not load correctly.\n", f.Name()))
continue
}
symPlugin, err := plug.Lookup("Plugin")
@ -216,7 +200,7 @@ func LoadPlugins() {
var plugActions plugin.PluginActions
plugActions, ok := symPlugin.(plugin.PluginActions)
if !ok {
fmt.Printf("Plugin '%v' could not load correctly, error: %v\n", f.Name(), "unexpected type from module symbol")
log.Send(2, fmt.Sprintf("Plugin '%v' could not load correctly, error: %v\n", f.Name(), "unexpected type from module symbol"))
continue
}

View File

@ -1,10 +1,10 @@
package main
import (
"github.com/rendon/testcli"
"github.com/stretchr/testify/assert"
"os"
"testing"
"github.com/rendon/testcli"
)
func TestInit(t *testing.T) {

View File

@ -3,6 +3,7 @@ package main
import (
"encoding/json"
"fmt"
"github.com/hunterlong/statup/log"
"strconv"
"time"
"upper.io/db.v3"
@ -107,7 +108,7 @@ func (s *Service) GraphData() string {
sql := fmt.Sprintf("SELECT date_trunc('%v', created_at), AVG(latency)*1000 AS value FROM hits WHERE service=%v AND created_at > '%v' GROUP BY 1 ORDER BY date_trunc ASC;", increment, s.Id, since.Format(time.RFC3339))
dated, err := dbSession.Query(db.Raw(sql))
if err != nil {
fmt.Println(err)
log.Send(2, err)
return ""
}
for dated.Next() {
@ -119,7 +120,7 @@ func (s *Service) GraphData() string {
}
data, err := json.Marshal(d)
if err != nil {
fmt.Println(err)
log.Send(2, err)
return ""
}
return string(data)

View File

@ -3,6 +3,7 @@ package main
import (
"fmt"
"github.com/go-yaml/yaml"
"github.com/hunterlong/statup/log"
"github.com/hunterlong/statup/plugin"
"github.com/hunterlong/statup/types"
"net/http"
@ -36,7 +37,7 @@ func RunDatabaseUpgrades() {
for _, request := range requests {
_, err := dbSession.Exec(db.Raw(request + ";"))
if err != nil {
fmt.Println(err)
log.Send(2, err)
}
}
fmt.Println("Database Upgraded")
@ -79,6 +80,7 @@ func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) {
}
err := config.Save()
if err != nil {
log.Send(2, err)
config.Error = err
SetupResponseError(w, r, config)
return
@ -86,6 +88,7 @@ func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) {
configs, err = LoadConfig()
if err != nil {
log.Send(2, err)
config.Error = err
SetupResponseError(w, r, config)
return
@ -93,6 +96,7 @@ func ProcessSetupHandler(w http.ResponseWriter, r *http.Request) {
err = DbConnection(configs.Connection)
if err != nil {
log.Send(2, err)
DeleteConfig()
config.Error = err
SetupResponseError(w, r, config)
@ -130,7 +134,7 @@ func InsertDefaultComms() {
func DeleteConfig() {
err := os.Remove("./config.yml")
if err != nil {
throw(err)
log.Send(3, err)
}
}
@ -155,10 +159,12 @@ func (c *DbConfig) Save() error {
var err error
config, err := os.Create("config.yml")
if err != nil {
log.Send(2, err)
return err
}
data, err := yaml.Marshal(c)
if err != nil {
log.Send(2, err)
return err
}
config.WriteString(string(data))
@ -166,10 +172,12 @@ func (c *DbConfig) Save() error {
configs, err = LoadConfig()
if err != nil {
log.Send(2, err)
return err
}
err = DbConnection(configs.Connection)
if err != nil {
log.Send(2, err)
return err
}
DropDatabase()
@ -205,7 +213,7 @@ func DropDatabase() {
for _, request := range requests {
_, err := dbSession.Exec(request)
if err != nil {
fmt.Println(err)
log.Send(2, err)
}
}
}
@ -223,7 +231,7 @@ func CreateDatabase() {
for _, request := range requests {
_, err := dbSession.Exec(request)
if err != nil {
fmt.Println(err)
log.Send(2, err)
}
}
//secret := NewSHA1Hash()

View File

@ -1,6 +1,7 @@
package main
import (
"github.com/hunterlong/statup/log"
"golang.org/x/crypto/bcrypt"
"net/http"
"time"
@ -60,6 +61,7 @@ func (u *User) Create() (int64, error) {
col := dbSession.Collection("users")
uuid, err := col.Insert(u)
if uuid == nil {
log.Send(2, err)
return 0, err
}
OnNewUser(u)
@ -77,6 +79,7 @@ func AuthUser(username, password string) (*User, bool) {
var auth bool
user, err := SelectUsername(username)
if err != nil {
log.Send(2, err)
return nil, false
}
if CheckHash(password, user.Password) {

View File

@ -3,9 +3,9 @@ package main
import (
"bytes"
"fmt"
"github.com/hunterlong/statup/log"
"html/template"
"io/ioutil"
"log"
"strings"
)
@ -32,7 +32,7 @@ func ExportIndexHTML() string {
footer, _ := tmplBox.String("footer.html")
render, err := tmplBox.String("index.html")
if err != nil {
panic(err)
log.Send(3, err)
}
t := template.New("message")
t.Funcs(template.FuncMap{
@ -55,7 +55,7 @@ func ExportIndexHTML() string {
var tpl bytes.Buffer
if err := t.Execute(&tpl, out); err != nil {
log.Println(err)
log.Send(3, err)
}
result := tpl.String()

3
web.go
View File

@ -13,6 +13,7 @@ import (
"strconv"
"strings"
"time"
"github.com/hunterlong/statup/log"
)
var (
@ -134,7 +135,7 @@ func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
}
_, err := user.Create()
if err != nil {
fmt.Println(err)
log.Send(2, err)
}
http.Redirect(w, r, "/users", http.StatusSeeOther)
}