aboutsummaryrefslogtreecommitdiff
path: root/frontend/src/components/Timeline.jsx
blob: faaa8de3492ee1e4d2417ec5edec587f2c69b64f (plain) (blame)
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
/*
 * This file is part of caronte (https://github.com/eciavatta/caronte).
 * Copyright (c) 2020 Emiliano Ciavatta.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React, { Component } from "react";
import { withRouter } from "react-router-dom";

import ChartContainer from "react-timeseries-charts/lib/components/ChartContainer";
import ChartRow from "react-timeseries-charts/lib/components/ChartRow";
import Charts from "react-timeseries-charts/lib/components/Charts";
import LineChart from "react-timeseries-charts/lib/components/LineChart";
import MultiBrush from "react-timeseries-charts/lib/components/MultiBrush";
import Resizable from "react-timeseries-charts/lib/components/Resizable";
import YAxis from "react-timeseries-charts/lib/components/YAxis";
import { TimeRange, TimeSeries } from "pondjs";
import styler from "react-timeseries-charts/lib/js/styler";

import backend from "../backend";
import dispatcher from "../dispatcher";
import log from "../log";
import ChoiceField from "./fields/ChoiceField";
import "./Timeline.scss";

const minutes = 60 * 1000;
const maxTimelineRange = 24 * 60 * minutes;
import classNames from "classnames";

const leftSelectionPaddingMultiplier = 24;
const rightSelectionPaddingMultiplier = 8;

class Timeline extends Component {
  state = {
    metric: "connections_per_service",
  };

  constructor() {
    super();

    this.disableTimeSeriesChanges = false;
    this.selectionTimeout = null;
  }

  componentDidMount() {
    const urlParams = new URLSearchParams(this.props.location.search);
    this.setState({
      servicePortFilter: urlParams.get("service_port") || null,
      matchedRulesFilter: urlParams.getAll("matched_rules") || null,
    });

    this.loadStatistics(this.state.metric).then(() =>
      log.debug("Statistics loaded after mount")
    );
    dispatcher.register(
      "connections_filters",
      this.handleConnectionsFiltersCallback
    );
    dispatcher.register("connection_updates", this.handleConnectionUpdates);
    dispatcher.register("notifications", this.handleNotifications);
    dispatcher.register("pulse_timeline", this.handlePulseTimeline);
  }

  componentWillUnmount() {
    dispatcher.unregister(this.handleConnectionsFiltersCallback);
    dispatcher.unregister(this.handleConnectionUpdates);
    dispatcher.unregister(this.handleNotifications);
    dispatcher.unregister(this.handlePulseTimeline);
  }

  loadStatistics = async (metric) => {
    const urlParams = new URLSearchParams();
    urlParams.set("metric", metric);

    let columns = [];
    if (metric === "matched_rules") {
      let rules = await this.loadRules();
      if (this.state.matchedRulesFilter.length > 0) {
        this.state.matchedRulesFilter.forEach((id) => {
          urlParams.append("rules_ids", id);
        });
        columns = this.state.matchedRulesFilter;
      } else {
        columns = rules.map((r) => r.id);
      }
    } else {
      let services = await this.loadServices();
      const filteredPort = this.state.servicePortFilter;
      if (filteredPort && services[filteredPort]) {
        const service = services[filteredPort];
        services = {};
        services[filteredPort] = service;
      }

      columns = Object.keys(services);
      columns.forEach((port) => urlParams.append("ports", port));
    }

    const metrics = (await backend.get("/api/statistics?" + urlParams)).json;
    if (metrics.length === 0) {
      return;
    }

    const zeroFilledMetrics = [];
    const toTime = (m) => new Date(m["range_start"]).getTime();

    let i;
    let timeStart = toTime(metrics[0]) - minutes;
    for (i = 0; timeStart < 0 && i < metrics.length; i++) {
      // workaround to remove negative timestamps :(
      timeStart = toTime(metrics[i]) - minutes;
    }

    let timeEnd = toTime(metrics[metrics.length - 1]) + minutes;
    if (timeEnd - timeStart > maxTimelineRange) {
      timeEnd = timeStart + maxTimelineRange;

      const now = new Date().getTime();
      if (
        !this.lastDisplayNotificationTime ||
        this.lastDisplayNotificationTime + minutes < now
      ) {
        this.lastDisplayNotificationTime = now;
        dispatcher.dispatch("notifications", { event: "timeline.range.large" });
      }
    }

    for (let interval = timeStart; interval <= timeEnd; interval += minutes) {
      if (i < metrics.length && interval === toTime(metrics[i])) {
        const m = metrics[i++];
        m["range_start"] = new Date(m["range_start"]);
        zeroFilledMetrics.push(m);
      } else {
        const m = {};
        m["range_start"] = new Date(interval);
        m[metric] = {};
        columns.forEach((c) => (m[metric][c] = 0));
        zeroFilledMetrics.push(m);
      }
    }

    const series = new TimeSeries({
      name: "statistics",
      columns: ["time"].concat(columns),
      points: zeroFilledMetrics.map((m) =>
        [m["range_start"]].concat(
          columns.map((c) =>
            metric in m && m[metric] != null ? m[metric][c] || 0 : 0
          )
        )
      ),
    });

    const start = series.range().begin();
    const end = series.range().end();

    this.setState({
      metric,
      series,
      timeRange: new TimeRange(start, end),
      columns,
      start,
      end,
    });
  };

  loadServices = async () => {
    const services = (await backend.get("/api/services")).json;
    this.setState({ services });
    return services;
  };

  loadRules = async () => {
    const rules = (await backend.get("/api/rules")).json;
    this.setState({ rules });
    return rules;
  };

  createStyler = () => {
    if (this.state.metric === "matched_rules") {
      return styler(
        this.state.rules.map((rule) => {
          return { key: rule.id, color: rule.color, width: 2 };
        })
      );
    } else {
      return styler(
        Object.keys(this.state.services).map((port) => {
          return {
            key: port,
            color: this.state.services[port].color,
            width: 2,
          };
        })
      );
    }
  };

  handleTimeRangeChange = (timeRange) => {
    if (!this.disableTimeSeriesChanges) {
      this.setState({ timeRange });
    }
  };

  handleSelectionChange = (timeRange) => {
    this.disableTimeSeriesChanges = true;

    this.setState({ selection: timeRange });
    if (this.selectionTimeout) {
      clearTimeout(this.selectionTimeout);
    }
    this.selectionTimeout = setTimeout(() => {
      dispatcher.dispatch("timeline_updates", {
        from: timeRange.begin(),
        to: timeRange.end(),
      });
      this.selectionTimeout = null;
      this.disableTimeSeriesChanges = false;
    }, 1000);
  };

  handleConnectionsFiltersCallback = (payload) => {
    if (
      "service_port" in payload &&
      this.state.servicePortFilter !== payload["service_port"]
    ) {
      this.setState({ servicePortFilter: payload["service_port"] });
      this.loadStatistics(this.state.metric).then(() =>
        log.debug("Statistics reloaded after service port changed")
      );
    }
    if (
      "matched_rules" in payload &&
      this.state.matchedRulesFilter !== payload["matched_rules"]
    ) {
      this.setState({ matchedRulesFilter: payload["matched_rules"] });
      this.loadStatistics(this.state.metric).then(() =>
        log.debug("Statistics reloaded after matched rules changed")
      );
    }
  };

  handleConnectionUpdates = (payload) => {
    if (
      payload.from >= this.state.start &&
      payload.from < payload.to &&
      payload.to <= this.state.end
    ) {
      this.setState({
        selection: new TimeRange(payload.from, payload.to),
      });
      this.adjustSelection();
    }
  };

  handleNotifications = (payload) => {
    if (
      payload.event === "services.edit" &&
      this.state.metric !== "matched_rules"
    ) {
      this.loadStatistics(this.state.metric).then(() =>
        log.debug("Statistics reloaded after services updates")
      );
    } else if (
      payload.event.startsWith("rules") &&
      this.state.metric === "matched_rules"
    ) {
      this.loadStatistics(this.state.metric).then(() =>
        log.debug("Statistics reloaded after rules updates")
      );
    } else if (payload.event === "pcap.completed") {
      this.loadStatistics(this.state.metric).then(() =>
        log.debug("Statistics reloaded after pcap processed")
      );
    }
  };

  handlePulseTimeline = (payload) => {
    this.setState({ pulseTimeline: true });
    setTimeout(() => this.setState({ pulseTimeline: false }), payload.duration);
  };

  adjustSelection = () => {
    const seriesRange = this.state.series.range();
    const selection = this.state.selection;
    const delta = selection.end() - selection.begin();
    const start = Math.max(
      selection.begin().getTime() - delta * leftSelectionPaddingMultiplier,
      seriesRange.begin().getTime()
    );
    const end = Math.min(
      selection.end().getTime() + delta * rightSelectionPaddingMultiplier,
      seriesRange.end().getTime()
    );
    this.setState({ timeRange: new TimeRange(start, end) });
  };

  aggregateSeries = (func) => {
    const values = this.state.series
      .columns()
      .map((c) => this.state.series[func](c));
    return Math[func](...values);
  };

  render() {
    if (!this.state.series) {
      return null;
    }

    return (
      <footer className="footer">
        <div
          className={classNames("time-line", {
            "pulse-timeline": this.state.pulseTimeline,
          })}
        >
          <Resizable>
            <ChartContainer
              timeRange={this.state.timeRange}
              enableDragZoom={false}
              paddingTop={5}
              minDuration={60000}
              maxTime={this.state.end}
              minTime={this.state.start}
              paddingLeft={0}
              paddingRight={0}
              paddingBottom={0}
              enablePanZoom={true}
              utc={false}
              onTimeRangeChanged={this.handleTimeRangeChange}
            >
              <ChartRow height={this.props.height - 70}>
                <YAxis
                  id="axis1"
                  hideAxisLine
                  min={this.aggregateSeries("min")}
                  max={this.aggregateSeries("max")}
                  width="35"
                  type="linear"
                  transition={300}
                />
                <Charts>
                  <LineChart
                    axis="axis1"
                    series={this.state.series}
                    columns={this.state.columns}
                    style={this.createStyler()}
                    interpolation="curveBasis"
                  />

                  <MultiBrush
                    timeRanges={[this.state.selection]}
                    allowSelectionClear={false}
                    allowFreeDrawing={false}
                    onTimeRangeChanged={this.handleSelectionChange}
                  />
                </Charts>
              </ChartRow>
            </ChartContainer>
          </Resizable>

          <div className="metric-selection">
            <ChoiceField
              inline
              small
              keys={[
                "connections_per_service",
                "client_bytes_per_service",
                "server_bytes_per_service",
                "duration_per_service",
                "matched_rules",
              ]}
              values={[
                "connections_per_service",
                "client_bytes_per_service",
                "server_bytes_per_service",
                "duration_per_service",
                "matched_rules",
              ]}
              onChange={(metric) =>
                this.loadStatistics(metric).then(() =>
                  log.debug("Statistics loaded after metric changes")
                )
              }
              value={this.state.metric}
            />
          </div>
        </div>
      </footer>
    );
  }
}

export default withRouter(Timeline);