Merge branch 'master' into fix-webhook-apikey

pull/80/head
Hunter Long 2018-10-11 10:27:58 -07:00 committed by GitHub
commit 9dab20e3e9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 175 additions and 329 deletions

View File

@ -30,12 +30,12 @@ import (
"time" "time"
) )
// 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
utils.InitLogs() utils.InitLogs()
source.Assets() source.Assets()
LoadDotEnvs() loadDotEnvs()
switch args[0] { switch args[0] {
case "app": case "app":
@ -55,15 +55,13 @@ func CatchCLI(args []string) error {
return errors.New("end") return errors.New("end")
} }
case "sass": case "sass":
utils.InitLogs()
source.Assets()
err := source.CompileSASS(dir) err := source.CompileSASS(dir)
if err == nil { if err == nil {
return errors.New("end") return errors.New("end")
} }
return err return err
case "update": case "update":
gitCurrent, err := CheckGithubUpdates() gitCurrent, err := checkGithubUpdates()
if err != nil { if err != nil {
return nil return nil
} }
@ -87,7 +85,7 @@ func CatchCLI(args []string) error {
case "export": case "export":
var err error var err error
fmt.Printf("Statup v%v Exporting Static 'index.html' page...\n", VERSION) fmt.Printf("Statup v%v Exporting Static 'index.html' page...\n", VERSION)
core.Configs, err = core.LoadConfig(dir) core.Configs, err = core.LoadConfigFile(dir)
if err != nil { if err != nil {
utils.Log(4, "config.yml file not found") utils.Log(4, "config.yml file not found")
return err return err
@ -126,7 +124,7 @@ func CatchCLI(args []string) error {
// RunOnce will initialize the Statup application and check each service 1 time, will not run HTTP server // RunOnce will initialize the Statup application and check each service 1 time, will not run HTTP server
func RunOnce() { func RunOnce() {
var err error var err error
core.Configs, err = core.LoadConfig(utils.Directory) core.Configs, err = core.LoadConfigFile(utils.Directory)
if err != nil { if err != nil {
utils.Log(4, "config.yml file not found") utils.Log(4, "config.yml file not found")
} }
@ -138,7 +136,7 @@ func RunOnce() {
if err != nil { if err != nil {
fmt.Println("Core database was not found, Statup is not setup yet.") fmt.Println("Core database was not found, Statup is not setup yet.")
} }
core.CoreApp.SelectAllServices() _, err = core.CoreApp.SelectAllServices(true)
if err != nil { if err != nil {
utils.Log(4, err) utils.Log(4, err)
} }
@ -170,156 +168,22 @@ func HelpEcho() {
fmt.Println("Give Statup a Star at https://github.com/hunterlong/statup") fmt.Println("Give Statup a Star at https://github.com/hunterlong/statup")
} }
// func checkGithubUpdates() (githubResponse, error) {
//func TestPlugin(plug types.PluginActions) { var gitResp githubResponse
// defer utils.DeleteFile("./.plugin_test.db")
// source.Assets()
//
// info := plug.GetInfo()
// fmt.Printf("\n" + BRAKER + "\n")
// fmt.Printf(" Plugin Name: %v\n", info.Name)
// fmt.Printf(" Plugin Description: %v\n", info.Description)
// fmt.Printf(" Plugin Routes: %v\n", len(plug.Routes()))
// for k, r := range plug.Routes() {
// fmt.Printf(" - Route %v - (%v) /%v \n", k+1, r.Method, r.URL)
// }
//
// // Function to create a new Core with example services, hits, failures, users, and default communications
// FakeSeed(plug)
//
// fmt.Println("\n" + BRAKER)
// fmt.Println(POINT + "Sending 'OnLoad(sqlbuilder.Database)'")
// core.OnLoad(core.DbSession)
// fmt.Println("\n" + BRAKER)
// fmt.Println(POINT + "Sending 'OnSuccess(Service)'")
// core.OnSuccess(core.SelectService(1))
// fmt.Println("\n" + BRAKER)
// fmt.Println(POINT + "Sending 'OnFailure(Service, FailureData)'")
// fakeFailD := &types.failure{
// Issue: "No issue, just testing this plugin. This would include HTTP failure information though",
// }
// core.OnFailure(core.SelectService(1), fakeFailD)
// fmt.Println("\n" + BRAKER)
// fmt.Println(POINT + "Sending 'OnSettingsSaved(Core)'")
// fmt.Println(BRAKER)
// core.OnSettingsSaved(core.CoreApp.ToCore())
// fmt.Println("\n" + BRAKER)
// fmt.Println(POINT + "Sending 'OnNewService(Service)'")
// core.OnNewService(core.SelectService(2))
// fmt.Println("\n" + BRAKER)
// fmt.Println(POINT + "Sending 'OnNewUser(user)'")
// user, _ := core.SelectUser(1)
// core.OnNewUser(user)
// fmt.Println("\n" + BRAKER)
// fmt.Println(POINT + "Sending 'OnUpdateService(Service)'")
// srv := core.SelectService(2)
// srv.Type = "http"
// srv.Domain = "https://yahoo.com"
// core.OnUpdateService(srv)
// fmt.Println("\n" + BRAKER)
// fmt.Println(POINT + "Sending 'OnDeletedService(Service)'")
// core.OnDeletedService(core.SelectService(1))
// fmt.Println("\n" + BRAKER)
//}
//
//func FakeSeed(plug types.PluginActions) {
// var err error
// core.CoreApp = core.NewCore()
//
// core.CoreApp.AllPlugins = []types.PluginActions{plug}
//
// fmt.Printf("\n" + BRAKER)
//
// fmt.Println("\nCreating a SQLite database for testing, will be deleted automatically...")
// core.DbSession, err = gorm.Open("sqlite", "./.plugin_test.db")
// if err != nil {
// utils.Log(3, err)
// }
//
// fmt.Println("Finished creating Test SQLite database")
// fmt.Println("Inserting example services into test database...")
//
// core.CoreApp.Name = "Plugin Test"
// core.CoreApp.Description = "This is a fake Core for testing your plugin"
// core.CoreApp.Domain = "http://localhost:8080"
// core.CoreApp.ApiSecret = "0x0x0x0x0"
// core.CoreApp.ApiKey = "abcdefg12345"
//
// fakeSrv := &core.Service{Service: &types.Service{
// Name: "Test Plugin Service",
// Domain: "https://google.com",
// Method: "GET",
// }}
// fakeSrv.Create()
//
// fakeSrv2 := &core.Service{Service: &types.Service{
// Name: "Awesome Plugin Service",
// Domain: "https://netflix.com",
// Method: "GET",
// }}
// fakeSrv2.Create()
//
// fakeUser := &types.user{
// Id: 6334,
// Username: "Bulbasaur",
// Password: "$2a$14$NzT/fLdE3f9iB1Eux2C84O6ZoPhI4NfY0Ke32qllCFo8pMTkUPZzy",
// Email: "info@testdomain.com",
// Admin: true,
// CreatedAt: time.Now(),
// }
// fakeUser.Create()
//
// fakeUser = &types.user{
// Id: 6335,
// Username: "Billy",
// Password: "$2a$14$NzT/fLdE3f9iB1Eux2C84O6ZoPhI4NfY0Ke32qllCFo8pMTkUPZzy",
// Email: "info@awesome.com",
// CreatedAt: time.Now(),
// }
// fakeUser.Create()
//
// for i := 0; i <= 50; i++ {
// dd := &types.Hit{
// Latency: rand.Float64(),
// }
// fakeSrv.CreateHit(dd)
//
// dd = &types.Hit{
// Latency: rand.Float64(),
// }
// fakeSrv2.CreateHit(dd)
//
// fail := &types.failure{
// Issue: "This is not an issue, but it would container HTTP response errors.",
// }
// fakeSrv.CreateFailure(fail)
//
// fail = &types.failure{
// Issue: "HTTP Status Code 521 did not match 200",
// }
// fakeSrv.CreateFailure(fail)
// }
//
// fmt.Println("Seeding example data is complete, running Plugin Tests")
//
//}
func CheckGithubUpdates() (GithubResponse, error) {
var gitResp GithubResponse
response, err := http.Get("https://api.github.com/repos/hunterlong/statup/releases/latest") response, err := http.Get("https://api.github.com/repos/hunterlong/statup/releases/latest")
if err != nil { if err != nil {
return GithubResponse{}, err return githubResponse{}, err
} }
defer response.Body.Close() defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body) contents, err := ioutil.ReadAll(response.Body)
if err != nil { if err != nil {
return GithubResponse{}, err return githubResponse{}, err
} }
err = json.Unmarshal(contents, &gitResp) err = json.Unmarshal(contents, &gitResp)
return gitResp, err return gitResp, err
} }
type GithubResponse struct { type githubResponse struct {
URL string `json:"url"` URL string `json:"url"`
AssetsURL string `json:"assets_url"` AssetsURL string `json:"assets_url"`
UploadURL string `json:"upload_url"` UploadURL string `json:"upload_url"`
@ -330,17 +194,17 @@ type GithubResponse struct {
TargetCommitish string `json:"target_commitish"` TargetCommitish string `json:"target_commitish"`
Name string `json:"name"` Name string `json:"name"`
Draft bool `json:"draft"` Draft bool `json:"draft"`
Author GitAuthor `json:"author"` Author gitAuthor `json:"author"`
Prerelease bool `json:"prerelease"` Prerelease bool `json:"prerelease"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
PublishedAt time.Time `json:"published_at"` PublishedAt time.Time `json:"published_at"`
Assets []GitAssets `json:"assets"` Assets []gitAssets `json:"assets"`
TarballURL string `json:"tarball_url"` TarballURL string `json:"tarball_url"`
ZipballURL string `json:"zipball_url"` ZipballURL string `json:"zipball_url"`
Body string `json:"body"` Body string `json:"body"`
} }
type GitAuthor struct { type gitAuthor struct {
Login string `json:"login"` Login string `json:"login"`
ID int `json:"id"` ID int `json:"id"`
NodeID string `json:"node_id"` NodeID string `json:"node_id"`
@ -361,13 +225,13 @@ type GitAuthor struct {
SiteAdmin bool `json:"site_admin"` SiteAdmin bool `json:"site_admin"`
} }
type GitAssets struct { type gitAssets struct {
URL string `json:"url"` URL string `json:"url"`
ID int `json:"id"` ID int `json:"id"`
NodeID string `json:"node_id"` NodeID string `json:"node_id"`
Name string `json:"name"` Name string `json:"name"`
Label string `json:"label"` Label string `json:"label"`
Uploader GitUploader `json:"uploader"` Uploader gitUploader `json:"uploader"`
ContentType string `json:"content_type"` ContentType string `json:"content_type"`
State string `json:"state"` State string `json:"state"`
Size int `json:"size"` Size int `json:"size"`
@ -377,7 +241,7 @@ type GitAssets struct {
BrowserDownloadURL string `json:"browser_download_url"` BrowserDownloadURL string `json:"browser_download_url"`
} }
type GitUploader struct { type gitUploader struct {
Login string `json:"login"` Login string `json:"login"`
ID int `json:"id"` ID int `json:"id"`
NodeID string `json:"node_id"` NodeID string `json:"node_id"`

View File

@ -23,7 +23,7 @@ import (
func TestRunSQLiteApp(t *testing.T) { func TestRunSQLiteApp(t *testing.T) {
t.SkipNow() t.SkipNow()
run := CatchCLI([]string{"app"}) run := catchCLI([]string{"app"})
assert.Nil(t, run) assert.Nil(t, run)
} }
@ -64,46 +64,46 @@ func TestAssetsCommand(t *testing.T) {
} }
func TestVersionCLI(t *testing.T) { func TestVersionCLI(t *testing.T) {
run := CatchCLI([]string{"version"}) run := catchCLI([]string{"version"})
assert.EqualError(t, run, "end") assert.EqualError(t, run, "end")
} }
func TestAssetsCLI(t *testing.T) { func TestAssetsCLI(t *testing.T) {
run := CatchCLI([]string{"assets"}) run := catchCLI([]string{"assets"})
assert.EqualError(t, run, "end") assert.EqualError(t, run, "end")
assert.FileExists(t, dir+"/assets/css/base.css") assert.FileExists(t, dir+"/assets/css/base.css")
assert.FileExists(t, dir+"/assets/scss/base.scss") assert.FileExists(t, dir+"/assets/scss/base.scss")
} }
func TestSassCLI(t *testing.T) { func TestSassCLI(t *testing.T) {
run := CatchCLI([]string{"sass"}) run := catchCLI([]string{"sass"})
assert.EqualError(t, run, "end") assert.EqualError(t, run, "end")
assert.FileExists(t, dir+"/assets/css/base.css") assert.FileExists(t, dir+"/assets/css/base.css")
} }
func TestUpdateCLI(t *testing.T) { func TestUpdateCLI(t *testing.T) {
t.SkipNow() t.SkipNow()
run := CatchCLI([]string{"update"}) run := catchCLI([]string{"update"})
assert.EqualError(t, run, "end") assert.EqualError(t, run, "end")
} }
func TestTestPackageCLI(t *testing.T) { func TestTestPackageCLI(t *testing.T) {
run := CatchCLI([]string{"test", "plugins"}) run := catchCLI([]string{"test", "plugins"})
assert.EqualError(t, run, "end") assert.EqualError(t, run, "end")
} }
func TestHelpCLI(t *testing.T) { func TestHelpCLI(t *testing.T) {
run := CatchCLI([]string{"help"}) run := catchCLI([]string{"help"})
assert.EqualError(t, run, "end") assert.EqualError(t, run, "end")
} }
func TestRunOnceCLI(t *testing.T) { func TestRunOnceCLI(t *testing.T) {
t.SkipNow() t.SkipNow()
run := CatchCLI([]string{"run"}) run := catchCLI([]string{"run"})
assert.Nil(t, run) assert.Nil(t, run)
} }
func TestEnvCLI(t *testing.T) { func TestEnvCLI(t *testing.T) {
run := CatchCLI([]string{"env"}) run := catchCLI([]string{"env"})
assert.Error(t, run) assert.Error(t, run)
} }

View File

@ -57,13 +57,13 @@ func parseFlags() {
func main() { func main() {
var err error var err error
parseFlags() parseFlags()
LoadDotEnvs() loadDotEnvs()
source.Assets() source.Assets()
utils.InitLogs() utils.InitLogs()
args := flag.Args() args := flag.Args()
if len(args) >= 1 { if len(args) >= 1 {
err := CatchCLI(args) err := catchCLI(args)
if err != nil { if err != nil {
if err.Error() == "end" { if err.Error() == "end" {
os.Exit(0) os.Exit(0)
@ -73,7 +73,7 @@ func main() {
} }
} }
utils.Log(1, fmt.Sprintf("Starting Statup v%v", VERSION)) utils.Log(1, fmt.Sprintf("Starting Statup v%v", VERSION))
core.Configs, err = core.LoadConfig(utils.Directory) core.Configs, err = core.LoadConfigFile(utils.Directory)
if err != nil { if err != nil {
utils.Log(3, err) utils.Log(3, err)
core.SetupMode = true core.SetupMode = true
@ -84,8 +84,8 @@ func main() {
mainProcess() mainProcess()
} }
// LoadDotEnvs attempts to load database configs from a '.env' file in root directory // loadDotEnvs attempts to load database configs from a '.env' file in root directory
func LoadDotEnvs() error { func loadDotEnvs() error {
err := godotenv.Load() err := godotenv.Load()
if err == nil { if err == nil {
utils.Log(1, "Environment file '.env' Loaded") utils.Log(1, "Environment file '.env' Loaded")
@ -98,10 +98,6 @@ func LoadDotEnvs() error {
func mainProcess() { func mainProcess() {
dir := utils.Directory dir := utils.Directory
var err error var err error
core.Configs, err = core.LoadConfig(dir)
if err != nil {
utils.Log(4, fmt.Sprintf("could not load config.yml %v", err))
}
err = core.Configs.Connect(false, dir) err = core.Configs.Connect(false, dir)
if err != nil { if err != nil {
utils.Log(4, fmt.Sprintf("could not connect to database: %v", err)) utils.Log(4, fmt.Sprintf("could not connect to database: %v", err))

View File

@ -83,7 +83,6 @@ func TestRunAll(t *testing.T) {
}) })
t.Run(dbt+" Load Configs", func(t *testing.T) { t.Run(dbt+" Load Configs", func(t *testing.T) {
RunLoadConfig(t) RunLoadConfig(t)
t.Log(core.Configs)
}) })
t.Run(dbt+" Connect to Database", func(t *testing.T) { t.Run(dbt+" Connect to Database", func(t *testing.T) {
err := core.Configs.Connect(false, dir) err := core.Configs.Connect(false, dir)
@ -229,28 +228,8 @@ func TestRunAll(t *testing.T) {
func RunSaveConfig(t *testing.T, db string) { func RunSaveConfig(t *testing.T, db string) {
var err error var err error
port := 5432 core.Configs = core.EnvToConfig()
if db == "mysql" { core.Configs.DbConn = db
port = 3306
} else if db == "mssql" {
port = 1433
}
core.Configs = &core.DbConfig{
DbConn: db,
DbHost: os.Getenv("DB_HOST"),
DbUser: os.Getenv("DB_USER"),
DbPass: os.Getenv("DB_PASS"),
DbData: os.Getenv("DB_DATABASE"),
DbPort: port,
Project: "Testing " + db,
Description: "This is a test of Statup.io!",
Domain: "",
Username: "admin",
Password: "admin",
Email: "",
Error: nil,
Location: dir,
}
core.Configs, err = core.Configs.Save() core.Configs, err = core.Configs.Save()
assert.Nil(t, err) assert.Nil(t, err)
} }
@ -274,7 +253,7 @@ func RunInsertSampleData(t *testing.T) {
func RunLoadConfig(t *testing.T) { func RunLoadConfig(t *testing.T) {
var err error var err error
core.Configs, err = core.LoadConfig(dir) core.Configs, err = core.LoadConfigFile(dir)
t.Log(core.Configs) t.Log(core.Configs)
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, core.Configs) assert.NotNil(t, core.Configs)
@ -302,7 +281,7 @@ func RunSelectCoreMYQL(t *testing.T, db string) {
func RunSelectAllMysqlServices(t *testing.T) { func RunSelectAllMysqlServices(t *testing.T) {
var err error var err error
services, err := core.CoreApp.SelectAllServices() services, err := core.CoreApp.SelectAllServices(false)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 15, len(services)) assert.Equal(t, 15, len(services))
} }
@ -374,7 +353,7 @@ func RunUserDelete(t *testing.T) {
func RunSelectAllServices(t *testing.T) { func RunSelectAllServices(t *testing.T) {
var err error var err error
services, err := core.CoreApp.SelectAllServices() services, err := core.CoreApp.SelectAllServices(false)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 15, len(services)) assert.Equal(t, 15, len(services))
for _, s := range services { for _, s := range services {
@ -482,7 +461,7 @@ func RunDeleteService(t *testing.T) {
service := core.SelectService(4) service := core.SelectService(4)
assert.NotNil(t, service) assert.NotNil(t, service)
assert.Equal(t, "JSON API Tester", service.Name) assert.Equal(t, "JSON API Tester", service.Name)
assert.True(t, service.IsRunning()) assert.False(t, service.IsRunning())
err := service.Delete() err := service.Delete()
assert.False(t, service.IsRunning()) assert.False(t, service.IsRunning())
assert.Nil(t, err) assert.Nil(t, err)

View File

@ -30,8 +30,8 @@ type ErrorResponse struct {
Error string Error string
} }
// LoadConfig will attempt to load the 'config.yml' file in a specific directory // LoadConfigFile will attempt to load the 'config.yml' file in a specific directory
func LoadConfig(directory string) (*DbConfig, error) { func LoadConfigFile(directory string) (*DbConfig, error) {
var configs *DbConfig var configs *DbConfig
if os.Getenv("DB_CONN") != "" { if os.Getenv("DB_CONN") != "" {
utils.Log(1, "DB_CONN environment variable was found, waiting for database...") utils.Log(1, "DB_CONN environment variable was found, waiting for database...")
@ -67,72 +67,104 @@ func LoadUsingEnv() (*DbConfig, error) {
if os.Getenv("DB_DATABASE") == "" { if os.Getenv("DB_DATABASE") == "" {
return nil, errors.New("Missing DB_DATABASE environment variable") return nil, errors.New("Missing DB_DATABASE environment variable")
} }
Configs.DbConn = os.Getenv("DB_CONN") Configs = EnvToConfig()
Configs.DbHost = os.Getenv("DB_HOST")
Configs.DbPort = int(utils.StringInt(os.Getenv("DB_PORT")))
Configs.DbUser = os.Getenv("DB_USER")
Configs.DbPass = os.Getenv("DB_PASS")
Configs.DbData = os.Getenv("DB_DATABASE")
CoreApp.DbConnection = os.Getenv("DB_CONN")
CoreApp.Name = os.Getenv("NAME") CoreApp.Name = os.Getenv("NAME")
CoreApp.Domain = os.Getenv("DOMAIN") CoreApp.Domain = os.Getenv("DOMAIN")
CoreApp.DbConnection = Configs.DbConn
if os.Getenv("USE_CDN") == "true" { if os.Getenv("USE_CDN") == "true" {
CoreApp.UseCdn = true CoreApp.UseCdn = true
} }
err := Configs.Connect(true, utils.Directory)
if err != nil {
utils.Log(4, err)
return nil, err
}
Configs.Save()
exists := DbSession.HasTable("core")
if !exists {
utils.Log(1, fmt.Sprintf("Core database does not exist, creating now!"))
Configs.DropDatabase()
Configs.CreateDatabase()
CoreApp, err = Configs.InsertCore()
if err != nil {
utils.Log(3, err)
}
dbConfig := &DbConfig{ admin := ReturnUser(&types.User{
Username: "admin",
Password: "admin",
Email: "info@admin.com",
Admin: true,
})
_, err := admin.Create()
SampleData()
return Configs, err
}
return Configs, nil
}
// DefaultPort accepts a database type and returns its default port
func DefaultPort(db string) int64 {
switch db {
case "mysql":
return 3306
case "postgres":
return 5432
case "mssql":
return 1433
default:
return 0
}
}
// EnvToConfig converts environment variables to a DbConfig variable
func EnvToConfig() *DbConfig {
port := DefaultPort(os.Getenv("DB_PORT"))
name := os.Getenv("NAME")
if name == "" {
name = "Statup"
}
description := os.Getenv("DESCRIPTION")
if description == "" {
description = "Statup Monitoring Sample Data"
}
data := &DbConfig{
DbConn: os.Getenv("DB_CONN"), DbConn: os.Getenv("DB_CONN"),
DbHost: os.Getenv("DB_HOST"), DbHost: os.Getenv("DB_HOST"),
DbUser: os.Getenv("DB_USER"), DbUser: os.Getenv("DB_USER"),
DbPass: os.Getenv("DB_PASS"), DbPass: os.Getenv("DB_PASS"),
DbData: os.Getenv("DB_DATABASE"), DbData: os.Getenv("DB_DATABASE"),
DbPort: 5432, DbPort: port,
Project: "Statup - " + os.Getenv("NAME"), Project: name,
Description: "New Statup Installation", Description: description,
Domain: os.Getenv("DOMAIN"), Domain: os.Getenv("DOMAIN"),
Email: "",
Username: "admin", Username: "admin",
Password: "admin", Password: "admin",
Email: "info@localhost.com", Error: nil,
Location: utils.Directory,
}
return data
} }
err := dbConfig.Connect(true, utils.Directory) // SampleData runs all the sample data for a new Statup installation
if err != nil { func SampleData() error {
utils.Log(4, err) if err := InsertSampleData(); err != nil {
return nil, err return err
} }
if err := InsertSampleHits(); err != nil {
exists := DbSession.HasTable("core") return err
if !exists {
utils.Log(1, fmt.Sprintf("Core database does not exist, creating now!"))
dbConfig.DropDatabase()
dbConfig.CreateDatabase()
CoreApp, err = dbConfig.InsertCore()
if err != nil {
utils.Log(3, err)
} }
return nil
admin := &types.User{
Username: "admin",
Password: "admin",
Email: "info@admin.com",
Admin: true,
}
admin.Create()
InsertSampleData()
return Configs, err
}
return Configs, nil
} }
// DeleteConfig will delete the 'config.yml' file // DeleteConfig will delete the 'config.yml' file
func DeleteConfig() { func DeleteConfig() error {
err := os.Remove(utils.Directory + "/config.yml") err := os.Remove(utils.Directory + "/config.yml")
if err != nil { if err != nil {
utils.Log(3, err) utils.Log(3, err)
return err
} }
return nil
} }

View File

@ -59,15 +59,15 @@ func (c *Core) ToCore() *types.Core {
// InitApp will initialize Statup // InitApp will initialize Statup
func InitApp() { func InitApp() {
SelectCore() SelectCore()
insertNotifierDB() InsertNotifierDB()
CoreApp.SelectAllServices() CoreApp.SelectAllServices(true)
checkServices() checkServices()
CoreApp.Notifications = notifier.Load() CoreApp.Notifications = notifier.Load()
go DatabaseMaintence() go DatabaseMaintence()
} }
// insertNotifierDB inject the Statup database instance to the Notifier package // 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)
if err != nil { if err != nil {

View File

@ -63,7 +63,7 @@ func TestDbConfig_Save(t *testing.T) {
} }
func TestLoadDbConfig(t *testing.T) { func TestLoadDbConfig(t *testing.T) {
Configs, err := LoadConfig(dir) Configs, err := LoadConfigFile(dir)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "sqlite", Configs.DbConn) assert.Equal(t, "sqlite", Configs.DbConn)
} }
@ -118,7 +118,7 @@ func TestInsertNotifierDB(t *testing.T) {
if skipNewDb { if skipNewDb {
t.SkipNow() t.SkipNow()
} }
err := insertNotifierDB() err := InsertNotifierDB()
assert.Nil(t, err) assert.Nil(t, err)
} }

View File

@ -193,47 +193,41 @@ func (db *DbConfig) InsertCore() (*Core, error) {
// Connect will attempt to connect to the sqlite, postgres, or mysql database // Connect will attempt to connect to the sqlite, postgres, or mysql database
func (db *DbConfig) Connect(retry bool, location string) error { func (db *DbConfig) Connect(retry bool, location string) error {
var err error
if DbSession != nil { if DbSession != nil {
DbSession = nil return nil
} }
var conn, dbType string var conn, dbType string
var err error
dbType = Configs.DbConn dbType = Configs.DbConn
if Configs.DbPort == 0 {
Configs.DbPort = DefaultPort(dbType)
}
switch dbType { switch dbType {
case "sqlite": case "sqlite":
conn = utils.Directory + "/statup.db" conn = location + "/statup.db"
dbType = "sqlite3" dbType = "sqlite3"
case "mysql": case "mysql":
if Configs.DbPort == 0 {
Configs.DbPort = 3306
}
host := fmt.Sprintf("%v:%v", Configs.DbHost, Configs.DbPort) host := fmt.Sprintf("%v:%v", Configs.DbHost, Configs.DbPort)
conn = fmt.Sprintf("%v:%v@tcp(%v)/%v?charset=utf8&parseTime=True&loc=UTC", Configs.DbUser, Configs.DbPass, host, Configs.DbData) conn = fmt.Sprintf("%v:%v@tcp(%v)/%v?charset=utf8&parseTime=True&loc=UTC", Configs.DbUser, Configs.DbPass, host, Configs.DbData)
case "postgres": case "postgres":
if Configs.DbPort == 0 {
Configs.DbPort = 5432
}
conn = fmt.Sprintf("host=%v port=%v user=%v dbname=%v password=%v sslmode=disable", Configs.DbHost, Configs.DbPort, Configs.DbUser, Configs.DbData, Configs.DbPass) conn = fmt.Sprintf("host=%v port=%v user=%v dbname=%v password=%v sslmode=disable", Configs.DbHost, Configs.DbPort, Configs.DbUser, Configs.DbData, Configs.DbPass)
case "mssql": case "mssql":
if Configs.DbPort == 0 {
Configs.DbPort = 1433
}
host := fmt.Sprintf("%v:%v", Configs.DbHost, Configs.DbPort) host := fmt.Sprintf("%v:%v", Configs.DbHost, Configs.DbPort)
conn = fmt.Sprintf("sqlserver://%v:%v@%v?database=%v", Configs.DbUser, Configs.DbPass, host, Configs.DbData) conn = fmt.Sprintf("sqlserver://%v:%v@%v?database=%v", Configs.DbUser, Configs.DbPass, host, Configs.DbData)
} }
DbSession, err = gorm.Open(dbType, conn) dbSession, err := gorm.Open(dbType, conn)
if err != nil { if err != nil {
if retry { if retry {
utils.Log(1, fmt.Sprintf("Database connection to '%v' is not available, trying again in 5 seconds...", conn)) utils.Log(1, fmt.Sprintf("Database connection to '%v' is not available, trying again in 5 seconds...", conn))
return db.waitForDb() return db.waitForDb()
} else { } else {
fmt.Println("ERROR:", err)
return err return err
} }
} }
err = DbSession.DB().Ping() err = dbSession.DB().Ping()
if err == nil { if err == nil {
utils.Log(1, fmt.Sprintf("Database connection to '%v' was successful.", Configs.DbData)) DbSession = dbSession
utils.Log(1, fmt.Sprintf("Database %v connection '%v@%v' at %v was successful.", dbType, Configs.DbUser, Configs.DbHost, Configs.DbData))
} }
return err return err
} }
@ -358,7 +352,6 @@ func (db *DbConfig) CreateDatabase() error {
// If this function has an issue, it will ROLLBACK to the previous state. // If this function has an issue, it will ROLLBACK to the previous state.
func (db *DbConfig) MigrateDatabase() error { func (db *DbConfig) MigrateDatabase() error {
utils.Log(1, "Migrating Database Tables...") utils.Log(1, "Migrating Database Tables...")
tx := DbSession.Begin() tx := DbSession.Begin()
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {

View File

@ -31,7 +31,7 @@ func injectDatabase() {
func ExportIndexHTML() string { func ExportIndexHTML() string {
source.Assets() source.Assets()
injectDatabase() injectDatabase()
CoreApp.SelectAllServices() CoreApp.SelectAllServices(false)
CoreApp.UseCdn = true CoreApp.UseCdn = true
for _, srv := range CoreApp.Services { for _, srv := range CoreApp.Services {
service := srv.(*Service) service := srv.(*Service)

View File

@ -41,6 +41,10 @@ func ReturnService(s *types.Service) *Service {
return &Service{s} return &Service{s}
} }
func Services() []types.ServiceInterface {
return CoreApp.Services
}
// SelectService returns a *core.Service from in memory // SelectService returns a *core.Service from in memory
func SelectService(id int64) *Service { func SelectService(id int64) *Service {
for _, s := range CoreApp.Services { for _, s := range CoreApp.Services {
@ -75,7 +79,7 @@ func (s *Service) LimitedCheckins() []*Checkin {
} }
// SelectAllServices returns a slice of *core.Service to be store on []*core.Services, should only be called once on startup. // SelectAllServices returns a slice of *core.Service to be store on []*core.Services, should only be called once on startup.
func (c *Core) SelectAllServices() ([]*Service, error) { func (c *Core) SelectAllServices(start bool) ([]*Service, error) {
var services []*Service var services []*Service
db := servicesDB().Find(&services).Order("order_id desc") db := servicesDB().Find(&services).Order("order_id desc")
if db.Error != nil { if db.Error != nil {
@ -84,8 +88,10 @@ func (c *Core) SelectAllServices() ([]*Service, error) {
} }
CoreApp.Services = nil CoreApp.Services = nil
for _, service := range services { for _, service := range services {
if start {
service.Start() service.Start()
service.CheckinProcess() service.CheckinProcess()
}
service.AllFailures() service.AllFailures()
CoreApp.Services = append(CoreApp.Services, service) CoreApp.Services = append(CoreApp.Services, service)
} }

View File

@ -27,7 +27,7 @@ var (
) )
func TestSelectHTTPService(t *testing.T) { func TestSelectHTTPService(t *testing.T) {
services, err := CoreApp.SelectAllServices() services, err := CoreApp.SelectAllServices(false)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 15, len(services)) assert.Equal(t, 15, len(services))
assert.Equal(t, "Google", services[0].Name) assert.Equal(t, "Google", services[0].Name)
@ -39,7 +39,7 @@ func TestSelectAllServices(t *testing.T) {
for _, s := range services { for _, s := range services {
service := s.(*Service) service := s.(*Service)
service.Check(false) service.Check(false)
assert.True(t, service.IsRunning()) assert.False(t, service.IsRunning())
t.Logf("ID: %v %v\n", service.Id, service.Name) t.Logf("ID: %v %v\n", service.Id, service.Name)
} }
assert.Equal(t, 15, len(services)) assert.Equal(t, 15, len(services))
@ -77,7 +77,7 @@ func TestUpdateService(t *testing.T) {
} }
func TestUpdateAllServices(t *testing.T) { func TestUpdateAllServices(t *testing.T) {
services, err := CoreApp.SelectAllServices() services, err := CoreApp.SelectAllServices(false)
assert.Nil(t, err) assert.Nil(t, err)
for k, srv := range services { for k, srv := range services {
srv.Name = "Changed " + srv.Name srv.Name = "Changed " + srv.Name
@ -268,7 +268,7 @@ func TestCreateServiceFailure(t *testing.T) {
func TestDeleteService(t *testing.T) { func TestDeleteService(t *testing.T) {
service := SelectService(newServiceId) service := SelectService(newServiceId)
count, err := CoreApp.SelectAllServices() count, err := CoreApp.SelectAllServices(false)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 18, len(count)) assert.Equal(t, 18, len(count))

View File

@ -39,7 +39,7 @@ func DesktopInit(ip string, port int) {
var err error var err error
exists := utils.FileExists(utils.Directory + "/statup.db") exists := utils.FileExists(utils.Directory + "/statup.db")
if exists { if exists {
core.Configs, err = core.LoadConfig(utils.Directory) core.Configs, err = core.LoadConfigFile(utils.Directory)
if err != nil { if err != nil {
utils.Log(3, err) utils.Log(3, err)
return return
@ -79,7 +79,7 @@ func DesktopInit(ip string, port int) {
return return
} }
core.Configs, err = core.LoadConfig(utils.Directory) core.Configs, err = core.LoadConfigFile(utils.Directory)
if err != nil { if err != nil {
utils.Log(3, err) utils.Log(3, err)
config.Error = err config.Error = err

View File

@ -45,13 +45,13 @@ func init() {
func loadDatabase() { func loadDatabase() {
core.NewCore() core.NewCore()
core.LoadConfig(dir) core.LoadConfigFile(dir)
core.Configs = &core.DbConfig{ core.Configs = &core.DbConfig{
DbConn: "sqlite", DbConn: "sqlite",
Location: dir, Location: dir,
} }
core.Configs.Connect(false, utils.Directory)
core.CoreApp.DbConnection = "sqlite" core.CoreApp.DbConnection = "sqlite"
core.Configs.Connect(false, utils.Directory)
core.CoreApp.Version = "DEV" core.CoreApp.Version = "DEV"
core.Configs.Save() core.Configs.Save()
} }
@ -75,11 +75,14 @@ func Clean() {
} }
func TestInit(t *testing.T) { func TestInit(t *testing.T) {
Clean() //Clean()
loadDatabase() //loadDatabase()
resetDatabase() //resetDatabase()
loadDatabase() //loadDatabase()
core.InitApp() //core.SelectCore()
//core.InsertNotifierDB()
//core.CoreApp.SelectAllServices(false)
//core.CoreApp.Notifications = notifier.Load()
} }
func formatJSON(res string, out interface{}) { func formatJSON(res string, out interface{}) {
@ -93,7 +96,7 @@ func TestApiIndexHandler(t *testing.T) {
var obj types.Core var obj types.Core
formatJSON(body, &obj) formatJSON(body, &obj)
assert.Equal(t, 200, rr.Code) assert.Equal(t, 200, rr.Code)
assert.Equal(t, "Statup Sample Data", obj.Name) assert.Equal(t, "Awesome Status", obj.Name)
assert.Equal(t, "sqlite", obj.DbConnection) assert.Equal(t, "sqlite", obj.DbConnection)
} }
@ -104,8 +107,8 @@ func TestApiAllServicesHandlerHandler(t *testing.T) {
var obj []types.Service var obj []types.Service
formatJSON(body, &obj) formatJSON(body, &obj)
assert.Equal(t, 200, rr.Code) assert.Equal(t, 200, rr.Code)
assert.Equal(t, "Google", obj[0].Name) assert.Equal(t, "Test Service 9", obj[0].Name)
assert.Equal(t, "https://google.com", obj[0].Domain) assert.Equal(t, "https://www.youtube.com/watch?v=yydZbVoCbn0&t=870s", obj[0].Domain)
} }
func TestApiServiceHandler(t *testing.T) { func TestApiServiceHandler(t *testing.T) {
@ -174,7 +177,7 @@ func TestApiAllUsersHandler(t *testing.T) {
var obj []types.User var obj []types.User
formatJSON(body, &obj) formatJSON(body, &obj)
assert.Equal(t, true, obj[0].Admin) assert.Equal(t, true, obj[0].Admin)
assert.Equal(t, "testadmin", obj[0].Username) assert.Equal(t, "admin", obj[0].Username)
} }
func TestApiCreateUserHandler(t *testing.T) { func TestApiCreateUserHandler(t *testing.T) {
@ -194,13 +197,13 @@ func TestApiCreateUserHandler(t *testing.T) {
} }
func TestApiViewUserHandler(t *testing.T) { func TestApiViewUserHandler(t *testing.T) {
rr, err := httpRequestAPI(t, "GET", "/api/users/2", nil) rr, err := httpRequestAPI(t, "GET", "/api/users/1", nil)
assert.Nil(t, err) assert.Nil(t, err)
body := rr.Body.String() body := rr.Body.String()
assert.Equal(t, 200, rr.Code) assert.Equal(t, 200, rr.Code)
var obj types.User var obj types.User
formatJSON(body, &obj) formatJSON(body, &obj)
assert.Equal(t, "testadmin2", obj.Username) assert.Equal(t, "admin", obj.Username)
assert.Equal(t, true, obj.Admin) assert.Equal(t, true, obj.Admin)
} }

View File

@ -21,7 +21,6 @@ import (
"github.com/hunterlong/statup/utils" "github.com/hunterlong/statup/utils"
"net/http" "net/http"
"os" "os"
"strconv"
"time" "time"
) )
@ -31,32 +30,16 @@ func setupHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
port := 5432
if os.Getenv("DB_CONN") == "mysql" {
port = 3306
}
var data interface{} var data interface{}
if os.Getenv("DB_CONN") != "" { if os.Getenv("DB_CONN") != "" {
data = &types.DbConfig{ data, _ = core.LoadUsingEnv()
DbConn: os.Getenv("DB_CONN"),
DbHost: os.Getenv("DB_HOST"),
DbUser: os.Getenv("DB_USER"),
DbPass: os.Getenv("DB_PASS"),
DbData: os.Getenv("DB_DATABASE"),
DbPort: port,
Project: os.Getenv("NAME"),
Description: os.Getenv("DESCRIPTION"),
Email: "",
Username: "admin",
Password: "",
}
} }
executeResponse(w, r, "setup.html", data, nil) executeResponse(w, r, "setup.html", data, nil)
} }
func processSetupHandler(w http.ResponseWriter, r *http.Request) { func processSetupHandler(w http.ResponseWriter, r *http.Request) {
var err error var err error
if core.CoreApp.Services != nil { if core.Services() != nil {
http.Redirect(w, r, "/", http.StatusSeeOther) http.Redirect(w, r, "/", http.StatusSeeOther)
return return
} }
@ -66,15 +49,14 @@ func processSetupHandler(w http.ResponseWriter, r *http.Request) {
dbPass := r.PostForm.Get("db_password") dbPass := r.PostForm.Get("db_password")
dbDatabase := r.PostForm.Get("db_database") dbDatabase := r.PostForm.Get("db_database")
dbConn := r.PostForm.Get("db_connection") dbConn := r.PostForm.Get("db_connection")
dbPort, _ := strconv.Atoi(r.PostForm.Get("db_port")) dbPort := utils.StringInt(r.PostForm.Get("db_port"))
project := r.PostForm.Get("project") project := r.PostForm.Get("project")
username := r.PostForm.Get("username") username := r.PostForm.Get("username")
password := r.PostForm.Get("password") password := r.PostForm.Get("password")
sample := r.PostForm.Get("sample_data") //sample := r.PostForm.Get("sample_data")
description := r.PostForm.Get("description") description := r.PostForm.Get("description")
domain := r.PostForm.Get("domain") domain := r.PostForm.Get("domain")
email := r.PostForm.Get("email") email := r.PostForm.Get("email")
dir := utils.Directory dir := utils.Directory
config := &core.DbConfig{ config := &core.DbConfig{
@ -94,24 +76,21 @@ func processSetupHandler(w http.ResponseWriter, r *http.Request) {
Location: utils.Directory, Location: utils.Directory,
} }
core.Configs, err = config.Save() if core.Configs, err = config.Save(); err != nil {
if err != nil {
utils.Log(4, err) utils.Log(4, err)
config.Error = err config.Error = err
setupResponseError(w, r, config) setupResponseError(w, r, config)
return return
} }
core.Configs, err = core.LoadConfig(dir) if core.Configs, err = core.LoadConfigFile(dir); err != nil {
if err != nil {
utils.Log(3, err) utils.Log(3, err)
config.Error = err config.Error = err
setupResponseError(w, r, config) setupResponseError(w, r, config)
return return
} }
err = core.Configs.Connect(false, dir) if err = core.Configs.Connect(false, dir); err != nil {
if err != nil {
utils.Log(4, err) utils.Log(4, err)
core.DeleteConfig() core.DeleteConfig()
config.Error = err config.Error = err
@ -138,11 +117,7 @@ func processSetupHandler(w http.ResponseWriter, r *http.Request) {
}) })
admin.Create() admin.Create()
if sample == "on" { core.SampleData()
core.InsertSampleData()
core.InsertSampleHits()
}
core.InitApp() core.InitApp()
resetCookies() resetCookies()
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)

View File

@ -78,11 +78,10 @@ func LoadPlugin(file string) error {
utils.Log(3, fmt.Sprintf("Plugin '%v' could not locate Plugin variable. %v", fileBin, err)) utils.Log(3, fmt.Sprintf("Plugin '%v' could not locate Plugin variable. %v", fileBin, err))
return err return err
} }
var plugActions types.PluginActions
plugActions, ok := symPlugin.(types.PluginActions) plugActions, ok := symPlugin.(types.PluginActions)
if !ok { if !ok {
utils.Log(3, fmt.Sprintf("Plugin %v was not type PluginObject", f.Name())) utils.Log(3, fmt.Sprintf("Plugin %v was not type PluginObject", f.Name()))
return fmt.Errorf("Plugin %v was not type PluginActions, %v", f.Name(), plugActions.GetInfo()) return fmt.Errorf("Plugin %v was not type PluginActions %v", f.Name(), plugActions.GetInfo())
} }
info := plugActions.GetInfo() info := plugActions.GetInfo()
err = plugActions.OnLoad() err = plugActions.OnLoad()
@ -102,7 +101,7 @@ func LoadPlugins() {
} }
files, err := ioutil.ReadDir(pluginDir) files, err := ioutil.ReadDir(pluginDir)
if err != nil { if err != nil {
utils.Log(2, fmt.Sprintf("Plugins directory was not found. Error: %v\n", err)) utils.Log(2, fmt.Sprintf("Plugins directory was not found. Error: %v", err))
return return
} }
for _, f := range files { for _, f := range files {
@ -112,5 +111,5 @@ func LoadPlugins() {
continue continue
} }
} }
utils.Log(1, fmt.Sprintf("Loaded %v Plugins\n", len(core.CoreApp.Plugins))) utils.Log(1, fmt.Sprintf("Loaded %v Plugins", len(core.CoreApp.Plugins)))
} }

View File

@ -35,7 +35,7 @@ type DbConfig struct {
DbUser string `yaml:"user"` DbUser string `yaml:"user"`
DbPass string `yaml:"password"` DbPass string `yaml:"password"`
DbData string `yaml:"database"` DbData string `yaml:"database"`
DbPort int `yaml:"port"` DbPort int64 `yaml:"port"`
ApiKey string `yaml:"api_key"` ApiKey string `yaml:"api_key"`
ApiSecret string `yaml:"api_secret"` ApiSecret string `yaml:"api_secret"`
Project string `yaml:"-"` Project string `yaml:"-"`

View File

@ -125,7 +125,6 @@ func Log(level int, err interface{}) error {
// Http returns a log for a HTTP request // Http returns a log for a HTTP request
func Http(r *http.Request) string { func Http(r *http.Request) string {
msg := fmt.Sprintf("%v (%v) | IP: %v", r.RequestURI, r.Method, r.Host) msg := fmt.Sprintf("%v (%v) | IP: %v", r.RequestURI, r.Method, r.Host)
fmtLogs.Printf("WEB: %v\n", msg)
fmt.Printf("WEB: %v\n", msg) fmt.Printf("WEB: %v\n", msg)
pushLastLine(msg) pushLastLine(msg)
return msg return msg