From b54514327780484f1ac89d62208d2e98dc917732 Mon Sep 17 00:00:00 2001 From: hunterlong Date: Thu, 11 Oct 2018 09:53:13 -0700 Subject: [PATCH] removed exports - cleaned - tests --- cmd/cli.go | 172 ++---------------- cmd/cli_test.go | 18 +- cmd/main.go | 14 +- cmd/main_test.go | 33 +--- core/configs.go | 122 ++++++++----- core/core.go | 8 +- core/core_test.go | 4 +- core/database.go | 27 +-- core/export.go | 2 +- core/services.go | 12 +- core/services_test.go | 8 +- handlers/index.go | 4 +- ...api_handlers_test.go => route_api_test.go} | 29 +-- handlers/setup.go | 41 +---- plugin/plugin.go | 7 +- types/types.go | 2 +- utils/log.go | 1 - 17 files changed, 175 insertions(+), 329 deletions(-) rename handlers/{api_handlers_test.go => route_api_test.go} (93%) diff --git a/cmd/cli.go b/cmd/cli.go index 6d60b02f..c8e0e1bf 100644 --- a/cmd/cli.go +++ b/cmd/cli.go @@ -30,12 +30,12 @@ import ( "time" ) -// CatchCLI will run functions based on the commands sent to Statup -func CatchCLI(args []string) error { +// catchCLI will run functions based on the commands sent to Statup +func catchCLI(args []string) error { dir := utils.Directory utils.InitLogs() source.Assets() - LoadDotEnvs() + loadDotEnvs() switch args[0] { case "app": @@ -55,15 +55,13 @@ func CatchCLI(args []string) error { return errors.New("end") } case "sass": - utils.InitLogs() - source.Assets() err := source.CompileSASS(dir) if err == nil { return errors.New("end") } return err case "update": - gitCurrent, err := CheckGithubUpdates() + gitCurrent, err := checkGithubUpdates() if err != nil { return nil } @@ -87,7 +85,7 @@ func CatchCLI(args []string) error { case "export": var err error 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 { utils.Log(4, "config.yml file not found") 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 func RunOnce() { var err error - core.Configs, err = core.LoadConfig(utils.Directory) + core.Configs, err = core.LoadConfigFile(utils.Directory) if err != nil { utils.Log(4, "config.yml file not found") } @@ -138,7 +136,7 @@ func RunOnce() { if err != nil { fmt.Println("Core database was not found, Statup is not setup yet.") } - core.CoreApp.SelectAllServices() + _, err = core.CoreApp.SelectAllServices(true) if err != nil { utils.Log(4, err) } @@ -170,156 +168,22 @@ func HelpEcho() { fmt.Println("Give Statup a Star at https://github.com/hunterlong/statup") } -// -//func TestPlugin(plug types.PluginActions) { -// 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 +func checkGithubUpdates() (githubResponse, error) { + var gitResp githubResponse response, err := http.Get("https://api.github.com/repos/hunterlong/statup/releases/latest") if err != nil { - return GithubResponse{}, err + return githubResponse{}, err } defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) if err != nil { - return GithubResponse{}, err + return githubResponse{}, err } err = json.Unmarshal(contents, &gitResp) return gitResp, err } -type GithubResponse struct { +type githubResponse struct { URL string `json:"url"` AssetsURL string `json:"assets_url"` UploadURL string `json:"upload_url"` @@ -330,17 +194,17 @@ type GithubResponse struct { TargetCommitish string `json:"target_commitish"` Name string `json:"name"` Draft bool `json:"draft"` - Author GitAuthor `json:"author"` + Author gitAuthor `json:"author"` Prerelease bool `json:"prerelease"` CreatedAt time.Time `json:"created_at"` PublishedAt time.Time `json:"published_at"` - Assets []GitAssets `json:"assets"` + Assets []gitAssets `json:"assets"` TarballURL string `json:"tarball_url"` ZipballURL string `json:"zipball_url"` Body string `json:"body"` } -type GitAuthor struct { +type gitAuthor struct { Login string `json:"login"` ID int `json:"id"` NodeID string `json:"node_id"` @@ -361,13 +225,13 @@ type GitAuthor struct { SiteAdmin bool `json:"site_admin"` } -type GitAssets struct { +type gitAssets struct { URL string `json:"url"` ID int `json:"id"` NodeID string `json:"node_id"` Name string `json:"name"` Label string `json:"label"` - Uploader GitUploader `json:"uploader"` + Uploader gitUploader `json:"uploader"` ContentType string `json:"content_type"` State string `json:"state"` Size int `json:"size"` @@ -377,7 +241,7 @@ type GitAssets struct { BrowserDownloadURL string `json:"browser_download_url"` } -type GitUploader struct { +type gitUploader struct { Login string `json:"login"` ID int `json:"id"` NodeID string `json:"node_id"` diff --git a/cmd/cli_test.go b/cmd/cli_test.go index c470c5bc..5f25209f 100644 --- a/cmd/cli_test.go +++ b/cmd/cli_test.go @@ -23,7 +23,7 @@ import ( func TestRunSQLiteApp(t *testing.T) { t.SkipNow() - run := CatchCLI([]string{"app"}) + run := catchCLI([]string{"app"}) assert.Nil(t, run) } @@ -64,46 +64,46 @@ func TestAssetsCommand(t *testing.T) { } func TestVersionCLI(t *testing.T) { - run := CatchCLI([]string{"version"}) + run := catchCLI([]string{"version"}) assert.EqualError(t, run, "end") } func TestAssetsCLI(t *testing.T) { - run := CatchCLI([]string{"assets"}) + run := catchCLI([]string{"assets"}) assert.EqualError(t, run, "end") assert.FileExists(t, dir+"/assets/css/base.css") assert.FileExists(t, dir+"/assets/scss/base.scss") } func TestSassCLI(t *testing.T) { - run := CatchCLI([]string{"sass"}) + run := catchCLI([]string{"sass"}) assert.EqualError(t, run, "end") assert.FileExists(t, dir+"/assets/css/base.css") } func TestUpdateCLI(t *testing.T) { t.SkipNow() - run := CatchCLI([]string{"update"}) + run := catchCLI([]string{"update"}) assert.EqualError(t, run, "end") } func TestTestPackageCLI(t *testing.T) { - run := CatchCLI([]string{"test", "plugins"}) + run := catchCLI([]string{"test", "plugins"}) assert.EqualError(t, run, "end") } func TestHelpCLI(t *testing.T) { - run := CatchCLI([]string{"help"}) + run := catchCLI([]string{"help"}) assert.EqualError(t, run, "end") } func TestRunOnceCLI(t *testing.T) { t.SkipNow() - run := CatchCLI([]string{"run"}) + run := catchCLI([]string{"run"}) assert.Nil(t, run) } func TestEnvCLI(t *testing.T) { - run := CatchCLI([]string{"env"}) + run := catchCLI([]string{"env"}) assert.Error(t, run) } diff --git a/cmd/main.go b/cmd/main.go index c7945e05..a95ffde1 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -57,13 +57,13 @@ func parseFlags() { func main() { var err error parseFlags() - LoadDotEnvs() + loadDotEnvs() source.Assets() utils.InitLogs() args := flag.Args() if len(args) >= 1 { - err := CatchCLI(args) + err := catchCLI(args) if err != nil { if err.Error() == "end" { os.Exit(0) @@ -73,7 +73,7 @@ func main() { } } 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 { utils.Log(3, err) core.SetupMode = true @@ -84,8 +84,8 @@ func main() { mainProcess() } -// LoadDotEnvs attempts to load database configs from a '.env' file in root directory -func LoadDotEnvs() error { +// loadDotEnvs attempts to load database configs from a '.env' file in root directory +func loadDotEnvs() error { err := godotenv.Load() if err == nil { utils.Log(1, "Environment file '.env' Loaded") @@ -98,10 +98,6 @@ func LoadDotEnvs() error { func mainProcess() { dir := utils.Directory 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) if err != nil { utils.Log(4, fmt.Sprintf("could not connect to database: %v", err)) diff --git a/cmd/main_test.go b/cmd/main_test.go index 487c40ce..6cd36bef 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -83,7 +83,6 @@ func TestRunAll(t *testing.T) { }) t.Run(dbt+" Load Configs", func(t *testing.T) { RunLoadConfig(t) - t.Log(core.Configs) }) t.Run(dbt+" Connect to Database", func(t *testing.T) { err := core.Configs.Connect(false, dir) @@ -229,28 +228,8 @@ func TestRunAll(t *testing.T) { func RunSaveConfig(t *testing.T, db string) { var err error - port := 5432 - if db == "mysql" { - 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 = core.EnvToConfig() + core.Configs.DbConn = db core.Configs, err = core.Configs.Save() assert.Nil(t, err) } @@ -274,7 +253,7 @@ func RunInsertSampleData(t *testing.T) { func RunLoadConfig(t *testing.T) { var err error - core.Configs, err = core.LoadConfig(dir) + core.Configs, err = core.LoadConfigFile(dir) t.Log(core.Configs) assert.Nil(t, err) assert.NotNil(t, core.Configs) @@ -302,7 +281,7 @@ func RunSelectCoreMYQL(t *testing.T, db string) { func RunSelectAllMysqlServices(t *testing.T) { var err error - services, err := core.CoreApp.SelectAllServices() + services, err := core.CoreApp.SelectAllServices(false) assert.Nil(t, err) assert.Equal(t, 15, len(services)) } @@ -374,7 +353,7 @@ func RunUserDelete(t *testing.T) { func RunSelectAllServices(t *testing.T) { var err error - services, err := core.CoreApp.SelectAllServices() + services, err := core.CoreApp.SelectAllServices(false) assert.Nil(t, err) assert.Equal(t, 15, len(services)) for _, s := range services { @@ -482,7 +461,7 @@ func RunDeleteService(t *testing.T) { service := core.SelectService(4) assert.NotNil(t, service) assert.Equal(t, "JSON API Tester", service.Name) - assert.True(t, service.IsRunning()) + assert.False(t, service.IsRunning()) err := service.Delete() assert.False(t, service.IsRunning()) assert.Nil(t, err) diff --git a/core/configs.go b/core/configs.go index e987c6a5..d5db8368 100644 --- a/core/configs.go +++ b/core/configs.go @@ -30,8 +30,8 @@ type ErrorResponse struct { Error string } -// LoadConfig will attempt to load the 'config.yml' file in a specific directory -func LoadConfig(directory string) (*DbConfig, error) { +// LoadConfigFile will attempt to load the 'config.yml' file in a specific directory +func LoadConfigFile(directory string) (*DbConfig, error) { var configs *DbConfig if os.Getenv("DB_CONN") != "" { 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") == "" { return nil, errors.New("Missing DB_DATABASE environment variable") } - Configs.DbConn = os.Getenv("DB_CONN") - 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") + Configs = EnvToConfig() CoreApp.Name = os.Getenv("NAME") CoreApp.Domain = os.Getenv("DOMAIN") + CoreApp.DbConnection = Configs.DbConn if os.Getenv("USE_CDN") == "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"), DbHost: os.Getenv("DB_HOST"), DbUser: os.Getenv("DB_USER"), DbPass: os.Getenv("DB_PASS"), DbData: os.Getenv("DB_DATABASE"), - DbPort: 5432, - Project: "Statup - " + os.Getenv("NAME"), - Description: "New Statup Installation", + DbPort: port, + Project: name, + Description: description, Domain: os.Getenv("DOMAIN"), + Email: "", Username: "admin", Password: "admin", - Email: "info@localhost.com", + Error: nil, + Location: utils.Directory, } + return data +} - err := dbConfig.Connect(true, utils.Directory) - if err != nil { - utils.Log(4, err) - return nil, err +// SampleData runs all the sample data for a new Statup installation +func SampleData() error { + if err := InsertSampleData(); err != nil { + return err } - - exists := DbSession.HasTable("core") - 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) - } - - admin := &types.User{ - Username: "admin", - Password: "admin", - Email: "info@admin.com", - Admin: true, - } - admin.Create() - - InsertSampleData() - - return Configs, err - + if err := InsertSampleHits(); err != nil { + return err } - - return Configs, nil + return nil } // DeleteConfig will delete the 'config.yml' file -func DeleteConfig() { +func DeleteConfig() error { err := os.Remove(utils.Directory + "/config.yml") if err != nil { utils.Log(3, err) + return err } + return nil } diff --git a/core/core.go b/core/core.go index b14da95e..2a6908f9 100644 --- a/core/core.go +++ b/core/core.go @@ -59,15 +59,15 @@ func (c *Core) ToCore() *types.Core { // InitApp will initialize Statup func InitApp() { SelectCore() - insertNotifierDB() - CoreApp.SelectAllServices() + InsertNotifierDB() + CoreApp.SelectAllServices(true) checkServices() CoreApp.Notifications = notifier.Load() go DatabaseMaintence() } -// insertNotifierDB inject the Statup database instance to the Notifier package -func insertNotifierDB() error { +// InsertNotifierDB inject the Statup database instance to the Notifier package +func InsertNotifierDB() error { if DbSession == nil { err := Configs.Connect(false, utils.Directory) if err != nil { diff --git a/core/core_test.go b/core/core_test.go index d0832c78..1388f0b6 100644 --- a/core/core_test.go +++ b/core/core_test.go @@ -63,7 +63,7 @@ func TestDbConfig_Save(t *testing.T) { } func TestLoadDbConfig(t *testing.T) { - Configs, err := LoadConfig(dir) + Configs, err := LoadConfigFile(dir) assert.Nil(t, err) assert.Equal(t, "sqlite", Configs.DbConn) } @@ -118,7 +118,7 @@ func TestInsertNotifierDB(t *testing.T) { if skipNewDb { t.SkipNow() } - err := insertNotifierDB() + err := InsertNotifierDB() assert.Nil(t, err) } diff --git a/core/database.go b/core/database.go index d8688265..3c9a1669 100644 --- a/core/database.go +++ b/core/database.go @@ -193,47 +193,41 @@ func (db *DbConfig) InsertCore() (*Core, error) { // Connect will attempt to connect to the sqlite, postgres, or mysql database func (db *DbConfig) Connect(retry bool, location string) error { - var err error if DbSession != nil { - DbSession = nil + return nil } var conn, dbType string + var err error dbType = Configs.DbConn + if Configs.DbPort == 0 { + Configs.DbPort = DefaultPort(dbType) + } switch dbType { case "sqlite": - conn = utils.Directory + "/statup.db" + conn = location + "/statup.db" dbType = "sqlite3" case "mysql": - if Configs.DbPort == 0 { - Configs.DbPort = 3306 - } 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) 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) case "mssql": - if Configs.DbPort == 0 { - Configs.DbPort = 1433 - } 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) } - DbSession, err = gorm.Open(dbType, conn) + dbSession, err := gorm.Open(dbType, conn) if err != nil { if retry { utils.Log(1, fmt.Sprintf("Database connection to '%v' is not available, trying again in 5 seconds...", conn)) return db.waitForDb() } else { - fmt.Println("ERROR:", err) return err } } - err = DbSession.DB().Ping() + err = dbSession.DB().Ping() 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 } @@ -358,7 +352,6 @@ func (db *DbConfig) CreateDatabase() error { // If this function has an issue, it will ROLLBACK to the previous state. func (db *DbConfig) MigrateDatabase() error { utils.Log(1, "Migrating Database Tables...") - tx := DbSession.Begin() defer func() { if r := recover(); r != nil { diff --git a/core/export.go b/core/export.go index fe4b6529..b6c9bf79 100644 --- a/core/export.go +++ b/core/export.go @@ -31,7 +31,7 @@ func injectDatabase() { func ExportIndexHTML() string { source.Assets() injectDatabase() - CoreApp.SelectAllServices() + CoreApp.SelectAllServices(false) CoreApp.UseCdn = true for _, srv := range CoreApp.Services { service := srv.(*Service) diff --git a/core/services.go b/core/services.go index 3743063c..234f7278 100644 --- a/core/services.go +++ b/core/services.go @@ -41,6 +41,10 @@ func ReturnService(s *types.Service) *Service { return &Service{s} } +func Services() []types.ServiceInterface { + return CoreApp.Services +} + // SelectService returns a *core.Service from in memory func SelectService(id int64) *Service { 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. -func (c *Core) SelectAllServices() ([]*Service, error) { +func (c *Core) SelectAllServices(start bool) ([]*Service, error) { var services []*Service db := servicesDB().Find(&services).Order("order_id desc") if db.Error != nil { @@ -84,8 +88,10 @@ func (c *Core) SelectAllServices() ([]*Service, error) { } CoreApp.Services = nil for _, service := range services { - service.Start() - service.CheckinProcess() + if start { + service.Start() + service.CheckinProcess() + } service.AllFailures() CoreApp.Services = append(CoreApp.Services, service) } diff --git a/core/services_test.go b/core/services_test.go index b400ec64..7cbde32f 100644 --- a/core/services_test.go +++ b/core/services_test.go @@ -27,7 +27,7 @@ var ( ) func TestSelectHTTPService(t *testing.T) { - services, err := CoreApp.SelectAllServices() + services, err := CoreApp.SelectAllServices(false) assert.Nil(t, err) assert.Equal(t, 15, len(services)) assert.Equal(t, "Google", services[0].Name) @@ -39,7 +39,7 @@ func TestSelectAllServices(t *testing.T) { for _, s := range services { service := s.(*Service) service.Check(false) - assert.True(t, service.IsRunning()) + assert.False(t, service.IsRunning()) t.Logf("ID: %v %v\n", service.Id, service.Name) } assert.Equal(t, 15, len(services)) @@ -77,7 +77,7 @@ func TestUpdateService(t *testing.T) { } func TestUpdateAllServices(t *testing.T) { - services, err := CoreApp.SelectAllServices() + services, err := CoreApp.SelectAllServices(false) assert.Nil(t, err) for k, srv := range services { srv.Name = "Changed " + srv.Name @@ -268,7 +268,7 @@ func TestCreateServiceFailure(t *testing.T) { func TestDeleteService(t *testing.T) { service := SelectService(newServiceId) - count, err := CoreApp.SelectAllServices() + count, err := CoreApp.SelectAllServices(false) assert.Nil(t, err) assert.Equal(t, 18, len(count)) diff --git a/handlers/index.go b/handlers/index.go index 56c756eb..3d9ead7c 100644 --- a/handlers/index.go +++ b/handlers/index.go @@ -39,7 +39,7 @@ func DesktopInit(ip string, port int) { var err error exists := utils.FileExists(utils.Directory + "/statup.db") if exists { - core.Configs, err = core.LoadConfig(utils.Directory) + core.Configs, err = core.LoadConfigFile(utils.Directory) if err != nil { utils.Log(3, err) return @@ -79,7 +79,7 @@ func DesktopInit(ip string, port int) { return } - core.Configs, err = core.LoadConfig(utils.Directory) + core.Configs, err = core.LoadConfigFile(utils.Directory) if err != nil { utils.Log(3, err) config.Error = err diff --git a/handlers/api_handlers_test.go b/handlers/route_api_test.go similarity index 93% rename from handlers/api_handlers_test.go rename to handlers/route_api_test.go index 54c0757e..0de9a89e 100644 --- a/handlers/api_handlers_test.go +++ b/handlers/route_api_test.go @@ -45,13 +45,13 @@ func init() { func loadDatabase() { core.NewCore() - core.LoadConfig(dir) + core.LoadConfigFile(dir) core.Configs = &core.DbConfig{ DbConn: "sqlite", Location: dir, } - core.Configs.Connect(false, utils.Directory) core.CoreApp.DbConnection = "sqlite" + core.Configs.Connect(false, utils.Directory) core.CoreApp.Version = "DEV" core.Configs.Save() } @@ -75,11 +75,14 @@ func Clean() { } func TestInit(t *testing.T) { - Clean() - loadDatabase() - resetDatabase() - loadDatabase() - core.InitApp() + //Clean() + //loadDatabase() + //resetDatabase() + //loadDatabase() + //core.SelectCore() + //core.InsertNotifierDB() + //core.CoreApp.SelectAllServices(false) + //core.CoreApp.Notifications = notifier.Load() } func formatJSON(res string, out interface{}) { @@ -93,7 +96,7 @@ func TestApiIndexHandler(t *testing.T) { var obj types.Core formatJSON(body, &obj) 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) } @@ -104,8 +107,8 @@ func TestApiAllServicesHandlerHandler(t *testing.T) { var obj []types.Service formatJSON(body, &obj) assert.Equal(t, 200, rr.Code) - assert.Equal(t, "Google", obj[0].Name) - assert.Equal(t, "https://google.com", obj[0].Domain) + assert.Equal(t, "Test Service 9", obj[0].Name) + assert.Equal(t, "https://www.youtube.com/watch?v=yydZbVoCbn0&t=870s", obj[0].Domain) } func TestApiServiceHandler(t *testing.T) { @@ -174,7 +177,7 @@ func TestApiAllUsersHandler(t *testing.T) { var obj []types.User formatJSON(body, &obj) 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) { @@ -194,13 +197,13 @@ func TestApiCreateUserHandler(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) body := rr.Body.String() assert.Equal(t, 200, rr.Code) var obj types.User formatJSON(body, &obj) - assert.Equal(t, "testadmin2", obj.Username) + assert.Equal(t, "admin", obj.Username) assert.Equal(t, true, obj.Admin) } diff --git a/handlers/setup.go b/handlers/setup.go index b4884e2a..de4ab3d0 100644 --- a/handlers/setup.go +++ b/handlers/setup.go @@ -21,7 +21,6 @@ import ( "github.com/hunterlong/statup/utils" "net/http" "os" - "strconv" "time" ) @@ -31,32 +30,16 @@ func setupHandler(w http.ResponseWriter, r *http.Request) { return } w.WriteHeader(http.StatusOK) - port := 5432 - if os.Getenv("DB_CONN") == "mysql" { - port = 3306 - } var data interface{} if os.Getenv("DB_CONN") != "" { - data = &types.DbConfig{ - 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: "", - } + data, _ = core.LoadUsingEnv() } executeResponse(w, r, "setup.html", data, nil) } func processSetupHandler(w http.ResponseWriter, r *http.Request) { var err error - if core.CoreApp.Services != nil { + if core.Services() != nil { http.Redirect(w, r, "/", http.StatusSeeOther) return } @@ -66,15 +49,14 @@ func processSetupHandler(w http.ResponseWriter, r *http.Request) { dbPass := r.PostForm.Get("db_password") dbDatabase := r.PostForm.Get("db_database") 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") username := r.PostForm.Get("username") password := r.PostForm.Get("password") - sample := r.PostForm.Get("sample_data") + //sample := r.PostForm.Get("sample_data") description := r.PostForm.Get("description") domain := r.PostForm.Get("domain") email := r.PostForm.Get("email") - dir := utils.Directory config := &core.DbConfig{ @@ -94,24 +76,21 @@ func processSetupHandler(w http.ResponseWriter, r *http.Request) { Location: utils.Directory, } - core.Configs, err = config.Save() - if err != nil { + if core.Configs, err = config.Save(); err != nil { utils.Log(4, err) config.Error = err setupResponseError(w, r, config) return } - core.Configs, err = core.LoadConfig(dir) - if err != nil { + if core.Configs, err = core.LoadConfigFile(dir); err != nil { utils.Log(3, err) config.Error = err setupResponseError(w, r, config) return } - err = core.Configs.Connect(false, dir) - if err != nil { + if err = core.Configs.Connect(false, dir); err != nil { utils.Log(4, err) core.DeleteConfig() config.Error = err @@ -138,11 +117,7 @@ func processSetupHandler(w http.ResponseWriter, r *http.Request) { }) admin.Create() - if sample == "on" { - core.InsertSampleData() - core.InsertSampleHits() - } - + core.SampleData() core.InitApp() resetCookies() time.Sleep(2 * time.Second) diff --git a/plugin/plugin.go b/plugin/plugin.go index 786e2741..f2035046 100644 --- a/plugin/plugin.go +++ b/plugin/plugin.go @@ -78,11 +78,10 @@ func LoadPlugin(file string) error { utils.Log(3, fmt.Sprintf("Plugin '%v' could not locate Plugin variable. %v", fileBin, err)) return err } - var plugActions types.PluginActions plugActions, ok := symPlugin.(types.PluginActions) if !ok { 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() err = plugActions.OnLoad() @@ -102,7 +101,7 @@ func LoadPlugins() { } files, err := ioutil.ReadDir(pluginDir) 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 } for _, f := range files { @@ -112,5 +111,5 @@ func LoadPlugins() { 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))) } diff --git a/types/types.go b/types/types.go index cea15916..21664322 100644 --- a/types/types.go +++ b/types/types.go @@ -35,7 +35,7 @@ type DbConfig struct { DbUser string `yaml:"user"` DbPass string `yaml:"password"` DbData string `yaml:"database"` - DbPort int `yaml:"port"` + DbPort int64 `yaml:"port"` ApiKey string `yaml:"api_key"` ApiSecret string `yaml:"api_secret"` Project string `yaml:"-"` diff --git a/utils/log.go b/utils/log.go index 916a6711..996d1fd6 100644 --- a/utils/log.go +++ b/utils/log.go @@ -125,7 +125,6 @@ func Log(level int, err interface{}) error { // Http returns a log for a HTTP request func Http(r *http.Request) string { 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) pushLastLine(msg) return msg