~humaid/ns2-trace-go

ref: v0.1 ns2-trace-go/main.go -rw-r--r-- 5.5 KiB
a284d8fdHumaid AlQassimi Add AGPL license 1 year, 9 months ago
                                                                                
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
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"github.com/go-macaron/binding"
	chart "github.com/wcharczuk/go-chart"
	"github.com/wcharczuk/go-chart/drawing"
	"gopkg.in/macaron.v1"
	"html/template"
	"log"
	"math/rand"
	"mime/multipart"
	"net/http"
	"os"
	"sort"
	"strconv"
)

var Analysises map[string]Analysis

type Analysis struct {
	Traces      []*TraceItem
	JitterStats []*JitterStat
	Stats       TraceStats
}

func main() {
	port := "4000"

	if os.Getenv("PORT") != "" {
		port = os.Getenv("PORT")
	}

	Analysises = make(map[string]Analysis)
	m := macaron.Classic()
	m.Use(macaron.Renderer())

	m.Get("/", func(ctx *macaron.Context) {
		ctx.HTML(200, "index")
	})

	m.Post("/", binding.MultipartForm(SubmitForm{}), func(ctx *macaron.Context,
		form SubmitForm, errs binding.Errors) {
		if len(errs) > 0 {
			ctx.PlainText(400, []byte(fmt.Sprintf("Form binding error: %s", errs)))
			return
		}
		f, err := form.File.Open()
		if err != nil {
			ctx.PlainText(400, []byte("File uploaded cannot be opened"))
			return
		}
		defer f.Close()
		buf := bufio.NewScanner(f)

		// TODO make sure this ID does not already exist
		analysisID := fmt.Sprint(rand.Intn(899999) + 100000)
		var trace []*TraceItem
		trace, err = GetTracesFromBuffer(buf)
		if err != nil {
			ctx.PlainText(400, []byte(fmt.Sprintf("Failed to parse file: %s\n\nMake sure use use trace-full or namtrace-full when generating the file!", err)))
			return
		}
		jsChan := make(chan []*JitterStat, 1)
		statsChan := make(chan TraceStats, 1)
		go func() {
			jsChan <- CalculateJitters(trace)
		}()
		go func() {
			statsChan <- CalculateStats(trace)
		}()

		Analysises[analysisID] = Analysis{
			Traces:      trace,
			JitterStats: <-jsChan,
			Stats:       <-statsChan,
		}
		ctx.Redirect(fmt.Sprintf("/%s", analysisID))
	})
	m.Group("/:id", func() {
		m.Get("/", func(ctx *macaron.Context) {
			analysis, ok := Analysises[ctx.Params("id")]
			if !ok {
				ctx.PlainText(404, []byte("Analysis results does not exist"))
				return
			}
			ctx.Data["ID"] = ctx.Params("id")
			ctx.Data["Analysis"] = analysis
			ctx.HTML(200, "analysis")
		})
		m.Group("/:from/:to/:type", func() {
			m.Get("/data.json", func(ctx *macaron.Context) {
				analysis, ok := Analysises[ctx.Params("id")]
				if !ok {
					ctx.PlainText(404, []byte("Analysis results does not exist"))
					return
				}
				var from, to int
				var pType string = ctx.Params("type")
				var err error

				from, err = strconv.Atoi(ctx.Params("from"))
				if err != nil {
					ctx.PlainText(400, []byte("Malformed request parameters"))
					return
				}
				to, err = strconv.Atoi(ctx.Params("to"))
				if err != nil {
					ctx.PlainText(400, []byte("Malformed request parameters"))
					return
				}

				var st *JitterStat = nil
				for _, stat := range analysis.JitterStats {
					if stat.FromNode == from && stat.ToNode == to && stat.PacketType == pType {
						st = stat
					}
				}
				if st == nil {
					ctx.PlainText(404, []byte("The jitter stat requested does not exist"))
					return
				}
				var seqValues, jitterValues []float64

				for seq := range st.Jitter {
					seqValues = append(seqValues, float64(seq))
				}
				sort.Float64s(seqValues)

				for v := range seqValues {
					jitterValues = append(jitterValues, st.Jitter[v])
				}
				ctx.JSON(200, [][]float64{seqValues, jitterValues})
			})
			m.Get("/:zoom", func(ctx *macaron.Context) {
				analysis, ok := Analysises[ctx.Params("id")]
				if !ok {
					ctx.PlainText(404, []byte("Analysis results does not exist"))
					return
				}
				var from, to int
				var pType string = ctx.Params("type")
				var err error

				from, err = strconv.Atoi(ctx.Params("from"))
				if err != nil {
					ctx.PlainText(400, []byte("Malformed request parameters"))
					return
				}
				to, err = strconv.Atoi(ctx.Params("to"))
				if err != nil {
					ctx.PlainText(400, []byte("Malformed request parameters"))
					return
				}

				var st *JitterStat = nil
				for _, stat := range analysis.JitterStats {
					if stat.FromNode == from && stat.ToNode == to && stat.PacketType == pType {
						st = stat
					}
				}
				if st == nil {
					ctx.PlainText(404, []byte("The jitter stat requested does not exist"))
					return
				}

				ctx.Data["ID"] = ctx.Params("id")
				ctx.Data["Stat"] = st

				var seqValues, jitterValues []float64

				for seq := range st.Jitter {
					seqValues = append(seqValues, float64(seq))
				}
				sort.Float64s(seqValues)

				for v := range seqValues {
					jitterValues = append(jitterValues, st.Jitter[v])
				}

				graph := chart.Chart{
					XAxis: chart.XAxis{
						Name: "Sequence",
					},
					YAxis: chart.YAxis{
						Name: "Jitter",
					},
					Series: []chart.Series{
						chart.ContinuousSeries{
							Style: chart.Style{
								StrokeColor: drawing.ColorRed,
							},
							XValues: seqValues,
							YValues: jitterValues,
						},
					},
				}
				if ctx.Params("zoom") == "zoom" {
					graph.YAxis.Range = &chart.ContinuousRange{
						Min: -0.5,
						Max: 0.5,
					}
					ctx.Data["IsZoom"] = true
				}

				var imgBuf bytes.Buffer
				err = graph.Render(chart.SVG, &imgBuf)
				if err != nil {
					ctx.PlainText(500, []byte(fmt.Sprintf("Failed to generate jitter graph: %s", err)))
					return
				}

				ctx.Data["Graph"] = template.HTML(imgBuf.String())

				ctx.HTML(200, "jitter")
			})
		})
	})
	log.Println("Running on 0.0.0.0:" + port)
	log.Println(http.ListenAndServe("0.0.0.0:"+port, m))
}

// SubmitForm holds the POST submission form for uploading the trace file.
type SubmitForm struct {
	File *multipart.FileHeader `form:"file" binding:"Required"`
}