forked from fortio/fortio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uihandler.go
766 lines (729 loc) · 24.4 KB
/
uihandler.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// Copyright 2017 Istio Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package ui // import "istio.io/fortio/ui"
import (
"bytes"
// md5 is mandated, not our choice
"crypto/md5" // nolint: gas
"encoding/base64"
"encoding/json"
"fmt"
"html"
"html/template"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"runtime"
"strconv"
"strings"
"sync"
"time"
"istio.io/fortio/fhttp"
"istio.io/fortio/log"
"istio.io/fortio/periodic"
"istio.io/fortio/stats"
)
// TODO: move some of those in their own files/package (e.g data transfer TSV)
// and add unit tests.
var (
// UI and Debug prefix/paths (read in ui handler).
uiPath string // absolute (base)
logoPath string // relative
chartJSPath string // relative
debugPath string // mostly relative
fetchPath string // this one is absolute
// Used to construct default URL to self.
httpPort int
// Start time of the UI Server (for uptime info).
startTime time.Time
// Directory where the static content and templates are to be loaded from.
// This is replaced at link time to the packaged directory (e.g /usr/local/lib/fortio/)
// but when fortio is installed with go get we use RunTime to find that directory.
// (see Dockerfile for how to set it)
resourcesDir string
extraBrowseLabel string // Extra label for report only
// Directory where results are written to/read from
dataDir string
mainTemplate *template.Template
browseTemplate *template.Template
syncTemplate *template.Template
uiRunMapMutex = &sync.Mutex{}
id int64
runs = make(map[int64]*periodic.RunnerOptions)
)
const (
fetchURI = "fetch/"
)
// Gets the resources directory from one of 3 sources:
func getResourcesDir(override string) string {
if override != "" {
log.Infof("Using resources directory from override: %s", override)
return override
}
if resourcesDir != "" {
log.Infof("Using resources directory set at link time: %s", resourcesDir)
return resourcesDir
}
_, filename, _, ok := runtime.Caller(0)
log.Infof("Guessing resources directory from runtime source location: %v - %s", ok, filename)
if ok {
return path.Dir(filename)
}
log.Errf("Unable to get source tree location. Failing to serve static contents.")
return ""
}
// HTMLEscapeWriter is an io.Writer escaping the output for safe html inclusion.
type HTMLEscapeWriter struct {
NextWriter io.Writer
}
func (w *HTMLEscapeWriter) Write(p []byte) (int, error) {
template.HTMLEscape(w.NextWriter, p)
return len(p), nil
}
// TODO: auto map from (Http)RunnerOptions to form generation and/or accept
// JSON serialized options as input.
// TODO: unit tests, allow additional data sets.
type mode int
// The main html has 3 principal modes:
const (
// Default: renders the forms/menus
menu mode = iota
// Trigger a run
run
// Request abort
stop
)
// Handler is the main UI handler creating the web forms and processing them.
func Handler(w http.ResponseWriter, r *http.Request) {
LogRequest(r, "UI")
mode := menu
JSONOnly := false
DoSave := (r.FormValue("save") == "on")
url := r.FormValue("url")
runid := int64(0)
if r.FormValue("load") == "Start" {
mode = run
if r.FormValue("json") == "on" {
JSONOnly = true
log.Infof("Starting JSON only load request from %v for %s", r.RemoteAddr, url)
} else {
log.Infof("Starting load request from %v for %s", r.RemoteAddr, url)
}
} else {
if r.FormValue("stop") == "Stop" {
runid, _ = strconv.ParseInt(r.FormValue("runid"), 10, 64) // nolint: gas
log.Critf("Stop request from %v for %d", r.RemoteAddr, runid)
mode = stop
}
}
// Those only exist/make sense on run mode but go variable declaration...
labels := r.FormValue("labels")
resolution, _ := strconv.ParseFloat(r.FormValue("r"), 64) // nolint: gas
percList, _ := stats.ParsePercentiles(r.FormValue("p")) // nolint: gas
qps, _ := strconv.ParseFloat(r.FormValue("qps"), 64) // nolint: gas
durStr := r.FormValue("t")
var dur time.Duration
if durStr == "on" || ((len(r.Form["t"]) > 1) && r.Form["t"][1] == "on") {
dur = -1
} else {
var err error
dur, err = time.ParseDuration(durStr)
if mode == run && err != nil {
log.Errf("Error parsing duration '%s': %v", durStr, err)
}
}
c, _ := strconv.Atoi(r.FormValue("c")) // nolint: gas
out := io.Writer(os.Stderr)
if !JSONOnly {
out = io.Writer(&HTMLEscapeWriter{NextWriter: w})
}
n, _ := strconv.ParseInt(r.FormValue("n"), 10, 64) // nolint: gas
opts := fhttp.NewHTTPOptions(url)
ro := periodic.RunnerOptions{
QPS: qps,
Duration: dur,
Out: out,
NumThreads: c,
Resolution: resolution,
Percentiles: percList,
Labels: labels,
Exactly: n,
}
if mode == run {
ro.Normalize()
uiRunMapMutex.Lock()
id++ // start at 1 as 0 means interrupt all
runid = id
runs[runid] = &ro
uiRunMapMutex.Unlock()
log.Infof("New run id %d", runid)
}
if !JSONOnly {
// Normal html mode
if mainTemplate == nil {
w.WriteHeader(http.StatusInternalServerError)
log.Critf("Nil template")
return
}
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
durSeconds := dur.Seconds()
if n > 0 {
if qps > 0 {
durSeconds = float64(n) / qps
} else {
durSeconds = -1
}
log.Infof("Estimating fixed #call %d duration to %g seconds %g", n, durSeconds, qps)
}
err := mainTemplate.Execute(w, &struct {
R *http.Request
Headers http.Header
Version string
LogoPath string
DebugPath string
ChartJSPath string
StartTime string
TargetURL string
Labels string
RunID int64
UpTime time.Duration
TestExpectedDurationSeconds float64
Port int
DoStop bool
DoLoad bool
}{r, opts.GetHeaders(), periodic.Version, logoPath, debugPath, chartJSPath,
startTime.Format(time.ANSIC), url, labels, runid,
fhttp.RoundDuration(time.Since(startTime)), durSeconds, httpPort, mode == stop, mode == run})
if err != nil {
log.Critf("Template execution failed: %v", err)
}
}
switch mode {
case menu:
// nothing more to do
case stop:
if runid <= 0 { // Stop all
i := 0
uiRunMapMutex.Lock()
for _, v := range runs {
v.Abort()
i++
}
uiRunMapMutex.Unlock()
log.Infof("Interrupted %d runs", i)
} else { // Stop one
uiRunMapMutex.Lock()
v, found := runs[runid]
if found {
v.Abort()
}
uiRunMapMutex.Unlock()
}
case run:
// mode == run case:
firstHeader := true
for _, header := range r.Form["H"] {
if len(header) == 0 {
continue
}
log.LogVf("adding header %v", header)
if firstHeader {
// If there is at least 1 non empty H passed, reset the header list
opts.ResetHeaders()
firstHeader = false
}
err := opts.AddAndValidateExtraHeader(header)
if err != nil {
log.Errf("Error adding custom headers: %v", err)
}
}
onBehalfOf(opts, r)
o := fhttp.HTTPRunnerOptions{
RunnerOptions: ro,
HTTPOptions: *opts,
AllowInitialErrors: true,
}
flusher, ok := w.(http.Flusher)
if !ok {
log.Fatalf("expected http.ResponseWriter to be an http.Flusher")
}
if !JSONOnly {
flusher.Flush()
}
res, err := fhttp.RunHTTPTest(&o)
uiRunMapMutex.Lock()
delete(runs, runid)
uiRunMapMutex.Unlock()
if err != nil {
w.Write([]byte(fmt.Sprintf("Aborting because %s\n", html.EscapeString(err.Error())))) // nolint: errcheck,gas
return
}
json, err := json.MarshalIndent(res, "", " ")
if err != nil {
log.Fatalf("Unable to json serialize result: %v", err)
}
savedAs := ""
if DoSave {
savedAs = SaveJSON(res.ID(), json)
}
if JSONOnly {
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(json)
if err != nil {
log.Errf("Unable to write json output for %v: %v", r.RemoteAddr, err)
}
return
}
if savedAs != "" {
// nolint: errcheck, gas
w.Write([]byte(fmt.Sprintf("Saved result to <a href='%s'>%s</a>\n", savedAs, savedAs)))
}
// nolint: errcheck, gas
w.Write([]byte(fmt.Sprintf("All done %d calls %.3f ms avg, %.1f qps\n</pre>\n<script>\n",
res.DurationHistogram.Count,
1000.*res.DurationHistogram.Avg,
res.ActualQPS)))
ResultToJsData(w, json)
w.Write([]byte("</script></body></html>\n")) // nolint: gas
}
}
// ResultToJsData converts a result object to chart data arrays and title
// and creates a chart from the result object
func ResultToJsData(w io.Writer, json []byte) {
// nolint: errcheck, gas
w.Write([]byte("var res = "))
// nolint: errcheck, gas
w.Write(json)
// nolint: errcheck, gas
w.Write([]byte("\nvar data = fortioResultToJsChartData(res)\nshowChart(data)\n"))
}
// SaveJSON save Json bytes to give file name (.json) in data-path dir.
func SaveJSON(name string, json []byte) string {
if dataDir == "" {
log.Infof("Not saving because data-path is unset")
return ""
}
name += ".json"
log.Infof("Saving %s in %s", name, dataDir)
err := ioutil.WriteFile(path.Join(dataDir, name), json, 0644)
if err != nil {
log.Errf("Unable to save %s in %s: %v", name, dataDir, err)
return ""
}
// Return the relative path from the /fortio/ UI
return "data/" + name
}
// DataList returns the .json files/entries in data dir.
func DataList() (dataList []string) {
files, err := ioutil.ReadDir(dataDir)
if err != nil {
log.Critf("Can list directory %s: %v", dataDir, err)
return
}
// Newest files at the top:
for i := len(files) - 1; i >= 0; i-- {
name := files[i].Name()
ext := ".json"
if !strings.HasSuffix(name, ext) || files[i].IsDir() {
log.LogVf("Skipping non %s file: %s", ext, name)
continue
}
dataList = append(dataList, name[:len(name)-len(ext)])
}
log.LogVf("data list is %v", dataList)
return dataList
}
// BrowseHandler handles listing and rendering the JSON results.
func BrowseHandler(w http.ResponseWriter, r *http.Request) {
LogRequest(r, "Browse")
path := r.URL.Path
if (path != uiPath) && (path != (uiPath + "browse")) {
if strings.HasPrefix(path, "/fortio") {
log.Infof("Redirecting /fortio in browse only path '%s'", path)
http.Redirect(w, r, uiPath, http.StatusSeeOther)
} else {
log.Infof("Illegal browse path '%s'", path)
w.WriteHeader(http.StatusNotFound)
}
return
}
url := r.FormValue("url")
doRender := (url != "")
dataList := DataList()
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
err := browseTemplate.Execute(w, &struct {
R *http.Request
Extra string
Version string
LogoPath string
ChartJSPath string
URL string
DataList []string
Port int
DoRender bool
}{r, extraBrowseLabel, periodic.Version, logoPath, chartJSPath,
url, dataList, httpPort, doRender})
if err != nil {
log.Critf("Template execution failed: %v", err)
}
}
// LogRequest logs the incoming request, including headers when loglevel is verbose
func LogRequest(r *http.Request, msg string) {
log.Infof("%s: %v %v %v %v (%s)", msg, r.Method, r.URL, r.Proto, r.RemoteAddr,
r.Header.Get("X-Forwarded-Proto"))
if log.LogVerbose() {
for name, headers := range r.Header {
for _, h := range headers {
log.LogVf("Header %v: %v\n", name, h)
}
}
}
}
// LogAndAddCacheControl logs the request and wrapps an HTTP handler to add a Cache-Control header for static files.
func LogAndAddCacheControl(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
LogRequest(r, "Static")
w.Header().Set("Cache-Control", "max-age=365000000, immutable")
h.ServeHTTP(w, r)
})
}
func sendHTMLDataIndex(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
w.Write([]byte("<html><body><ul>\n")) // nolint: errcheck, gas
for _, e := range DataList() {
w.Write([]byte("<li><a href=\"")) // nolint: errcheck, gas
w.Write([]byte(e)) // nolint: errcheck, gas
w.Write([]byte(".json\">")) // nolint: errcheck, gas
w.Write([]byte(e)) // nolint: errcheck, gas
w.Write([]byte("</a>\n")) // nolint: errcheck, gas
}
w.Write([]byte("</ul></body></html>")) // nolint: errcheck, gas
}
type tsvCache struct {
cachedDirTime time.Time
cachedResult []byte
}
var (
gTSVCache tsvCache
gTSVCacheMutex = &sync.Mutex{}
)
// format for gcloud transfer
// https://cloud.google.com/storage/transfer/create-url-list
func sendTSVDataIndex(urlPrefix string, w http.ResponseWriter) {
info, err := os.Stat(dataDir)
if err != nil {
log.Errf("Unable to stat %s: %v", dataDir, err)
w.WriteHeader(http.StatusServiceUnavailable)
return
}
gTSVCacheMutex.Lock() // Kind of a long time to hold a lock... hopefully the FS doesn't hang...
useCache := (info.ModTime() == gTSVCache.cachedDirTime) && (len(gTSVCache.cachedResult) > 0)
if !useCache {
var b bytes.Buffer
b.Write([]byte("TsvHttpData-1.0\n")) // nolint: errcheck, gas
for _, e := range DataList() {
fname := e + ".json"
f, err := os.Open(path.Join(dataDir, fname))
if err != nil {
log.Errf("Open error for %s: %v", fname, err)
continue
}
// This isn't a crypto hash, more like a checksum - and mandated by the
// spec above, not our choice
h := md5.New() // nolint: gas
var sz int64
if sz, err = io.Copy(h, f); err != nil {
f.Close() // nolint: errcheck, gas
log.Errf("Copy/read error for %s: %v", fname, err)
continue
}
b.Write([]byte(urlPrefix)) // nolint: errcheck, gas
b.Write([]byte(fname)) // nolint: errcheck, gas
b.Write([]byte("\t")) // nolint: errcheck, gas
b.Write([]byte(strconv.FormatInt(sz, 10))) // nolint: errcheck, gas
b.Write([]byte("\t")) // nolint: errcheck, gas
b.Write([]byte(base64.StdEncoding.EncodeToString(h.Sum(nil)))) // nolint: errcheck, gas
b.Write([]byte("\n")) // nolint: errcheck, gas
}
gTSVCache.cachedDirTime = info.ModTime()
gTSVCache.cachedResult = b.Bytes()
}
result := gTSVCache.cachedResult
lastModified := gTSVCache.cachedDirTime.Format(http.TimeFormat)
gTSVCacheMutex.Unlock()
log.Infof("Used cached %v to serve %d bytes TSV", useCache, len(result))
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
// Cloud transfer requires ETag
w.Header().Set("ETag", fmt.Sprintf("\"%s\"", lastModified))
w.Header().Set("Last-Modified", lastModified)
w.Write(result) // nolint: errcheck, gas
}
// LogAndFilterDataRequest logs the data request.
func LogAndFilterDataRequest(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
LogRequest(r, "Data")
path := r.URL.Path
if strings.HasSuffix(path, "/") || strings.HasSuffix(path, "/index.html") {
sendHTMLDataIndex(w)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
ext := "/index.tsv"
if strings.HasSuffix(path, ext) {
// Ingress effect:
// The Host header includes original host/port, only missing is the proto:
proto := r.Header.Get("X-Forwarded-Proto")
if len(proto) == 0 {
proto = "http"
}
urlPrefix := proto + "://" + r.Host + path[:len(path)-len(ext)+1]
log.LogVf("Prefix is '%s'", urlPrefix)
sendTSVDataIndex(urlPrefix, w)
return
}
if !strings.HasSuffix(path, ".json") {
log.Warnf("Filtering request for non .json '%s'", path)
w.WriteHeader(http.StatusNotFound)
return
}
h.ServeHTTP(w, r)
})
}
// FetcherHandler is the handler for the fetcher/proxy.
func FetcherHandler(w http.ResponseWriter, r *http.Request) {
LogRequest(r, "Fetch")
hj, ok := w.(http.Hijacker)
if !ok {
log.Critf("hijacking not supported")
return
}
conn, _, err := hj.Hijack()
if err != nil {
log.Errf("hijacking error %v", err)
return
}
// Don't forget to close the connection:
defer conn.Close() // nolint: errcheck
url := r.URL.String()[len(fetchPath):]
opts := fhttp.NewHTTPOptions("http://" + url)
opts.HTTPReqTimeOut = 5 * time.Minute
onBehalfOf(opts, r)
client := fhttp.NewClient(opts)
if client == nil {
return // error logged already
}
_, data, _ := client.Fetch()
_, err = conn.Write(data)
if err != nil {
log.Errf("Error writing fetched data to %v: %v", r.RemoteAddr, err)
}
}
func onBehalfOf(o *fhttp.HTTPOptions, r *http.Request) {
_ = o.AddAndValidateExtraHeader("X-On-Behalf-Of: " + r.RemoteAddr) // nolint: gas
}
// SyncHandler handles syncing/downloading from tsv url.
func SyncHandler(w http.ResponseWriter, r *http.Request) {
LogRequest(r, "Sync")
flusher, ok := w.(http.Flusher)
if !ok {
log.Fatalf("expected http.ResponseWriter to be an http.Flusher")
}
uStr := r.FormValue("url")
err := syncTemplate.Execute(w, &struct {
Version string
LogoPath string
URL string
}{periodic.Version, logoPath, uStr})
if err != nil {
log.Critf("Sync template execution failed: %v", err)
}
w.Write([]byte("Fetch of index url ... ")) // nolint: gas, errcheck
flusher.Flush()
o := fhttp.NewHTTPOptions(uStr)
onBehalfOf(o, r)
// If we had hundreds of thousands of entry we should stream, parallelize (connection pool)
// and not do multiple passes over the same data, but for small tsv this is fine.
// use std client to change the url and handle https:
client := fhttp.NewStdClient(o)
code, data, _ := client.Fetch()
if code != http.StatusOK {
w.Write([]byte(fmt.Sprintf("http error, code %d<script>setPB(1,1)</script>", code))) // nolint: gas, errcheck
} else {
sdata := strings.TrimSpace(string(data))
lines := strings.Split(sdata, "\n")
n := len(lines)
w.Write([]byte(fmt.Sprintf("success! fetching %d referenced URLs:<script>setPB(1,%d)</script>\n", n, n))) // nolint: gas, errcheck
w.Write([]byte("<table>")) // nolint: gas, errcheck
flusher.Flush()
for i, l := range lines[1:] {
parts := strings.Split(l, "\t")
u := parts[0]
w.Write([]byte("<tr><td>")) // nolint: gas, errcheck
w.Write([]byte(template.HTMLEscapeString(u))) // nolint: gas, errcheck
ur, err := url.Parse(u)
if err != nil {
w.Write([]byte("<td>skipped (not a valid url)")) // nolint: gas, errcheck
} else {
uPath := ur.Path
pathParts := strings.Split(uPath, "/")
name := pathParts[len(pathParts)-1]
downloadOne(w, client, name, u)
}
w.Write([]byte(fmt.Sprintf("</tr><script>setPB(%d)</script>\n", i+2))) // nolint: gas, errcheck
flusher.Flush()
}
w.Write([]byte("</table>")) // nolint: gas, errcheck
}
w.Write([]byte("\n</body></html>\n")) // nolint: gas, errcheck
}
func downloadOne(w io.Writer, client *fhttp.Client, name string, u string) {
if !strings.HasSuffix(name, ".json") {
w.Write([]byte("<td>skipped (not json)")) // nolint: gas, errcheck
return
}
localPath := path.Join(dataDir, name)
if _, err := os.Stat(localPath); err == nil || !os.IsNotExist(err) {
log.Infof("check %s : %v", localPath, err)
w.Write([]byte("<td>skipped (already exist or other error)")) // nolint: gas, errcheck
return
}
// url already validated
_ = client.ChangeURL(u) // nolint: gas
code1, data1, _ := client.Fetch()
if code1 != http.StatusOK {
w.Write([]byte(fmt.Sprintf("<td>Http error, code %d", code1))) // nolint: gas, errcheck
return
}
err := ioutil.WriteFile(localPath, data1, 0644)
if err != nil {
log.Errf("Unable to save %s: %v", localPath, err)
w.Write([]byte("<td>skipped (write error)")) // nolint: gas, errcheck
return
}
// finally ! success !
log.Infof("Success fetching %s", u)
// checkmark
w.Write([]byte("<td class='checkmark'>✓")) // nolint: gas, errcheck
}
// Serve starts the fhttp.Serve() plus the UI server on the given port
// and paths (empty disables the feature). uiPath should end with /
// (be a 'directory' path)
func Serve(port int, debugpath, uipath, staticRsrcDir string, datadir string) {
startTime = time.Now()
httpPort = port
if uipath == "" {
fhttp.Serve(port, debugpath) // doesn't return until exit
return
}
uiPath = uipath
dataDir = datadir
if uiPath[len(uiPath)-1] != '/' {
log.Warnf("Adding missing trailing / to UI path '%s'", uiPath)
uiPath += "/"
}
debugPath = ".." + debugpath // TODO: calculate actual path if not same number of directories
http.HandleFunc(uiPath, Handler)
fmt.Printf("UI starting - visit:\nhttp://localhost:%d%s\n", port, uiPath)
fetchPath = uiPath + fetchURI
http.HandleFunc(fetchPath, FetcherHandler)
fhttp.CheckConnectionClosedHeader = true // needed for proxy to avoid errors
logoPath = periodic.Version + "/static/img/logo.svg"
chartJSPath = periodic.Version + "/static/js/Chart.min.js"
// Serve static contents in the ui/static dir. If not otherwise specified
// by the function parameter staticPath, we use getResourcesDir which uses the
// link time value or the directory relative to this file to find the static
// contents, so no matter where or how the go binary is generated, the static
// dir should be found.
staticRsrcDir = getResourcesDir(staticRsrcDir)
if staticRsrcDir != "" {
fs := http.FileServer(http.Dir(staticRsrcDir))
prefix := uiPath + periodic.Version
http.Handle(prefix+"/static/", LogAndAddCacheControl(http.StripPrefix(prefix, fs)))
var err error
mainTemplate, err = template.ParseFiles(path.Join(staticRsrcDir, "templates/main.html"))
if err != nil {
log.Critf("Unable to parse main template: %v", err)
}
browseTemplate, err = template.ParseFiles(path.Join(staticRsrcDir, "templates/browse.html"))
if err != nil {
log.Critf("Unable to parse browse template: %v", err)
} else {
http.HandleFunc(uiPath+"browse", BrowseHandler)
}
syncTemplate, err = template.ParseFiles(path.Join(staticRsrcDir, "templates/sync.html"))
if err != nil {
log.Critf("Unable to parse sync template: %v", err)
} else {
http.HandleFunc(uiPath+"sync", SyncHandler)
}
}
if dataDir != "" {
fs := http.FileServer(http.Dir(dataDir))
http.Handle(uiPath+"data/", LogAndFilterDataRequest(http.StripPrefix(uiPath+"data", fs)))
}
fhttp.Serve(port, debugpath)
}
// Report starts the browsing only UI server on the given port.
// Similar to Serve with only the read only part.
func Report(port int, staticRsrcDir string, datadir string) {
extraBrowseLabel = ", report only limited UI"
httpPort = port
uiPath = "/"
dataDir = datadir
fmt.Printf("Browse only UI starting - visit:\nhttp://localhost:%d/\n", port)
logoPath = periodic.Version + "/static/img/logo.svg"
chartJSPath = periodic.Version + "/static/js/Chart.min.js"
staticRsrcDir = getResourcesDir(staticRsrcDir)
fs := http.FileServer(http.Dir(staticRsrcDir))
prefix := uiPath + periodic.Version
http.Handle(prefix+"/static/", LogAndAddCacheControl(http.StripPrefix(prefix, fs)))
var err error
browseTemplate, err = template.ParseFiles(path.Join(staticRsrcDir, "templates/browse.html"))
if err != nil {
log.Critf("Unable to parse browse template: %v", err)
} else {
http.HandleFunc(uiPath, BrowseHandler)
}
fsd := http.FileServer(http.Dir(dataDir))
http.Handle(uiPath+"data/", LogAndFilterDataRequest(http.StripPrefix(uiPath+"data", fsd)))
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
log.Critf("Error starting report server: %v", err)
}
}
// -- Redirection to https feature --
// RedirectToHTTPSHandler handler sends a redirect to same URL with https.
func RedirectToHTTPSHandler(w http.ResponseWriter, r *http.Request) {
dest := "https://" + r.Host + r.URL.String()
LogRequest(r, "Redirecting to "+dest)
http.Redirect(w, r, dest, http.StatusSeeOther)
}
// RedirectToHTTPS Sets up a redirector to https on the given port.
// (Do not create a loop, make sure this is addressed from an ingress)
func RedirectToHTTPS(port int) {
m := http.NewServeMux()
m.HandleFunc("/", RedirectToHTTPSHandler)
s := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: m,
}
fmt.Printf("Https redirector running on %v\n", s.Addr)
if err := s.ListenAndServe(); err != nil {
log.Critf("Error starting report server: %v", err)
}
fmt.Printf("Not reached, https redirector exiting - was on %v\n", s.Addr)
}