-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
374 lines (299 loc) · 8.35 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package main
import (
"fmt"
"github.com/gofiber/fiber/v2/middleware/pprof"
db "github.com/khorevaa/odin/database"
"github.com/khorevaa/odin/models"
"github.com/khorevaa/odin/utils"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"io/ioutil"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"flag"
swagger "github.com/arsmn/fiber-swagger/v2"
cli "github.com/jawher/mow.cli"
"github.com/khorevaa/odin/service"
"github.com/khorevaa/odin/service/cache"
"log"
"github.com/khorevaa/odin/api"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
rec "github.com/gofiber/fiber/v2/middleware/recover"
"github.com/jinzhu/configor"
_ "github.com/khorevaa/odin/docs" // docs is generated by Swag CLI, you have to import it.
"github.com/recoilme/pudge"
)
const appName = "odin"
// nolint: gochecknoglobals
var (
version = "v. dev"
commit = "none"
date = time.Now().Format(time.RFC3339)
builtBy = "dev"
)
// main
// @title Odin: Remote Administration for 1S.Enterprise Application Servers
// @version 1.0
// @description ODIN Swagger UI
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:3001
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.read Grants read access
// @scope.metrics Grants read access and control metrics operations
// @scope.admin Grants read and write access to administrative information
// @BasePath /api/v1
func main() {
var (
debug bool
prefork bool
port string
appVersion string
preConfigureAppServersFile string
appData string
)
app := cli.App(appName, "Remote Administration for 1S.Enterprise Application Servers")
appVersion = buildVersion()
app.Version("version v", appVersion)
app.BoolOptPtr(&debug, "debug", false, "Enable debug")
app.BoolOptPtr(&prefork, "prefork", false, "Enable prefork in Production")
app.StringOptPtr(&port, "port p", ":3001", "Port to listen on")
app.StringOptPtr(&appData, "dir", "", "App data dir")
app.StringOptPtr(&preConfigureAppServersFile, "config c", "", "File to load preconfigure app servers")
app.Before = func() {
if debug {
// TODO
}
}
app.Action = func() {
server := fiber.New(fiber.Config{
Prefork: prefork,
DisableStartupMessage: true,
})
memoryCache := &cache.Memory{
Expiration: 30 * time.Minute,
}
if len(appData) == 0 {
appData = utils.GetAppDataDir(appName)
}
memoryCache.Connect()
rep := db.NewRepository(appData)
serv, err := service.NewService(memoryCache, rep)
failOnErr(err)
if len(preConfigureAppServersFile) > 0 {
loadAppServers(preConfigureAppServersFile, serv)
}
// Middleware
server.Use(rec.New())
server.Use(service.Middleware(serv))
if debug {
server.Use(logger.New())
server.Use(pprof.New())
}
api.Routes(server, serv)
server.Use("/docs", swagger.Handler) // default
// Setup static files
//server.Static("/", "./static/public")
// Handle not founds
server.Use(api.NotFound)
go func() {
startupMessage(port, false, debug, serv)
log.Fatal(server.Listen(port)) // go run main.go -port=:3000
}()
gracefullyShutdownInit(server)
}
app.After = func() {
_ = pudge.CloseAll()
}
app.ErrorHandling = flag.ExitOnError
err := app.Run(os.Args)
failOnErr(err)
}
func readLicenseFile(filename string) (string, error) {
raw, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
return string(raw), nil
}
func loadAppServers(filePath string, serv service.Service) {
type config struct {
App []models.AppServer
}
var servers config
err := configor.Load(&servers, filePath)
if err != nil {
log.Fatal(err)
}
for _, server := range servers.App {
err := serv.AddAppServer(&server)
if err != nil {
log.Printf("error save app server <%s>", err)
failOnErr(err)
}
}
}
func failOnErr(err error) {
if err != nil {
println(err.Error())
cli.Exit(1)
}
}
func buildVersion() string {
var result = version
if commit != "" {
result = fmt.Sprintf("%s\ncommit: %s", result, commit)
}
if date != "" {
result = fmt.Sprintf("%s\nbuilt at: %s", result, date)
}
if builtBy != "" {
result = fmt.Sprintf("%s\nbuilt by: %s", result, builtBy)
}
return result
}
func gracefullyShutdownInit(app *fiber.App) {
// Wait for interrupt signal to gracefully shutdown the server with
// setup signal catching
quit := make(chan os.Signal, 1)
// catch all signals since not explicitly listing
signal.Notify(quit, syscall.SIGQUIT, os.Interrupt, os.Kill)
q := <-quit
if q != nil {
println(fmt.Sprintf("RECEIVED SIGNAL: %s", q))
}
// Close db
println("Close db ...")
if err := pudge.CloseAll(); err != nil {
log.Println("Database Shutdown err:", err)
}
println("Shutdown Server ...")
if err := app.Shutdown(); err != nil {
log.Println("Server Shutdown:", err)
}
println("Shutdown complete")
time.Sleep(2 * time.Second)
cli.Exit(1)
}
func startupMessage(addr string, tls bool, debug bool, serv service.Service) {
if len(os.Getenv("FIBER_PREFORK_CHILD")) > 0 {
// Для пожчиненных процессов мы не выводим сообщение
return
}
var logo string
logo += "%s"
logo += " ┌───────────────────────────────────────────────────┐\n"
logo += " │ %s │\n"
logo += " │ %s │\n"
logo += " │ %s │\n"
logo += " │ %s │\n"
logo += " │ %s │\n"
logo += " │ %s │\n"
logo += " │ │\n"
logo += " │ Built by: %s Built at: %s │\n"
logo += " │ Cache: %s DB: %s │\n"
logo += " └───────────────────────────────────────────────────┘"
logo += "%s"
const (
cBlack = "\u001b[90m"
// cRed = "\u001b[91m"
cCyan = "\u001b[96m"
// cGreen = "\u001b[92m"
cYellow = "\u001b[93m"
// cBlue = "\u001b[94m"
// cMagenta = "\u001b[95m"
// cWhite = "\u001b[97m"
cReset = "\u001b[0m"
)
value := func(s string, width int) string {
pad := width - len(s)
str := ""
for i := 0; i < pad; i++ {
str += "."
}
if s == "Disabled" {
str += " " + s
} else {
str += fmt.Sprintf(" %s%s%s", cYellow, s, cBlack)
}
return str
}
center := func(s string, width int) string {
pad := strconv.Itoa((width - len(s)) / 2)
str := fmt.Sprintf("%"+pad+"s", " ")
str += s
str += fmt.Sprintf("%"+pad+"s", " ")
if len(str) < width {
str += " "
}
return str
}
centerValue := func(s string, width int) string {
pad := strconv.Itoa((width - len(s)) / 2)
str := fmt.Sprintf("%"+pad+"s", " ")
str += fmt.Sprintf("%s%s%s", cCyan, s, cBlack)
str += fmt.Sprintf("%"+pad+"s", " ")
if len(str)-10 < width {
str += " "
}
return str
}
host, port := parseAddr(addr)
if host == "" || host == "0.0.0.0" {
host = "127.0.0.1"
}
addr = "http://" + host + ":" + port
if tls {
addr = "https://" + host + ":" + port
}
t, _ := time.Parse(time.RFC3339, date)
cacheInfo := "redis"
switch serv.GetCache().(type) {
case *cache.Memory:
cacheInfo = "in memory"
}
dbInfo := "pudge"
pprofInfo := ""
if debug {
pprofInfo = " Pprof: " + addr + "/debug/pprof"
}
switch serv.Repository().(type) {
case *db.InMemory:
dbInfo = "in memory"
}
mainLogo := fmt.Sprintf(logo,
cBlack,
centerValue(" ODIN "+version, 49),
center("Remote Administration", 49),
center("for 1S.Enterprise Application Servers", 49),
centerValue(" API: "+addr+"/api/v1", 49),
centerValue(" Docs: "+addr+"/docs", 49),
centerValue(pprofInfo, 49),
value(builtBy, 13), value(t.Format("2006-01-02"), 13),
value(cacheInfo, 16), value(dbInfo, 19),
cReset,
)
out := colorable.NewColorableStdout()
if os.Getenv("TERM") == "dumb" ||
(!isatty.IsTerminal(os.Stdout.Fd()) &&
!isatty.IsCygwinTerminal(os.Stdout.Fd())) {
out = colorable.NewNonColorable(os.Stdout)
}
fmt.Fprintln(out, mainLogo)
}
func parseAddr(raw string) (host, port string) {
if i := strings.LastIndex(raw, ":"); i != -1 {
return raw[:i], raw[i+1:]
}
return raw, ""
}