-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
234 lines (218 loc) · 5.68 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
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"regexp"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/maruel/mess/internal/model"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog/pkgerrors"
)
var started = time.Now()
func getVersion() string {
info, ok := debug.ReadBuildInfo()
if !ok {
return "unknown version/" + runtime.Version()
}
commit := ""
timestamp := ""
tainted := false
for _, s := range info.Settings {
if s.Key == "vcs.time" {
timestamp = s.Value
} else if s.Key == "vcs.revision" {
commit = s.Value
} else if s.Key == "vcs.modified" && s.Value == "true" {
tainted = true
}
}
if commit == "" || timestamp == "" {
return "parsing error/" + runtime.Version()
}
s := timestamp[:16] + "-" + commit[:10]
if tainted {
s += "-tainted"
}
return s + "/" + info.GoVersion
}
func configureLog() {
zerolog.CallerMarshalFunc = func(file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
return short + ":" + strconv.Itoa(line)
}
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
log.Logger = log.Logger.With().Caller().Logger()
}
// watchExe watches the main executable and cancel the returned context when
// touched.
//
// The assumption is that the executable is run as a systemd service unit or
// something similar that will restart the service.
func watchExe(ctx context.Context) (context.Context, func(), error) {
exe, err := os.Executable()
if err != nil {
return nil, nil, err
}
w, err := fsnotify.NewWatcher()
if err != nil {
return nil, nil, err
}
if err := w.Add(exe); err != nil {
w.Close()
return nil, nil, err
}
log.Debug().Dur("ms", time.Since(started).Round(time.Millisecond)/10).Str("file", exe).Msg("file watching")
ctx2, cancel := context.WithCancel(ctx)
go func() {
select {
case e := <-w.Events:
log.Warn().Dur("ms", time.Since(started).Round(time.Millisecond)/10).Interface("ev", e).Str("file", exe).Msg("file watching event")
case err2 := <-w.Errors:
log.Warn().Dur("ms", time.Since(started).Round(time.Millisecond)/10).Err(err2).Str("file", exe).Msg("file watching error")
case <-ctx2.Done():
}
w.Close()
cancel()
}()
return ctx2, cancel, err
}
func mainImpl() error {
configureLog()
port := flag.Int("port", 7899, "HTTP port for the web server to listen to")
local := flag.Bool("local", false, "Bind local, allow everyone to be admin; useful for local testing the UI")
cid := flag.String("cid", "", "Google OAuth2 Client ID")
usr := flag.String("usr", "", "Comma separated users allowed access")
flag.Parse()
if *cid == "" {
fmt.Printf("Warning: you should pass -cid\n")
fmt.Printf("\n")
fmt.Printf("- Visit https://console.cloud.google.com/apis/credentials\n")
fmt.Printf("- Expose this server to the internet, preferably fronted with Caddy.\n")
fmt.Printf("- Create ID client Oauth 2.0 for a Web Application.\n")
fmt.Printf("- Javascript Origin: https://<domain.com\n")
fmt.Printf("- Redirection: https://<domain.com/oauth2callback\n")
fmt.Printf("\n")
} else if b, _ := regexp.MatchString(`^[a-z0-9\-]{10,}\.apps\.googleusercontent\.com$`, *cid); !b {
fmt.Printf("Warning: the client id passed to -cid doesn't like the expected form.\n")
fmt.Printf("\n")
fmt.Printf("It should look like 1111-aaaaaaaaaaa.apps.googleusercontent.com\n")
fmt.Printf("\n")
}
allowed := map[string]struct{}{}
for _, u := range strings.Split(*usr, ",") {
allowed[u] = struct{}{}
}
if len(allowed) == 0 {
fmt.Printf("Warning: No user is allowed access.\n")
fmt.Printf("\n")
fmt.Printf("Use the -usr flag to allow Google Accounts.\n")
fmt.Printf("\n")
}
outputs, err := model.NewTaskOutputs("outputs")
if err != nil {
return err
}
// Use one of sqlite or json DB backend.
d, err := model.NewDBSqlite3("mess.db")
//d, err := model.NewDBJSON("db.json.zst")
if err != nil {
return err
}
ctx, cancel, err := watchExe(context.Background())
if err != nil {
return err
}
defer cancel()
log.Info().Dur("ms", time.Since(started).Round(time.Millisecond)/10).Msg("Loaded DB")
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
cancel()
}()
wg := sync.WaitGroup{}
ver := getVersion()
s := server{
local: *local,
version: ver,
cid: *cid,
allowed: allowed,
tables: d,
outputs: outputs,
authCache: map[string]*userInfo{},
}
s.sched.init(d)
wg.Add(1)
go func() {
s.sched.loop(ctx)
wg.Done()
}()
if err := s.start(*port); err != nil {
cancel()
wg.Wait()
return err
}
wg.Add(1)
go func() {
s.serve(ctx)
wg.Done()
}()
log.Info().Dur("ms", time.Since(started).Round(time.Millisecond)/10).
Str("port", s.l.Addr().String()).
Str("version", ver).Msg("Listening")
done := ctx.Done()
wg.Add(1)
go func() {
// Intentionally save too often initially.
for t := time.NewTimer(5 * time.Second); ; {
select {
case <-done:
t.Stop()
wg.Done()
return
case <-t.C:
_ = d.Snapshot()
}
}
}()
wg.Add(1)
go func() {
outputs.Loop(ctx, 10000, 6*time.Minute)
wg.Done()
}()
<-done
stopping := time.Now()
log.Info().Dur("ms", time.Since(started).Round(time.Millisecond)/10).Msg("Terminating")
// Do not save until everything completed.
wg.Wait()
err = d.Close()
if err != nil {
// This is a big deal.
err = fmt.Errorf("data loss! %w", err)
}
log.Info().Dur("ms", time.Since(stopping).Round(time.Millisecond)/10).Msg("Saved DB")
return err
}
func main() {
if err := mainImpl(); err != nil {
fmt.Fprintf(os.Stderr, "mess: %v\n", err)
os.Exit(1)
}
}