This repository was archived by the owner on Jun 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
207 lines (172 loc) · 5.89 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package main
import (
"github.com/MarvinMenzerath/UpAndRunning2/lib"
"github.com/MarvinMenzerath/UpAndRunning2/routes"
"github.com/MarvinMenzerath/UpAndRunning2/routes/APIv1"
"github.com/MarvinMenzerath/UpAndRunning2/routes/APIv2"
"github.com/franela/goreq"
"github.com/julienschmidt/httprouter"
"github.com/op/go-logging"
"net/http"
"runtime"
"strconv"
"time"
)
const VERSION = "2.2.1"
var goVersion = runtime.Version()
var goArch = runtime.GOOS + "_" + runtime.GOARCH
// UpAndRunning2 Main - The application's entrance-point
func main() {
// Logger
lib.SetupLogger()
// Welcome
logging.MustGetLogger("").Info("Welcome to UpAndRunning2 v" + VERSION + " [" + goVersion + "@" + goArch + "]!")
// Config
lib.ReadConfigurationFromFile("config/local.json")
lib.SetStaticConfiguration(lib.StaticConfiguration{VERSION, goVersion, goArch})
// Database
lib.OpenDatabase(lib.GetConfiguration().Database)
// Config (again)
lib.ReadConfigurationFromDatabase(lib.GetDatabase())
// Admin-User
admin := lib.Admin{}
admin.Init()
// Session-Management
lib.InitSessionManagement()
// Additional Libraries
goreq.SetConnectTimeout(5 * time.Second)
lib.InitHttpStatusCodeMap()
go lib.RunTelegramBot()
// Start Checking and Serving
checkAllSites()
startCheckTimer()
startCleaningTimer()
serveRequests()
lib.GetDatabase().Close()
}
// Create all routes and start the HTTP-server
func serveRequests() {
router := httprouter.New()
// Default API-message
router.GET("/api", routes.ApiIndex)
// API
setupApi1(router)
setupApi2(router)
// Web-Frontend
if lib.GetConfiguration().Application.UseWebFrontend {
setupWebFrontend(router)
} else {
router.GET("/", routes.NoWebFrontendIndex)
}
// 404 Handler
router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Error 404: Not Found", 404)
})
logging.MustGetLogger("").Debug("Listening on " + lib.GetConfiguration().Address + ":" + strconv.Itoa(lib.GetConfiguration().Port) + "...")
logging.MustGetLogger("").Fatal(http.ListenAndServe(lib.GetConfiguration().Address+":"+strconv.Itoa(lib.GetConfiguration().Port), router))
}
// Setup all routes for API v1
func setupApi1(router *httprouter.Router) {
router.GET("/api/v1/*all", APIv1.ApiIndexVersion)
router.POST("/api/v1/*all", APIv1.ApiIndexVersion)
router.PUT("/api/v1/*all", APIv1.ApiIndexVersion)
router.DELETE("/api/v1/*all", APIv1.ApiIndexVersion)
}
// Setup all routes for API v2
func setupApi2(router *httprouter.Router) {
router.GET("/api/v2", APIv2.ApiIndexVersion)
// Public Statistics
router.GET("/api/v2/websites", APIv2.ApiWebsites)
router.GET("/api/v2/websites/:url/status", APIv2.ApiWebsitesStatus)
router.GET("/api/v2/websites/:url/results", APIv2.ApiWebsitesResults)
// Authentication
router.POST("/api/v2/auth/login", APIv2.ApiAuthLogin)
router.GET("/api/v2/auth/logout", APIv2.ApiAuthLogout)
// Settings
router.PUT("/api/v2/settings/password", APIv2.ApiSettingsPassword)
router.PUT("/api/v2/settings/interval", APIv2.ApiSettingsInterval)
// Website Management
router.POST("/api/v2/websites/:url", APIv2.ApiWebsitesAdd)
router.PUT("/api/v2/websites/:url", APIv2.ApiWebsitesEdit)
router.DELETE("/api/v2/websites/:url", APIv2.ApiWebsitesDelete)
router.PUT("/api/v2/websites/:url/enabled", APIv2.ApiWebsitesEnabled)
router.PUT("/api/v2/websites/:url/visibility", APIv2.ApiWebsitesVisibility)
router.GET("/api/v2/websites/:url/notifications", APIv2.ApiWebsitesGetNotifications)
router.PUT("/api/v2/websites/:url/notifications", APIv2.ApiWebsitePutNotifications)
router.GET("/api/v2/websites/:url/check", APIv2.ApiWebsiteCheck)
}
// Setup all routes for Web-Frontend
func setupWebFrontend(router *httprouter.Router) {
// Index
router.GET("/", routes.ViewIndex)
router.GET("/status/:url", routes.ViewIndex)
router.GET("/results/:url", routes.ViewIndex)
// Admin
router.GET("/admin", routes.ViewAdmin)
router.GET("/admin/login", routes.ViewLogin)
// Static Files
router.ServeFiles("/public/*filepath", http.Dir("public"))
}
// Creates a timer to regularly check all Websites
func startCheckTimer() {
timer := time.NewTimer(time.Second * time.Duration(lib.GetConfiguration().Dynamic.Interval))
go func() {
<-timer.C
checkAllSites()
startCheckTimer()
}()
}
// Creates a timer to remove old check-results from the Database
func startCleaningTimer() {
timer := time.NewTimer(time.Hour * 24)
go func() {
<-timer.C
lib.CleanDatabase()
startCleaningTimer()
}()
}
// Checks all enabled Websites
func checkAllSites() {
// Check for internet-connection
if !lib.GetConfiguration().Application.RunCheckIfOffline {
res, err := goreq.Request{Uri: "https://google.com", Method: "HEAD", UserAgent: "UpAndRunning2 (https://github.com/MarvinMenzerath/UpAndRunning2)", MaxRedirects: 1, Timeout: 5 * time.Second}.Do()
if err != nil {
logging.MustGetLogger("").Warning("Did not check Websites because of missing internet-connection: ", err)
return
} else {
if res.StatusCode != 200 {
logging.MustGetLogger("").Warning("Did not check Websites because of missing internet-connection.")
res.Body.Close()
return
}
}
}
// Query the Database
db := lib.GetDatabase()
rows, err := db.Query("SELECT id, protocol, url, checkMethod FROM websites WHERE enabled = 1;")
if err != nil {
logging.MustGetLogger("").Error("Unable to fetch Websites: ", err)
return
}
defer rows.Close()
// Check every Website
count := 0
for rows.Next() {
var website lib.Website
err = rows.Scan(&website.Id, &website.Protocol, &website.Url, &website.CheckMethod)
if err != nil {
logging.MustGetLogger("").Error("Unable to read Website-Row: ", err)
return
}
go website.RunCheck(false)
count++
time.Sleep(time.Millisecond * 200)
}
// Check for Errors
err = rows.Err()
if err != nil {
logging.MustGetLogger("").Error("Unable to read Website-Rows: ", err)
return
}
logging.MustGetLogger("").Info("Checked " + strconv.Itoa(count) + " active Websites.")
}