-
Notifications
You must be signed in to change notification settings - Fork 0
/
crongo.go
327 lines (282 loc) · 7.43 KB
/
crongo.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
package main
import (
"bytes"
"database/sql"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/fatih/color"
"github.com/gosuri/uitable"
_ "github.com/mattn/go-sqlite3"
"github.com/urfave/cli"
)
var dbFile = os.Getenv("HOME") + "/crongo.db"
type command struct {
id int
cmd string
date *time.Time
stdout string
stderr string
errorCode int
}
func runCommand(command string) (c command) {
name := "bash"
args := []string{"-c", command}
var outbuf, errbuf bytes.Buffer
cmd := exec.Command(name, args...)
cmd.Stdout = &outbuf
cmd.Stderr = &errbuf
err := cmd.Run()
c.stdout = outbuf.String()
c.stderr = errbuf.String()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
ws := exitError.Sys().(syscall.WaitStatus)
c.errorCode = ws.ExitStatus()
} else {
// Workaround for Mac
c.errorCode = 1
if c.stderr == "" {
c.stderr = err.Error()
}
}
} else {
ws := cmd.ProcessState.Sys().(syscall.WaitStatus)
c.errorCode = ws.ExitStatus()
}
c.cmd = command
return c
}
func listAllRuns(limit int, filter string) []command {
filterAppendix := ""
if filter != "" {
filterAppendix = "where cmd like '%" + filter + "%'"
}
stmt := "select * from (select * from commands " + filterAppendix + " order by id DESC limit " + fmt.Sprint(limit) + ") order by id ASC"
//select * from (select * from commands order by id DESC limit 5) order by id ASC
return runStatement(stmt)
}
func listAllFailedRuns(limit int, filter string) []command {
filterAppendix := ""
if filter != "" {
filterAppendix = "and cmd like '%" + filter + "%'"
}
stmt := "select * from (select * from commands where error_code > 0 " + filterAppendix + " order by id DESC limit " + fmt.Sprint(limit) + ") order by id ASC"
return runStatement(stmt)
}
func formatCommands(commands []command) string {
table := uitable.New()
table.MaxColWidth = 50
statusDot := "◉"
table.AddRow("CODE", "ID", "DATE", "CMD", "STDOUT", "STDERR")
for _, command := range commands {
statusLine := statusDot + " " + strconv.Itoa(command.errorCode)
table.AddRow(statusLine, command.id, command.date.In(time.Local), command.cmd, command.stdout, command.stderr)
}
// Workaround: uitable counts non printable characters like colors, therefore garbeling the width of the table
// paint all status codes red
out := strings.Replace(table.String(), statusDot, color.RedString(statusDot), -1)
// paint all red status codes with a follow up zero green
out = strings.Replace(out, color.RedString(statusDot)+" 0", color.GreenString(statusDot)+" 0", -1)
return out
}
func runStatement(stmt string) []command {
var commands []command
database, err := sql.Open("sqlite3", dbFile)
if err != nil {
log.Fatal(err)
}
//TODO Add debug flag here
// log.Printf("Running stmt: %s", stmt)
rows, err := database.Query(stmt)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var c command
err = rows.Scan(&c.id, &c.date, &c.cmd, &c.stdout, &c.stderr, &c.errorCode)
if err != nil {
log.Fatal(err)
}
commands = append(commands, c)
}
return commands
}
func writeToDb(c command) {
log.Printf("Accessing db in %s", dbFile)
database, err := sql.Open("sqlite3", dbFile)
if err != nil {
log.Fatal(err)
}
statement, err := database.Prepare("CREATE TABLE IF NOT EXISTS commands (id INTEGER PRIMARY KEY, sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, cmd TEXT, stdout TEXT, stderr TEXT, error_code TEXT)")
if err != nil {
log.Fatal(err)
}
statement.Exec()
statement, err = database.Prepare("INSERT INTO commands (cmd, stdout, stderr, error_code) VALUES (?, ?, ?, ?)")
statement.Exec(c.cmd, c.stdout, c.stderr, c.errorCode)
}
func runCommandAndStoreIntoDatabase(cmd string) (exitCode int) {
c := runCommand(cmd)
writeToDb(c)
prettyPrintCommand(c)
return c.errorCode
}
func prettyPrintCommand(c command) {
fmt.Printf("stdout:\n%v\nstderr:\n%v\nexit_code: %v\n", c.stdout, c.stderr, c.errorCode)
}
func getCommandInfoFromDatabase(id int) error {
c := runStatement("select * from commands where id = " + fmt.Sprint(id))
if len(c) > 0 {
prettyPrintCommand(c[0])
return nil
}
return fmt.Errorf("Command with id %s not found", strconv.Itoa(id))
}
func purgeDatabase(numberOfEntriesToKeep int) {
runStatement(`
DELETE FROM "commands"
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM "commands"
ORDER BY id DESC
LIMIT ` + strconv.Itoa(numberOfEntriesToKeep) + `
) purge
);`)
// Actually release occupied space
runStatement("vacuum")
}
func main() {
run(os.Args)
}
func run(args []string) {
app := cli.NewApp()
app.Version = "0.3.3"
var limit int
var filter string
app.Commands = []cli.Command{
{
Name: "run",
Aliases: []string{"r"},
Usage: "run a command",
ArgsUsage: "command to run",
Action: func(c *cli.Context) error {
if !c.IsSet("log") {
// Don't log anything
log.SetOutput(ioutil.Discard)
}
if len(c.Args()) != 1 {
return cli.NewExitError("Command missing", 1)
}
exitCode := runCommandAndStoreIntoDatabase(c.Args().Get(0))
// reflect exit code
return cli.NewExitError("", exitCode)
},
},
{
Name: "list",
Aliases: []string{"l"},
Usage: "list runs",
Subcommands: []cli.Command{
{
Name: "all",
Usage: "list all runs",
Action: func(c *cli.Context) error {
fmt.Println(formatCommands(listAllRuns(limit, filter)))
return nil
},
Flags: []cli.Flag{
cli.IntFlag{
Name: "limit",
Value: 500,
Usage: "limit number of results",
Destination: &limit,
},
cli.StringFlag{
Name: "filter",
Usage: "filter for command",
Destination: &filter,
},
},
},
{
Name: "failed",
Usage: "list all failed runs",
Action: func(c *cli.Context) error {
fmt.Println(formatCommands(listAllFailedRuns(limit, filter)))
return nil
},
Flags: []cli.Flag{
cli.IntFlag{
Name: "limit",
Value: 500,
Usage: "limit number of results",
Destination: &limit,
},
cli.StringFlag{
Name: "filter",
Usage: "filter for command",
Destination: &filter,
},
},
},
},
},
{
Name: "id",
Aliases: []string{"i"},
Usage: "get info about command in database",
ArgsUsage: "id of command",
Action: func(c *cli.Context) error {
if !c.IsSet("log") {
// Don't log anything
log.SetOutput(ioutil.Discard)
}
if len(c.Args()) != 1 {
return cli.NewExitError("Command missing", 1)
}
id, _ := strconv.Atoi(c.Args().Get(0))
err := getCommandInfoFromDatabase(id)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
return nil
},
},
{
Name: "purge",
Aliases: []string{"p"},
Usage: "purge all entries except the newest, default 100",
ArgsUsage: "entries to purge",
Action: func(c *cli.Context) error {
if len(c.Args()) != 1 {
purgeDatabase(100)
} else if numberOfEntriesToKeep, err := strconv.Atoi(c.Args().Get(0)); err == nil {
purgeDatabase(numberOfEntriesToKeep)
}
return nil
},
},
}
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug",
Usage: "print debug log",
},
}
sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.CommandsByName(app.Commands))
err := app.Run(args)
if err != nil {
log.Fatal(err)
}
}