-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilt_in_commands.go
318 lines (256 loc) · 7.56 KB
/
built_in_commands.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
package goapp
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"time"
"github.com/mitoteam/mttools"
"github.com/spf13/cobra"
)
func (app *AppBase) buildRootCmd() {
app.rootCmd = &cobra.Command{
Version: app.Version,
//disable default 'completion' subcommand
CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
Run: func(cmd *cobra.Command, args []string) {
//show help if no subcommand given
cmd.Help()
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
//Load Settings
if mttools.IsFileExists(app.AppSettingsFilename) {
if err := app.loadSettings(); err != nil {
return err
}
} else {
//do not require settings loading just for certain commands
no_settings_required_cmd_list := []string{"init", "version", "info", "help"}
if !mttools.InSlice(cmd.Name(), no_settings_required_cmd_list) {
log.Fatalf(
"No "+app.AppSettingsFilename+" file found. Please create one or use `%s init` command.\n", app.ExecutableName,
)
}
}
if app.PreCmdF != nil {
if err := app.PreCmdF(cmd); err != nil {
return err
}
}
return nil
},
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
if app.PostCmdF != nil {
if err := app.PostCmdF(cmd); err != nil {
return err
}
}
return nil
},
}
}
func (app *AppBase) buildVersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Prints the raw version number of " + app.AppName + ".",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(app.Version)
},
}
}
func (app *AppBase) buildLicenseCmd() *cobra.Command {
return &cobra.Command{
Use: "license",
Short: "Prints license information for " + app.AppName + ".",
Run: func(cmd *cobra.Command, args []string) {
title := app.AppName + " license information"
fmt.Println(title + "\n" + strings.Repeat("-", len(title)) + "\n")
fmt.Println(app.License)
},
}
}
func (app *AppBase) buildInstallCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "install",
Short: "Creates system service to run " + app.AppName + ".",
Run: func(cmd *cobra.Command, args []string) {
if mttools.IsSystemdAvailable() {
unitData := &mttools.ServiceData{
Name: app.baseSettings.ServiceName,
User: app.baseSettings.ServiceUser,
Group: app.baseSettings.ServiceGroup,
Autostart: app.serviceAutostart,
}
if err := unitData.InstallSystemdService(); err != nil {
log.Fatal(err)
}
} else {
log.Fatalf(
"Directory %s does not exists. Only systemd based services supported for now.\n",
mttools.SystemdServiceDirPath,
)
}
},
}
cmd.PersistentFlags().BoolVar(
&app.serviceAutostart,
"autostart",
true,
"Set service to be auto started after boot. Please note: this option does not auto starts service after installation.",
)
return cmd
}
func (app *AppBase) buildUninstallCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "uninstall",
Short: "Removes installed system service " + app.AppName + ".",
Run: func(cmd *cobra.Command, args []string) {
if mttools.IsSystemdAvailable() {
unitData := &mttools.ServiceData{
Name: app.baseSettings.ServiceName,
}
if err := unitData.UninstallSystemdService(); err != nil {
log.Fatal(err)
}
} else {
log.Fatalf(
"Directory %s does not exists. Only systemd based services supported for now.\n",
mttools.SystemdServiceDirPath,
)
}
},
}
return cmd
}
func (app *AppBase) buildInitCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "init",
Short: "Creates settings file with defaults in working directory.",
RunE: func(cmd *cobra.Command, args []string) error {
if mttools.IsFileExists(app.AppSettingsFilename) {
return errors.New("Can not initialize existing file: " + app.AppSettingsFilename)
}
comment := `File was created automatically by '` + app.AppName + ` init' command. There are all
available options listed here with its default values. Recommendation is to edit options you
want to change and remove all others with default values to keep this as simple as possible.
`
if err := app.saveSettings(comment); err != nil {
return err
}
fmt.Println("Default app settings written to " + app.AppSettingsFilename)
if app.InitF != nil {
if err := app.InitF(); err != nil {
return err
}
}
return nil
},
}
return cmd
}
func (app *AppBase) buildInfoCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "info",
Short: "Prints info about app, settings, status etc.",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("%s\n", app.AppName)
fmt.Print("================================\n")
fmt.Printf("Version: %s\n", app.Version)
fmt.Printf("Commit: %s\n", app.BuildCommit)
fmt.Printf("Built: at %s with %s\n", app.BuildTime, app.BuildWith)
// Settings
fmt.Print("\n================================\n")
fmt.Print("SETTINGS\n")
fmt.Print("================================\n")
if app.baseSettings.LoadedFromFile {
app.printSettings()
} else {
fmt.Printf("File %s not found.\n", app.AppSettingsFilename)
}
if app.PrintInfoF != nil {
app.PrintInfoF()
}
},
}
return cmd
}
func (app *AppBase) buildRunCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "run",
Short: "Runs webserver.",
RunE: func(cmd *cobra.Command, args []string) error {
address := app.baseSettings.WebserverHostname +
":" + strconv.FormatUint(uint64(app.baseSettings.WebserverPort), 10)
//Graceful shutdown according to https://github.com/gorilla/mux#graceful-shutdown
httpSrv := &http.Server{
Addr: address,
WriteTimeout: time.Second * 10,
ReadTimeout: time.Second * 20,
IdleTimeout: time.Second * 60,
Handler: app.Handler(),
BaseContext: func(l net.Listener) context.Context { return app.BaseContext },
}
log.Printf("Starting up web server at http://%s\nPress Ctrl + C to stop it.\n", address)
go func() {
if err := httpSrv.ListenAndServe(); err != nil {
log.Println(err)
}
}()
cancel_channel := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(cancel_channel, os.Interrupt, os.Kill)
// Block execution until we receive our signal.
<-cancel_channel
// Notify application we are shutting down (via context.WithCancel())
app.appShutdownF()
log.Println("Shutting down web server")
// Create a deadline to wait for (10s).
shutdownCtx, cancel := context.WithTimeout(app.BaseContext, app.ShutdownTimeout)
defer cancel()
if err := httpSrv.Shutdown(shutdownCtx); err != nil {
log.Fatal("Server forced to shutdown:", err)
}
return nil
},
// Do startup procedures
PreRunE: func(cmd *cobra.Command, args []string) error {
log.Printf("%s version: %s\n", app.AppName, app.Version)
var err error
if app.PreRunF != nil {
err = app.PreRunF()
}
return err
},
// Do shutdown procedures
PostRunE: func(cmd *cobra.Command, args []string) error {
var err error
if app.PostRunF != nil {
err = app.PostRunF()
}
log.Println("Shutdown complete")
return err
},
}
//Extended query log
cmd.PersistentFlags().BoolVar(
&app.WebRouterLogRequests,
"log-requests",
false,
"Extended web router queries logging.",
)
// log SQL queries
cmd.PersistentFlags().BoolVar(
&app.baseSettings.LogSql,
"log-sql",
app.baseSettings.LogSql,
"Log SQL queries.",
)
return cmd
}