-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.go
257 lines (234 loc) · 6.38 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
package main
import (
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"net/http/pprof"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/blang/semver" // alt semver: "github.com/Masterminds/semver"
"github.com/facebookgo/grace/gracehttp"
"github.com/julienschmidt/httprouter"
"github.com/justinas/alice"
"github.com/spf13/cobra"
"github.com/ostrost/ostent/cmd"
"github.com/ostrost/ostent/ostent"
"github.com/ostrost/ostent/share/assets"
"github.com/ostrost/ostent/share/templates"
)
func run(*cobra.Command, []string) error {
if cv, err := newSemver(cmd.OstentVersion); err != nil {
logru.Printf("Current semver parse error: %s\n", err)
} else if upgradeChecks && cv != nil {
go untilUpgrade(cv)
}
send, recv := make(chan chan string, 1), make(chan string, 1)
send <- recv
go cmd.MainAgent(send)
hp := <-recv
close(send)
templates.InitTemplates()
go ostent.UpdateLoop()
return serve(hp)
}
func main() {
cmd.RootCmd.RunE = run
cmd.Execute()
}
var (
taggedBin = assets.AssetAltModTimeFunc != nil // whether the build features bin tag
logru = newLogger()
// flags
upgradeChecks = true
logRequests = !taggedBin
)
func newLogger() *logrus.Logger {
lr := logrus.New() // into os.Stderr
lr.Formatter = &logrus.TextFormatter{FullTimestamp: true}
// , TimestampFormat: "02/Jan/2006:15:04:05 -0700",
return lr
}
func init() {
var usagedefault string
if !logRequests {
usagedefault = fmt.Sprintf(" (default %t)", logRequests /* false */)
}
cmd.RootCmd.Flags().BoolVar(&logRequests, "log-requests", logRequests,
"log server requests"+usagedefault)
cmd.RootCmd.Flags().BoolVar(&upgradeChecks, "upgrade-checks", upgradeChecks,
"periodic upgrade checks") // default true
}
func newSemver(s string) (*semver.Version, error) {
v, err := semver.New(s)
if err == nil {
return v, nil
}
if err.Error() == "No Major.Minor.Patch elements found" &&
len(strings.SplitN(s, ".", 3)) == 2 {
return semver.New(s + ".0")
}
return nil, err
}
// serve constructs a *http.Server to (gracefully) Serve. Routes are set here.
func serve(laddr string) error {
distrib, err := ostent.Distrib()
if err != nil {
logru.Printf("Warning: detecting distrib: %s\n", err)
}
var (
serve1 = ostent.NewServeSSE(logRequests)
serve2 = ostent.NewServeWS(serve1, logru)
serve3 = ostent.NewServeIndex(serve2, templates.IndexTemplate, ostent.StaticData{
TAGGEDbin: taggedBin,
Distrib: distrib,
OstentVersion: cmd.OstentVersion,
})
serve4 = ostent.ServeAssets{
Logger: logru,
ReadFunc: assets.Asset,
InfoFunc: assets.AssetInfo,
AltModTimeFunc: assets.AssetAltModTimeFunc,
}
)
routes := map[[2]string]httprouter.Handle{
{"/index.sse", "GET"}: ostent.HandleFunc(serve1.IndexSSE),
{"/index.ws", "GET"}: ostent.HandleFunc(serve2.IndexWS),
{"/", "GET HEAD"}: ostent.HandleFunc(serve3.Index),
// {"/panic", "GET"}: ostent.HandleFunc(func(http.ResponseWriter, *http.Request) { panic("/") }),
}
for _, path := range assets.AssetNames() {
p := "/" + path
if path != "favicon.ico" && path != "robots.txt" {
p = "/" + cmd.OstentVersion + "/" + path // the Version prefix
}
routes[[2]string{p, "GET HEAD"}] = ostent.HandleThen(alice.New(
ostent.AddAssetPathContextFunc(path),
).Then)(serve4.Serve)
}
if !taggedBin { // pprof in dev
routes[[2]string{"/debug/pprof/:name", "GET HEAD POST"}] =
ostent.ParamsFunc(nil)(pprofHandle)
}
r := httprouter.New()
for x, handle := range routes {
for _, m := range strings.Split(x[1], " ") {
r.Handle(m, x[0], handle)
}
}
return gracehttp.Serve(&http.Server{
Addr: laddr,
ErrorLog: log.New(os.Stderr, "[ostent httpd] ", log.LstdFlags),
Handler: ostent.ServerHandler(logRequests, r),
})
}
// untilUpgrade waits for an upgrade and returns.
func untilUpgrade(cv *semver.Version) {
if checkUpgrade(cv) {
return
}
seed := time.Now().UTC().UnixNano()
random := rand.New(rand.NewSource(seed))
wait := time.Hour
wait += time.Duration(random.Int63n(int64(wait))) // 1.5 +- 0.5 h
for {
time.Sleep(wait)
if checkUpgrade(cv) {
break
}
}
}
// checkUpgrade does upgrade check and returns true if an upgrade is available.
func checkUpgrade(cv *semver.Version) bool {
newVersion, err := newerVersion()
if err != nil {
logru.Printf("Upgrade check error: %s\n", err)
return false
}
if newVersion == "" {
logru.Printf("Upgrade check: version is empty\n")
return false
}
nv, err := newSemver(newVersion)
if err != nil {
logru.Printf("Semver parse error: %s\n", err)
return false
}
if !nv.GT(*cv) {
return false
}
logru.Printf("Upgrade check: %s release available\n", newVersion)
ostent.OstentUpgrade.Set(newVersion)
return true
}
// newerVersion checks GitHub for the latest ostent version.
// Return is in form of "\d.*" (sans "^v").
func newerVersion() (string, error) {
// 1. https://github.com/ostrost/ostent/releases/latest // redirects, NOT followed
// 2. https://github.com/ostrost/ostent/releases/v... // Redirect location
// 3. return "v..." // basename of the location
type redirected struct {
error
url url.URL
}
checkRedirect := func(req *http.Request, _via []*http.Request) error {
return redirected{url: *req.URL}
}
client := &http.Client{CheckRedirect: checkRedirect}
resp, err := client.Get("https://github.com/ostrost/ostent/releases/latest")
if err == nil {
err = resp.Body.Close()
if err != nil {
return "", err
}
return "", errors.New("/latest GitHub page did not return a redirect")
}
urlerr, ok := err.(*url.Error)
if !ok {
return "", err
}
if resp != nil && resp.Body != nil {
if err := resp.Body.Close(); err != nil {
return "", err
}
}
redir, ok := urlerr.Err.(redirected)
if !ok {
return "", urlerr
}
v := filepath.Base(redir.url.Path)
if len(v) == 0 || v[0] != 'v' {
return "", fmt.Errorf("Unexpected version from GitHub: %q", v)
}
return v[1:], nil
}
func pprofHandle(w http.ResponseWriter, r *http.Request) {
name, err := ostent.ContextParam(r, "name")
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
var handler func(http.ResponseWriter, *http.Request)
switch name {
case "cmdline":
handler = pprof.Cmdline
case "profile":
handler = pprof.Profile
case "symbol":
handler = pprof.Symbol
case "trace":
handler = pprof.Trace
default:
handler = pprof.Index
}
if handler == nil {
http.NotFound(w, r)
return
}
handler(w, r)
}