/
main.go
815 lines (779 loc) · 23.9 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
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime/pprof"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/google/gopacket/pcap"
"github.com/google/gopacket/pcapgo"
"github.com/spq/pkappa2/internal/index"
"github.com/spq/pkappa2/internal/index/manager"
"github.com/spq/pkappa2/internal/query"
"github.com/spq/pkappa2/internal/tools"
"github.com/spq/pkappa2/web"
)
var (
baseDir = flag.String("base_dir", "/tmp", "All paths are relative to this path")
pcapDir = flag.String("pcap_dir", "", "Path where pcaps will be stored")
indexDir = flag.String("index_dir", "", "Path where indexes will be stored")
snapshotDir = flag.String("snapshot_dir", "", "Path where snapshots will be stored")
stateDir = flag.String("state_dir", "", "Path where state files will be stored")
converterDir = flag.String("converter_dir", "./converters", "Path where converter executables are searched")
userPassword = flag.String("user_password", "", "HTTP auth password for users")
pcapPassword = flag.String("pcap_password", "", "HTTP auth password for pcaps")
listenAddress = flag.String("address", ":8080", "Listen address")
startupCpuprofile = flag.String("startup_cpuprofile", "", "write cpu profile to file")
)
func main() {
flag.Parse()
if *startupCpuprofile != "" {
f, err := os.Create(*startupCpuprofile)
if err != nil {
log.Fatalf("Failed to create profile folder %s: %v", *startupCpuprofile, err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatalf("Failed to start CPU profile: %v", err)
}
}
tools.AssertFolderRWXPermissions("base_dir", *baseDir)
mgr, err := manager.New(
filepath.Join(*baseDir, *pcapDir),
filepath.Join(*baseDir, *indexDir),
filepath.Join(*baseDir, *snapshotDir),
filepath.Join(*baseDir, *stateDir),
*converterDir,
)
if err != nil {
log.Fatalf("manager.New failed: %v", err)
}
defer mgr.Close()
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
go func() {
<-signals
log.Println("Interrupt received. Cleaning up...")
mgr.Close()
os.Exit(1)
}()
var server *http.Server
r := chi.NewRouter()
r.Use(middleware.SetHeader("Access-Control-Allow-Origin", "*"))
r.Use(middleware.SetHeader("Access-Control-Allow-Methods", "*"))
/*
r.Options(`/*`, func(w http.ResponseWriter, r *http.Request) {
for k, v := range headers {
w.Header().Set(k, v)
}
})
*/
checkBasicAuth := func(password string) func(http.Handler) http.Handler {
if password == "" {
return func(h http.Handler) http.Handler {
return h
}
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, pass, ok := r.BasicAuth()
if ok && pass == password {
next.ServeHTTP(w, r)
return
}
w.Header().Add("WWW-Authenticate", `Basic realm="realm"`)
w.WriteHeader(http.StatusUnauthorized)
})
}
}
rUser := r.With(checkBasicAuth(*userPassword))
rPcap := r.With(checkBasicAuth(*pcapPassword))
rPcap.Post("/upload/{filename:.+[.]pcap[ng]?}", func(w http.ResponseWriter, r *http.Request) {
filename := chi.URLParam(r, "filename")
if filename != filepath.Base(filename) {
http.Error(w, "Invalid filename", http.StatusBadRequest)
return
}
tools.AssertFolderRWXPermissions("pcap_dir", filepath.Join(*baseDir, *pcapDir))
fullFilename := filepath.Join(*baseDir, *pcapDir, filename)
dst, err := os.OpenFile(fullFilename, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
http.Error(w, "File already exists", http.StatusInternalServerError)
return
}
if _, err := io.Copy(dst, r.Body); err != nil {
http.Error(w, fmt.Sprintf("Error while storing file: %v", err), http.StatusInternalServerError)
if err := dst.Close(); err != nil {
log.Printf("Failed to close new pcap file in upload: %v", err)
}
if err := os.Remove(fullFilename); err != nil {
log.Printf("Failed to remove empty new pcap file in upload: %v", err)
}
return
}
if err := dst.Close(); err != nil {
http.Error(w, fmt.Sprintf("Error while storing file: %s", err), http.StatusInternalServerError)
if err := os.Remove(fullFilename); err != nil {
log.Printf("Failed to remove new pcap file in upload after failed save: %v", err)
}
return
}
mgr.ImportPcap(filename)
http.Error(w, "OK", http.StatusOK)
})
rUser.Mount("/debug", middleware.Profiler())
rUser.Get("/api/status.json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(mgr.Status()); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
}
})
rUser.Get("/api/pcaps.json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(mgr.KnownPcaps()); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
}
})
rUser.Get("/api/tags", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(mgr.ListTags()); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
}
})
rUser.Delete("/api/tags", func(w http.ResponseWriter, r *http.Request) {
s := r.URL.Query()["name"]
if len(s) != 1 {
http.Error(w, "`name` parameter missing", http.StatusBadRequest)
return
}
if err := mgr.DelTag(s[0]); err != nil {
http.Error(w, fmt.Sprintf("delete failed: %v", err), http.StatusBadRequest)
return
}
})
rUser.Put("/api/tags", func(w http.ResponseWriter, r *http.Request) {
n := r.URL.Query()["name"]
if len(n) != 1 || n[0] == "" {
http.Error(w, "`name` parameter missing or empty", http.StatusBadRequest)
return
}
c := r.URL.Query()["color"]
if len(c) != 1 || c[0] == "" {
http.Error(w, "`color` parameter missing or empty", http.StatusBadRequest)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := mgr.AddTag(n[0], c[0], string(body)); err != nil {
http.Error(w, fmt.Sprintf("add failed: %v", err), http.StatusBadRequest)
return
}
})
rUser.Patch("/api/tags", func(w http.ResponseWriter, r *http.Request) {
n := r.URL.Query()["name"]
if len(n) != 1 || n[0] == "" {
http.Error(w, "`name` parameter missing or empty", http.StatusBadRequest)
return
}
m := r.URL.Query()["method"]
if len(m) != 1 || m[0] == "" {
http.Error(w, "`method` parameter missing or empty", http.StatusBadRequest)
return
}
operation := manager.UpdateTagOperation(nil)
streamMarkMethod := manager.UpdateTagOperationMarkAddStream
switch m[0] {
case "mark_del":
streamMarkMethod = manager.UpdateTagOperationMarkDelStream
fallthrough
case "mark_add":
s := r.URL.Query()["stream"]
if len(s) == 0 {
http.Error(w, "`stream` parameter missing", http.StatusBadRequest)
return
}
streams := make([]uint64, 0, len(s))
for _, n := range s {
v, err := strconv.ParseUint(n, 10, 64)
if err != nil {
http.Error(w, fmt.Sprintf("invalid value for `stream` parameter: %q", n), http.StatusBadRequest)
return
}
streams = append(streams, v)
}
operation = streamMarkMethod(streams)
case "change_color":
c := r.URL.Query()["color"]
if len(c) != 1 || c[0] == "" {
http.Error(w, "`color` parameter missing or empty", http.StatusBadRequest)
return
}
operation = manager.UpdateTagOperationUpdateColor(c[0])
case "converter_set":
c := r.URL.Query()["converters"]
operation = manager.UpdateTagOperationSetConverter(c)
default:
http.Error(w, fmt.Sprintf("unknown `method`: %q", m[0]), http.StatusBadRequest)
return
}
if err := mgr.UpdateTag(n[0], operation); err != nil {
http.Error(w, fmt.Sprintf("update failed: %v", err), http.StatusBadRequest)
return
}
})
rUser.Get("/api/converters", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(mgr.ListConverters()); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
}
})
rUser.Get(`/api/converters/stderr/{name:.+}/{pid:\d+}`, func(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
pidStr := chi.URLParam(r, "pid")
pid, err := strconv.ParseInt(pidStr, 10, 64)
if err != nil {
http.Error(w, fmt.Sprintf("invalid process id %q failed: %v", pidStr, err), http.StatusBadRequest)
return
}
converterDetails, err := mgr.ConverterStderr(name, int(pid))
if err != nil {
http.Error(w, fmt.Sprintf("get converter stderr failed: %v", err), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(converterDetails); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
}
})
rUser.Delete("/api/converters/{name:.+}", func(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
if err := mgr.ResetConverter(name); err != nil {
http.Error(w, fmt.Sprintf("reset failed: %v", err), http.StatusBadRequest)
}
})
rUser.Get(`/api/download/{stream:\d+}.pcap`, func(w http.ResponseWriter, r *http.Request) {
streamIDStr := chi.URLParam(r, "stream")
streamID, err := strconv.ParseUint(streamIDStr, 10, 64)
if err != nil {
http.Error(w, fmt.Sprintf("invalid stream id %q failed: %v", streamIDStr, err), http.StatusBadRequest)
return
}
v := mgr.GetView()
defer v.Release()
streamContext, err := v.Stream(streamID)
if err != nil {
http.Error(w, fmt.Sprintf("Stream(%d) failed: %v", streamID, err), http.StatusInternalServerError)
return
}
if streamContext.Stream() == nil {
http.Error(w, fmt.Sprintf("Stream(%d) not found", streamID), http.StatusNotFound)
return
}
packets, err := streamContext.Stream().Packets()
if err != nil {
http.Error(w, fmt.Sprintf("Stream(%d).Packets() failed: %v", streamID, err), http.StatusInternalServerError)
return
}
knownPcaps := map[string]time.Time{}
for _, kp := range mgr.KnownPcaps() {
knownPcaps[kp.Filename] = kp.PacketTimestampMin
}
pcapFiles := map[string][]uint64{}
for _, p := range packets {
if _, ok := knownPcaps[p.PcapFilename]; !ok {
http.Error(w, fmt.Sprintf("Unknown pcap %q referenced", p.PcapFilename), http.StatusInternalServerError)
return
}
pcapFiles[p.PcapFilename] = append(pcapFiles[p.PcapFilename], p.PcapIndex)
}
usedPcapFiles := []string{}
for fn, packetIndexes := range pcapFiles {
sort.Slice(packetIndexes, func(i, j int) bool {
return packetIndexes[i] < packetIndexes[j]
})
usedPcapFiles = append(usedPcapFiles, fn)
}
sort.Slice(usedPcapFiles, func(i, j int) bool {
return knownPcaps[usedPcapFiles[i]].Before(knownPcaps[usedPcapFiles[j]])
})
w.Header().Set("Content-Type", "application/vnd.tcpdump.pcap")
pcapProducer := pcapgo.NewWriterNanos(w)
for i, fn := range usedPcapFiles {
handle, err := pcap.OpenOffline(filepath.Join(mgr.PcapDir, fn))
if err != nil {
http.Error(w, fmt.Sprintf("OpenOffline failed: %v", err), http.StatusInternalServerError)
return
}
defer handle.Close()
if i == 0 {
if err := pcapProducer.WriteFileHeader(uint32(handle.SnapLen()), handle.LinkType()); err != nil {
http.Error(w, fmt.Sprintf("WriteFileHeader failed: %v", err), http.StatusInternalServerError)
return
}
}
pos := uint64(0)
for _, p := range pcapFiles[fn] {
for {
data, ci, err := handle.ReadPacketData()
if err != nil {
http.Error(w, fmt.Sprintf("ReadPacketData failed: %v", err), http.StatusInternalServerError)
return
}
pos++
if p != pos-1 {
continue
}
if err := pcapProducer.WritePacket(ci, data); err != nil {
http.Error(w, fmt.Sprintf("WritePacket failed: %v", err), http.StatusInternalServerError)
return
}
break
}
}
}
})
rUser.Get(`/api/stream/{stream:\d+}.json`, func(w http.ResponseWriter, r *http.Request) {
streamIDStr := chi.URLParam(r, "stream")
streamID, err := strconv.ParseUint(streamIDStr, 10, 64)
if err != nil {
http.Error(w, fmt.Sprintf("invalid stream id %q failed: %v", streamIDStr, err), http.StatusBadRequest)
return
}
v := mgr.GetView()
defer v.Release()
streamContext, err := v.Stream(streamID)
if err != nil {
http.Error(w, fmt.Sprintf("Stream(%d) failed: %v", streamID, err), http.StatusInternalServerError)
return
}
if streamContext.Stream() == nil {
http.Error(w, fmt.Sprintf("stream %d not found", streamID), http.StatusNotFound)
return
}
converter := "auto"
if f := r.URL.Query()["converter"]; len(f) == 1 {
converter = f[0]
}
converters, err := streamContext.AllConverters()
if err != nil {
http.Error(w, fmt.Sprintf("AllConverters() failed: %v", err), http.StatusInternalServerError)
return
}
if converter == "auto" {
if len(converters) == 1 {
converter = converters[0]
} else {
converter = ""
}
} else if converter == "none" {
converter = ""
} else {
if !strings.HasPrefix(converter, "converter:") {
http.Error(w, fmt.Sprintf("invalid converter %q", converter), http.StatusBadRequest)
return
}
converter = converter[len("converter:"):]
}
data, err := streamContext.Data(converter)
if err != nil {
http.Error(w, fmt.Sprintf("Data(%q) failed: %v", converter, err), http.StatusInternalServerError)
return
}
tags, err := streamContext.AllTags()
if err != nil {
http.Error(w, fmt.Sprintf("AllTags() failed: %v", err), http.StatusInternalServerError)
return
}
// TODO: Send correct ClientBytes and ServerBytes when sending converter output.
response := struct {
Stream *index.Stream
Data []index.Data
Tags []string
Converters []string
ActiveConverter string
}{
Stream: streamContext.Stream(),
Data: data,
Tags: tags,
Converters: converters,
ActiveConverter: converter,
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
return
}
})
rUser.Post("/api/search.json", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
qq, err := query.Parse(string(body))
if err != nil {
w.Header().Set("Content-Type", "application/json")
response := struct {
Error string
}{
Error: err.Error(),
}
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
return
}
return
}
page := uint(0)
if s := r.URL.Query()["page"]; len(s) == 1 {
n, err := strconv.ParseUint(s[0], 10, 64)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid page %q: %v", s[0], err), http.StatusBadRequest)
return
}
page = uint(n)
}
response := struct {
Debug []string
Results []struct {
Stream *index.Stream
Tags []string
}
Offset uint
MoreResults bool
}{
Debug: qq.Debug,
Results: []struct {
Stream *index.Stream
Tags []string
}{},
}
v := mgr.GetView()
defer v.Release()
hasMore, offset, err := v.SearchStreams(qq, func(c manager.StreamContext) error {
tags, err := c.AllTags()
if err != nil {
return err
}
response.Results = append(response.Results, struct {
Stream *index.Stream
Tags []string
}{
Stream: c.Stream(),
Tags: tags,
})
return nil
}, manager.Limit(100, page), manager.PrefetchAllTags())
if err != nil {
http.Error(w, fmt.Sprintf("SearchStreams failed: %v", err), http.StatusInternalServerError)
return
}
response.MoreResults = hasMore
response.Offset = offset
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
return
}
})
rUser.Get("/api/graph.json", func(w http.ResponseWriter, r *http.Request) {
var min, max time.Time
delta := 1 * time.Minute
if s := r.URL.Query()["delta"]; len(s) == 1 {
d, err := time.ParseDuration(s[0])
if err != nil || d <= 0 {
http.Error(w, fmt.Sprintf("Invalid delta %q: %v", s[0], err), http.StatusBadRequest)
return
}
delta = d
}
if s := r.URL.Query()["min"]; len(s) == 1 {
t, err := time.Parse("1", s[0])
if err != nil {
http.Error(w, fmt.Sprintf("Invalid min time %q: %v", s[0], err), http.StatusBadRequest)
return
}
min = t.Truncate(delta)
}
if s := r.URL.Query()["max"]; len(s) == 1 {
t, err := time.Parse("1", s[0])
if err != nil {
http.Error(w, fmt.Sprintf("Invalid max time %q: %v", s[0], err), http.StatusBadRequest)
return
}
max = t.Truncate(delta)
}
filter := (*query.Query)(nil)
if qs := r.URL.Query()["query"]; len(qs) == 1 {
q, err := query.Parse(qs[0])
if err != nil {
http.Error(w, fmt.Sprintf("Invalid query %q: %v", qs[0], err), http.StatusBadRequest)
return
}
if q.Grouping != nil {
http.Error(w, fmt.Sprintf("Invalid query %q: grouping not supported", qs[0]), http.StatusBadRequest)
return
}
filter = q
}
type (
Aspect uint8
)
const (
AspectAnchor Aspect = 0b0001
AspectAnchorFirst Aspect = 0b0000
AspectAnchorLast Aspect = 0b0001
AspectType Aspect = 0b1110
AspectTypeConnections Aspect = 0b0000
AspectTypeDuration Aspect = 0b0010
AspectTypeBytes Aspect = 0b0100
AspectTypeClientBytes Aspect = 0b0110
AspectTypeServerBytes Aspect = 0b1000
)
aspects := []Aspect(nil)
for _, a := range r.URL.Query()["aspect"] {
if !func() bool {
as := strings.Split(a, "@")
if len(as) != 1 && len(as) != 2 {
return false
}
aspect := Aspect(0)
if v, ok := map[string]Aspect{
"connections": AspectTypeConnections,
"duration": AspectTypeDuration,
"bytes": AspectTypeBytes,
"cbytes": AspectTypeClientBytes,
"sbytes": AspectTypeServerBytes,
}[as[0]]; ok {
aspect |= v
} else {
return false
}
if len(as) == 2 {
if v, ok := map[string]Aspect{
"first": AspectAnchorFirst,
"last": AspectAnchorLast,
}[as[1]]; ok {
aspect |= v
} else {
return false
}
}
aspects = append(aspects, aspect)
return true
}() {
http.Error(w, fmt.Sprintf("Invalid aspect %q: %v", a, err), http.StatusBadRequest)
return
}
}
if len(aspects) == 0 {
aspects = []Aspect{AspectAnchorFirst | AspectTypeConnections}
}
sort.Slice(aspects, func(i, j int) bool {
a, b := aspects[i], aspects[j]
if (a^b)&AspectAnchor != 0 {
return a&AspectAnchor < b&AspectAnchor
}
return a < b
})
groupingTags := r.URL.Query()["tag"]
v := mgr.GetView()
defer v.Release()
referenceTime, err := v.ReferenceTime()
if err != nil {
http.Error(w, fmt.Sprintf("ReferenceTime failed: %v", err), http.StatusInternalServerError)
return
}
type (
tagInfo struct {
name string
used map[int]int
}
)
tagInfos := []tagInfo(nil)
for _, tn := range groupingTags {
tagInfos = append(tagInfos, tagInfo{
name: tn,
used: make(map[int]int),
})
}
type tagGroup struct {
extends int
extendedBy string
counts map[time.Duration][]uint64
}
tagGroups := []tagGroup{{}}
handleStream := func(c manager.StreamContext) error {
tagGroupId := 0
for _, ti := range tagInfos {
hasTag, err := c.HasTag(ti.name)
if err != nil {
return err
}
if !hasTag {
continue
}
newTagGroupId, ok := ti.used[tagGroupId]
if !ok {
newTagGroupId = len(tagGroups)
tagGroups = append(tagGroups, tagGroup{
extends: tagGroupId,
extendedBy: ti.name,
})
ti.used[tagGroupId] = newTagGroupId
}
tagGroupId = newTagGroupId
}
s := c.Stream()
tagGroup := &tagGroups[tagGroupId]
if tagGroup.counts == nil {
tagGroup.counts = make(map[time.Duration][]uint64)
}
var t time.Time
skip := false
countsEntry := []uint64(nil)
countsKey := time.Duration(0)
for i, a := range aspects {
if i == 0 || (aspects[i-1]^a)&AspectAnchor != 0 {
if i != 0 {
tagGroup.counts[countsKey] = countsEntry
}
switch a & AspectAnchor {
case AspectAnchorFirst:
t = s.FirstPacket()
case AspectAnchorLast:
t = s.LastPacket()
}
t = t.Truncate(delta)
if skip = (!min.IsZero() && min.After(t)) || (!max.IsZero() && max.Before(t)); skip {
continue
}
ok := false
countsKey = t.Sub(referenceTime)
if countsEntry, ok = tagGroup.counts[countsKey]; !ok {
countsEntry = make([]uint64, len(aspects))
}
} else if skip {
continue
}
d := uint64(0)
switch a & AspectType {
case AspectTypeConnections:
d = 1
case AspectTypeBytes:
d = s.ClientBytes + s.ServerBytes
case AspectTypeClientBytes:
d = s.ClientBytes
case AspectTypeServerBytes:
d = s.ServerBytes
case AspectTypeDuration:
d = s.LastPacketTimeNS - s.FirstPacketTimeNS
}
countsEntry[i] += d
}
tagGroup.counts[countsKey] = countsEntry
return nil
}
if filter != nil {
_, _, err := v.SearchStreams(filter, handleStream, manager.PrefetchTags(groupingTags))
if err != nil {
http.Error(w, fmt.Sprintf("SearchStreams failed: %v", err), http.StatusInternalServerError)
return
}
} else {
err := v.AllStreams(handleStream, manager.PrefetchTags(groupingTags))
if err != nil {
http.Error(w, fmt.Sprintf("AllStreams failed: %v", err), http.StatusInternalServerError)
return
}
}
response := struct {
Min, Max time.Time
Delta time.Duration
Aspects []string
Data []struct {
Tags []string
Data [][]uint64
}
}{}
response.Delta = delta
for _, a := range aspects {
response.Aspects = append(response.Aspects, fmt.Sprintf("%s@%s", map[Aspect]string{
AspectTypeConnections: "connections",
AspectTypeDuration: "duration",
AspectTypeBytes: "bytes",
AspectTypeClientBytes: "cbytes",
AspectTypeServerBytes: "sbytes",
}[(a&AspectType)], []string{
"first", "last",
}[(a&AspectAnchor)/AspectAnchor]))
}
for _, tg := range tagGroups {
for d := range tg.counts {
t := referenceTime.Add(d)
if response.Min.IsZero() || response.Min.After(t) {
response.Min = t
}
if response.Max.IsZero() || response.Max.Before(t) {
response.Max = t
}
}
}
for tagGroupId := range tagGroups {
tg := &tagGroups[tagGroupId]
data := [][]uint64(nil)
for d, v := range tg.counts {
t := referenceTime.Add(d).Sub(response.Min) / delta
data = append(data, append([]uint64{uint64(t)}, v...))
}
sort.Slice(data, func(i, j int) bool {
return data[i][0] < data[j][0]
})
tagsList := []string{}
for tagGroupId != 0 {
tagGroupId = tg.extends
tagsList = append(tagsList, tg.extendedBy)
tg = &tagGroups[tagGroupId]
}
response.Data = append(response.Data, struct {
Tags []string
Data [][]uint64
}{
Tags: tagsList,
Data: data,
})
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, fmt.Sprintf("Encode failed: %v", err), http.StatusInternalServerError)
return
}
})
rUser.Get("/*", http.FileServer(http.FS(&web.FS{})).ServeHTTP)
server = &http.Server{
Addr: *listenAddress,
Handler: r,
}
log.Println("Ready to serve...")
if *startupCpuprofile != "" {
pprof.StopCPUProfile()
log.Printf("CPU profile written to %s", *startupCpuprofile)
}
if err := server.ListenAndServe(); err != nil {
log.Printf("ListenAndServe failed: %v", err)
}
}