From f11e5d9e55c963109af8b8517c7790bf2eb7cac8 Mon Sep 17 00:00:00 2001 From: Emiliano Ciavatta Date: Sat, 3 Oct 2020 17:01:32 +0200 Subject: Add title page window titles --- frontend/src/views/App.js | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'frontend/src/views') diff --git a/frontend/src/views/App.js b/frontend/src/views/App.js index fb4454c..abd5209 100644 --- a/frontend/src/views/App.js +++ b/frontend/src/views/App.js @@ -18,6 +18,14 @@ class App extends Component { componentDidMount() { backend.get("/api/services").then(_ => this.setState({configured: true})); + + setInterval(() => { + if (document.title.endsWith("❚")) { + document.title = document.title.slice(0, -1); + } else { + document.title += "❚"; + } + }, 500); } render() { -- cgit v1.2.3-70-g09d2 From e905618113309eaba7227ff1328a20f6846e4afd Mon Sep 17 00:00:00 2001 From: Emiliano Ciavatta Date: Mon, 5 Oct 2020 23:46:18 +0200 Subject: Implement timeline --- application_context.go | 2 + application_router.go | 22 +- connection_handler.go | 26 ++ connections_controller.go | 52 ++-- frontend/package.json | 3 + .../src/components/filters/FiltersDefinitions.js | 86 +++--- frontend/src/components/panels/MainPane.js | 34 +-- frontend/src/globals.js | 5 + frontend/src/log.js | 7 + frontend/src/views/App.js | 18 +- frontend/src/views/Connections.js | 158 +++++++---- frontend/src/views/Connections.scss | 52 ++-- frontend/src/views/Footer.js | 173 +++++++++++- frontend/src/views/Footer.scss | 17 +- frontend/yarn.lock | 312 +++++++++++++++++++-- statistics_controller.go | 71 +++++ storage.go | 31 ++ 17 files changed, 850 insertions(+), 219 deletions(-) create mode 100644 frontend/src/globals.js create mode 100644 frontend/src/log.js create mode 100644 statistics_controller.go (limited to 'frontend/src/views') diff --git a/application_context.go b/application_context.go index e4be74d..6ea449d 100644 --- a/application_context.go +++ b/application_context.go @@ -20,6 +20,7 @@ type ApplicationContext struct { ConnectionsController ConnectionsController ServicesController *ServicesController ConnectionStreamsController ConnectionStreamsController + StatisticsController StatisticsController IsConfigured bool } @@ -93,5 +94,6 @@ func (sm *ApplicationContext) configure() { sm.ServicesController = NewServicesController(sm.Storage) sm.ConnectionsController = NewConnectionsController(sm.Storage, sm.ServicesController) sm.ConnectionStreamsController = NewConnectionStreamsController(sm.Storage) + sm.StatisticsController = NewStatisticsController(sm.Storage) sm.IsConfigured = true } diff --git a/application_router.go b/application_router.go index 501956b..8b5e32f 100644 --- a/application_router.go +++ b/application_router.go @@ -119,7 +119,7 @@ func CreateApplicationRouter(applicationContext *ApplicationContext) *gin.Engine flushAllValue, isPresent := c.GetPostForm("flush_all") flushAll := isPresent && strings.ToLower(flushAllValue) == "true" fileName := fmt.Sprintf("%v-%s", time.Now().UnixNano(), fileHeader.Filename) - if err := c.SaveUploadedFile(fileHeader, ProcessingPcapsBasePath + fileName); err != nil { + if err := c.SaveUploadedFile(fileHeader, ProcessingPcapsBasePath+fileName); err != nil { log.WithError(err).Panic("failed to save uploaded file") } @@ -147,7 +147,7 @@ func CreateApplicationRouter(applicationContext *ApplicationContext) *gin.Engine } fileName := fmt.Sprintf("%v-%s", time.Now().UnixNano(), filepath.Base(request.File)) - if err := CopyFile(ProcessingPcapsBasePath + fileName, request.File); err != nil { + if err := CopyFile(ProcessingPcapsBasePath+fileName, request.File); err != nil { log.WithError(err).Panic("failed to copy pcap file") } if sessionID, err := applicationContext.PcapImporter.ImportPcap(fileName, request.FlushAll); err != nil { @@ -179,9 +179,9 @@ func CreateApplicationRouter(applicationContext *ApplicationContext) *gin.Engine sessionID := c.Param("id") if _, isPresent := applicationContext.PcapImporter.GetSession(sessionID); isPresent { if FileExists(PcapsBasePath + sessionID + ".pcap") { - c.FileAttachment(PcapsBasePath + sessionID + ".pcap", sessionID[:16] + ".pcap") + c.FileAttachment(PcapsBasePath+sessionID+".pcap", sessionID[:16]+".pcap") } else if FileExists(PcapsBasePath + sessionID + ".pcapng") { - c.FileAttachment(PcapsBasePath + sessionID + ".pcapng", sessionID[:16] + ".pcapng") + c.FileAttachment(PcapsBasePath+sessionID+".pcapng", sessionID[:16]+".pcapng") } else { log.WithField("sessionID", sessionID).Panic("pcap file not exists") } @@ -289,9 +289,17 @@ func CreateApplicationRouter(applicationContext *ApplicationContext) *gin.Engine unprocessableEntity(c, err) } }) - } + api.GET("/statistics", func(c *gin.Context) { + var filter StatisticsFilter + if err := c.ShouldBindQuery(&filter); err != nil { + badRequest(c, err) + return + } + success(c, applicationContext.StatisticsController.GetStatistics(c, filter)) + }) + } return router } @@ -352,3 +360,7 @@ func unprocessableEntity(c *gin.Context, err error) { func notFound(c *gin.Context, obj interface{}) { c.JSON(http.StatusNotFound, obj) } + +func serverError(c *gin.Context, err error) { + c.JSON(http.StatusInternalServerError, UnorderedDocument{"result": "error", "error": err.Error()}) +} diff --git a/connection_handler.go b/connection_handler.go index ffe4fac..3d38531 100644 --- a/connection_handler.go +++ b/connection_handler.go @@ -2,6 +2,7 @@ package main import ( "encoding/binary" + "fmt" "github.com/flier/gohs/hyperscan" "github.com/google/gopacket" "github.com/google/gopacket/tcpassembly" @@ -225,6 +226,31 @@ func (ch *connectionHandlerImpl) Complete(handler *StreamHandler) { log.WithError(err).WithField("connection", connection).Error("failed to update all connections streams") } } + + ch.UpdateStatistics(connection) +} + +func (ch *connectionHandlerImpl) UpdateStatistics(connection Connection) { + rangeStart := connection.StartedAt.Unix() / 60 // group statistic records by minutes + duration := connection.ClosedAt.Sub(connection.StartedAt) + // if one of the two parts doesn't close connection, the duration is +infinity or -infinity + if duration.Hours() > 1 || duration.Hours() < -1 { + duration = 0 + } + servicePort := connection.DestinationPort + + var results interface{} + if _, err := ch.Storage().Update(Statistics).Upsert(&results). + Filter(OrderedDocument{{"_id", time.Unix(rangeStart*60, 0)}}).OneComplex(UnorderedDocument{ + "$inc": UnorderedDocument{ + fmt.Sprintf("connections_per_service.%d", servicePort): 1, + fmt.Sprintf("client_bytes_per_service.%d", servicePort): connection.ClientBytes, + fmt.Sprintf("server_bytes_per_service.%d", servicePort): connection.ServerBytes, + fmt.Sprintf("duration_per_service.%d", servicePort): duration.Milliseconds(), + }, + }); err != nil { + log.WithError(err).WithField("connection", connection).Error("failed to update connection statistics") + } } func (ch *connectionHandlerImpl) Storage() Storage { diff --git a/connections_controller.go b/connections_controller.go index 2773506..2894193 100644 --- a/connections_controller.go +++ b/connections_controller.go @@ -31,40 +31,40 @@ type Connection struct { } type ConnectionsFilter struct { - From string `form:"from" binding:"omitempty,hexadecimal,len=24"` - To string `form:"to" binding:"omitempty,hexadecimal,len=24"` - ServicePort uint16 `form:"service_port"` - ClientAddress string `form:"client_address" binding:"omitempty,ip"` - ClientPort uint16 `form:"client_port"` - MinDuration uint `form:"min_duration"` - MaxDuration uint `form:"max_duration" binding:"omitempty,gtefield=MinDuration"` - MinBytes uint `form:"min_bytes"` - MaxBytes uint `form:"max_bytes" binding:"omitempty,gtefield=MinBytes"` - StartedAfter int64 `form:"started_after" ` - StartedBefore int64 `form:"started_before" binding:"omitempty,gtefield=StartedAfter"` - ClosedAfter int64 `form:"closed_after" ` - ClosedBefore int64 `form:"closed_before" binding:"omitempty,gtefield=ClosedAfter"` - Hidden bool `form:"hidden"` - Marked bool `form:"marked"` + From string `form:"from" binding:"omitempty,hexadecimal,len=24"` + To string `form:"to" binding:"omitempty,hexadecimal,len=24"` + ServicePort uint16 `form:"service_port"` + ClientAddress string `form:"client_address" binding:"omitempty,ip"` + ClientPort uint16 `form:"client_port"` + MinDuration uint `form:"min_duration"` + MaxDuration uint `form:"max_duration" binding:"omitempty,gtefield=MinDuration"` + MinBytes uint `form:"min_bytes"` + MaxBytes uint `form:"max_bytes" binding:"omitempty,gtefield=MinBytes"` + StartedAfter int64 `form:"started_after" ` + StartedBefore int64 `form:"started_before" binding:"omitempty,gtefield=StartedAfter"` + ClosedAfter int64 `form:"closed_after" ` + ClosedBefore int64 `form:"closed_before" binding:"omitempty,gtefield=ClosedAfter"` + Hidden bool `form:"hidden"` + Marked bool `form:"marked"` MatchedRules []string `form:"matched_rules" binding:"dive,hexadecimal,len=24"` - Limit int64 `form:"limit"` + Limit int64 `form:"limit"` } type ConnectionsController struct { - storage Storage + storage Storage servicesController *ServicesController } func NewConnectionsController(storage Storage, servicesController *ServicesController) ConnectionsController { return ConnectionsController{ - storage: storage, + storage: storage, servicesController: servicesController, } } func (cc ConnectionsController) GetConnections(c context.Context, filter ConnectionsFilter) []Connection { var connections []Connection - query := cc.storage.Find(Connections).Context(c).Sort("_id", false) + query := cc.storage.Find(Connections).Context(c) from, _ := RowIDFromHex(filter.From) if !from.IsZero() { @@ -73,6 +73,8 @@ func (cc ConnectionsController) GetConnections(c context.Context, filter Connect to, _ := RowIDFromHex(filter.To) if !to.IsZero() { query = query.Filter(OrderedDocument{{"_id", UnorderedDocument{"$gt": to}}}) + } else { + query = query.Sort("_id", false) } if filter.ServicePort > 0 { query = query.Filter(OrderedDocument{{"port_dst", filter.ServicePort}}) @@ -146,6 +148,10 @@ func (cc ConnectionsController) GetConnections(c context.Context, filter Connect } } + if !to.IsZero() { + connections = reverseConnections(connections) + } + return connections } @@ -178,3 +184,11 @@ func (cc ConnectionsController) setProperty(c context.Context, id RowID, propert } return updated } + +func reverseConnections(connections []Connection) []Connection { + for i := 0; i < len(connections)/2; i++ { + j := len(connections) - i - 1 + connections[i], connections[j] = connections[j], connections[i] + } + return connections +} diff --git a/frontend/package.json b/frontend/package.json index f22fad5..5bc13f1 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -14,8 +14,10 @@ "classnames": "^2.2.6", "dompurify": "^2.1.1", "eslint-config-react-app": "^5.2.1", + "flux": "^3.1.3", "lodash": "^4.17.20", "node-sass": "^4.14.0", + "pondjs": "^0.9.0", "react": "^16.13.1", "react-bootstrap": "^1.0.1", "react-dom": "^16.13.1", @@ -25,6 +27,7 @@ "react-router-dom": "^5.1.2", "react-scripts": "3.4.1", "react-tag-autocomplete": "^6.0.0-beta.6", + "react-timeseries-charts": "^0.16.1", "typed.js": "^2.0.11" }, "scripts": { diff --git a/frontend/src/components/filters/FiltersDefinitions.js b/frontend/src/components/filters/FiltersDefinitions.js index 02ccb42..d4f2912 100644 --- a/frontend/src/components/filters/FiltersDefinitions.js +++ b/frontend/src/components/filters/FiltersDefinitions.js @@ -1,12 +1,4 @@ -import { - cleanNumber, - timestampToTime, - timeToTimestamp, - validate24HourTime, - validateIpAddress, - validateMin, - validatePort -} from "../../utils"; +import {cleanNumber, validateIpAddress, validateMin, validatePort} from "../../utils"; import StringConnectionsFilter from "./StringConnectionsFilter"; import React from "react"; import RulesConnectionsFilter from "./RulesConnectionsFilter"; @@ -22,69 +14,69 @@ export const filtersDefinitions = { replaceFunc={cleanNumber} validateFunc={validatePort} key="service_port_filter" - width={200} />, - matched_rules: , + width={200}/>, + matched_rules: , client_address: , + width={320}/>, client_port: , + width={200}/>, min_duration: , + width={200}/>, max_duration: , + width={200}/>, min_bytes: , + width={200}/>, max_bytes: , - started_after: , - started_before: , - closed_after: , - closed_before: , - marked: , - hidden: + width={200}/>, + // started_after: , + // started_before: , + // closed_after: , + // closed_before: , + marked: , + // hidden: }; diff --git a/frontend/src/components/panels/MainPane.js b/frontend/src/components/panels/MainPane.js index 3202d6d..bd25e0c 100644 --- a/frontend/src/components/panels/MainPane.js +++ b/frontend/src/components/panels/MainPane.js @@ -8,24 +8,23 @@ import PcapPane from "./PcapPane"; import backend from "../../backend"; import RulePane from "./RulePane"; import ServicePane from "./ServicePane"; +import log from "../../log"; class MainPane extends Component { - constructor(props) { - super(props); - this.state = { - selectedConnection: null, - loading: false - }; - } + state = {}; componentDidMount() { const match = this.props.location.pathname.match(/^\/connections\/([a-f0-9]{24})$/); if (match != null) { - this.setState({loading: true}); + this.loading = true; backend.get(`/api/connections/${match[1]}`) - .then(res => this.setState({selectedConnection: res.json, loading: false})) - .catch(error => console.log(error)); + .then(res => { + this.loading = false; + this.setState({selectedConnection: res.json}); + log.debug(`Initial connection ${match[1]} loaded`); + }) + .catch(error => log.error("Error loading initial connection", error)); } } @@ -34,18 +33,19 @@ class MainPane extends Component {
{ - !this.state.loading && + !this.loading && this.setState({selectedConnection: c})} - initialConnection={this.state.selectedConnection} /> + initialConnection={this.state.selectedConnection}/> }
- } /> - } /> - } /> - } /> - } /> + }/> + }/> + }/> + }/> + }/>
diff --git a/frontend/src/globals.js b/frontend/src/globals.js new file mode 100644 index 0000000..cd4dc64 --- /dev/null +++ b/frontend/src/globals.js @@ -0,0 +1,5 @@ +import {Dispatcher} from "flux"; + +const dispatcher = new Dispatcher(); + +export default dispatcher; diff --git a/frontend/src/log.js b/frontend/src/log.js new file mode 100644 index 0000000..0883962 --- /dev/null +++ b/frontend/src/log.js @@ -0,0 +1,7 @@ +const log = { + debug: (...obj) => console.info(...obj), + info: (...obj) => console.info(...obj), + error: (...obj) => console.error(obj) +}; + +export default log; diff --git a/frontend/src/views/App.js b/frontend/src/views/App.js index abd5209..00d9110 100644 --- a/frontend/src/views/App.js +++ b/frontend/src/views/App.js @@ -7,17 +7,17 @@ import {BrowserRouter as Router} from "react-router-dom"; import Filters from "./Filters"; import backend from "../backend"; import ConfigurationPane from "../components/panels/ConfigurationPane"; +import log from "../log"; class App extends Component { - constructor(props) { - super(props); - - this.state = {}; - } + state = {}; componentDidMount() { - backend.get("/api/services").then(_ => this.setState({configured: true})); + backend.get("/api/services").then(_ => { + log.debug("Caronte is already configured. Loading main.."); + this.setState({configured: true}); + }); setInterval(() => { if (document.title.endsWith("❚")) { @@ -38,11 +38,11 @@ class App extends Component {
-
this.setState({filterWindowOpen: true})} /> +
this.setState({filterWindowOpen: true})}/>
- {this.state.configured ? : - this.setState({configured: true})} />} + {this.state.configured ? : + this.setState({configured: true})}/>} {modal}
diff --git a/frontend/src/views/Connections.js b/frontend/src/views/Connections.js index 73979c4..fe655b3 100644 --- a/frontend/src/views/Connections.js +++ b/frontend/src/views/Connections.js @@ -6,26 +6,31 @@ import {Redirect} from 'react-router'; import {withRouter} from "react-router-dom"; import backend from "../backend"; import ConnectionMatchedRules from "../components/ConnectionMatchedRules"; +import dispatcher from "../globals"; +import log from "../log"; +import ButtonField from "../components/fields/ButtonField"; class Connections extends Component { + state = { + loading: false, + connections: [], + firstConnection: null, + lastConnection: null, + flagRule: null, + rules: null, + queryString: null + }; + constructor(props) { super(props); - this.state = { - loading: false, - connections: [], - firstConnection: null, - lastConnection: null, - prevParams: null, - flagRule: null, - rules: null, - queryString: null - }; this.scrollTopThreashold = 0.00001; this.scrollBottomThreashold = 0.99999; - this.maxConnections = 500; + this.maxConnections = 200; this.queryLimit = 50; + this.connectionsListRef = React.createRef(); + this.lastScrollPosition = 0; } componentDidMount() { @@ -35,6 +40,17 @@ class Connections extends Component { this.setState({selected: this.props.initialConnection.id}); // TODO: scroll to initial connection } + + dispatcher.register((payload) => { + if (payload.actionType === "timeline-update") { + this.connectionsListRef.current.scrollTop = 0; + this.loadConnections({ + started_after: Math.round(payload.from.getTime() / 1000), + started_before: Math.round(payload.to.getTime() / 1000), + limit: this.maxConnections + }).then(() => log.info(`Loading connections between ${payload.from} and ${payload.to}`)); + } + }); } connectionSelected = (c) => { @@ -46,7 +62,7 @@ class Connections extends Component { if (this.state.loaded && prevProps.location.search !== this.props.location.search) { this.setState({queryString: this.props.location.search}); this.loadConnections({limit: this.queryLimit}) - .then(() => console.log("Connections reloaded after query string update")); + .then(() => log.info("Connections reloaded after query string update")); } } @@ -54,12 +70,26 @@ class Connections extends Component { let relativeScroll = e.currentTarget.scrollTop / (e.currentTarget.scrollHeight - e.currentTarget.clientHeight); if (!this.state.loading && relativeScroll > this.scrollBottomThreashold) { this.loadConnections({from: this.state.lastConnection.id, limit: this.queryLimit,}) - .then(() => console.log("Following connections loaded")); + .then(() => log.info("Following connections loaded")); } if (!this.state.loading && relativeScroll < this.scrollTopThreashold) { this.loadConnections({to: this.state.firstConnection.id, limit: this.queryLimit,}) - .then(() => console.log("Previous connections loaded")); + .then(() => log.info("Previous connections loaded")); + if (this.state.showMoreRecentButton) { + this.setState({showMoreRecentButton: false}); + } + } else { + if (this.lastScrollPosition > e.currentTarget.scrollTop) { + if (!this.state.showMoreRecentButton) { + this.setState({showMoreRecentButton: true}); + } + } else { + if (this.state.showMoreRecentButton) { + this.setState({showMoreRecentButton: false}); + } + } } + this.lastScrollPosition = e.currentTarget.scrollTop; }; addServicePortFilter = (port) => { @@ -85,14 +115,14 @@ class Connections extends Component { urlParams.set(name, value); } - this.setState({loading: true, prevParams: params}); + this.setState({loading: true}); let res = (await backend.get(`${url}?${urlParams}`)).json; let connections = this.state.connections; let firstConnection = this.state.firstConnection; let lastConnection = this.state.lastConnection; - if (params !== undefined && params.from !== undefined) { + if (params !== undefined && params.from !== undefined && params.to === undefined) { if (res.length > 0) { connections = this.state.connections.concat(res); lastConnection = connections[connections.length - 1]; @@ -102,7 +132,7 @@ class Connections extends Component { firstConnection = connections[0]; } } - } else if (params !== undefined && params.to !== undefined) { + } else if (params !== undefined && params.to !== undefined && params.from === undefined) { if (res.length > 0) { connections = res.concat(this.state.connections); firstConnection = connections[0]; @@ -112,6 +142,7 @@ class Connections extends Component { } } } else { + this.connectionsListRef.current.scrollTop = 0; if (res.length > 0) { connections = res; firstConnection = connections[0]; @@ -124,7 +155,7 @@ class Connections extends Component { } let rules = this.state.rules; - if (rules === null) { + if (rules == null) { rules = (await backend.get("/api/rules")).json; } @@ -135,15 +166,21 @@ class Connections extends Component { firstConnection: firstConnection, lastConnection: lastConnection }); + + if (firstConnection != null && lastConnection != null) { + dispatcher.dispatch({ + actionType: "connections-update", + from: new Date(lastConnection["started_at"]), + to: new Date(firstConnection["started_at"]) + }); + } } render() { let redirect; let queryString = this.state.queryString !== null ? this.state.queryString : ""; if (this.state.selected) { - let format = this.props.match.params.format; - format = format !== undefined ? "/" + format : ""; - redirect = ; + redirect = ; } let loading = null; @@ -154,48 +191,55 @@ class Connections extends Component { } return ( -
-
- - - - - - - - - - - - - - - - - { - this.state.connections.flatMap(c => { - return [ this.connectionSelected(c)} - selected={this.state.selected === c.id} - onMarked={marked => c.marked = marked} - onEnabled={enabled => c.hidden = !enabled} - addServicePortFilter={this.addServicePortFilter} />, - c.matched_rules.length > 0 && +
+ {this.state.showMoreRecentButton &&
+ + this.loadConnections({limit: this.queryLimit}) + .then(() => log.info("Most recent connections loaded")) + }/> +
} + +
+
servicesrcipsrcportdstipdstportstarted_atdurationupdownactions
+ + + + + + + + + + + + + + + + { + this.state.connections.flatMap(c => { + return [ this.connectionSelected(c)} + selected={this.state.selected === c.id} + onMarked={marked => c.marked = marked} + onEnabled={enabled => c.hidden = !enabled} + addServicePortFilter={this.addServicePortFilter}/>, + c.matched_rules.length > 0 && - ]; - }) - } - {loading} - -
servicesrcipsrcportdstipdstportstarted_atdurationupdownactions
- - {redirect} + addMatchedRulesFilter={this.addMatchedRulesFilter}/> + ]; + }) + } + {loading} + + + + {redirect} +
); } } - export default withRouter(Connections); diff --git a/frontend/src/views/Connections.scss b/frontend/src/views/Connections.scss index c7bd1df..9e2b6ba 100644 --- a/frontend/src/views/Connections.scss +++ b/frontend/src/views/Connections.scss @@ -1,37 +1,39 @@ @import "../colors.scss"; -.connections { +.connections-container { position: relative; - overflow: auto; height: 100%; - padding: 0 10px; + padding: 10px; background-color: $color-primary-3; - .table { - margin-top: 10px; - } + .connections { + position: relative; + overflow-y: scroll; + height: 100%; - .connections-header-padding { - position: sticky; - top: 0; - right: 0; - left: 0; - height: 10px; - margin-bottom: -10px; - background-color: $color-primary-3; - } + .table { + margin-bottom: 0; + } + + th { + font-size: 13.5px; + position: sticky; + top: 0; + padding: 5px; + border: none; + background-color: $color-primary-2; + } - th { - font-size: 13.5px; - position: sticky; - top: 10px; - padding: 5px; - border-top: 3px solid $color-primary-3; - border-bottom: 3px solid $color-primary-3; - background-color: $color-primary-2; + &:hover::-webkit-scrollbar-thumb { + background: $color-secondary-2; + } } - &:hover::-webkit-scrollbar-thumb { - background: $color-secondary-2; + .most-recent-button { + position: absolute; + z-index: 20; + top: 45px; + left: calc(50% - 50px); + background-color: red; } } diff --git a/frontend/src/views/Footer.js b/frontend/src/views/Footer.js index 0a3c5a3..ad1e4f7 100644 --- a/frontend/src/views/Footer.js +++ b/frontend/src/views/Footer.js @@ -1,19 +1,180 @@ import React, {Component} from 'react'; import './Footer.scss'; +import { + ChartContainer, + ChartRow, + Charts, + LineChart, + MultiBrush, + Resizable, + styler, + YAxis +} from "react-timeseries-charts"; +import {TimeRange, TimeSeries} from "pondjs"; +import backend from "../backend"; +import ChoiceField from "../components/fields/ChoiceField"; +import dispatcher from "../globals"; +import {withRouter} from "react-router-dom"; +import log from "../log"; + class Footer extends Component { + state = { + metric: "connections_per_service" + }; + + constructor() { + super(); + + this.disableTimeSeriesChanges = false; + this.selectionTimeout = null; + } + + filteredPort = () => { + const urlParams = new URLSearchParams(this.props.location.search); + return urlParams.get("service_port"); + }; + + componentDidMount() { + const filteredPort = this.filteredPort(); + this.setState({filteredPort}); + this.loadStatistics(this.state.metric, filteredPort).then(() => + log.debug("Statistics loaded after mount")); + + dispatcher.register((payload) => { + if (payload.actionType === "connections-update") { + this.setState({ + selection: new TimeRange(payload.from, payload.to), + }); + } + }); + } + + componentDidUpdate(prevProps, prevState, snapshot) { + const filteredPort = this.filteredPort(); + if (this.state.filteredPort !== filteredPort) { + this.setState({filteredPort}); + this.loadStatistics(this.state.metric, filteredPort).then(() => + log.debug("Statistics reloaded after filtered port changes")); + } + } + + loadStatistics = async (metric, filteredPort) => { + const urlParams = new URLSearchParams(); + urlParams.set("metric", metric); + + let services = (await backend.get("/api/services")).json; + if (filteredPort && services[filteredPort]) { + const service = services[filteredPort]; + services = {}; + services[filteredPort] = service; + } + + const ports = Object.keys(services); + ports.forEach(s => urlParams.append("ports", s)); + + const metrics = (await backend.get("/api/statistics?" + urlParams)).json; + const series = new TimeSeries({ + name: "statistics", + columns: ["time"].concat(ports), + points: metrics.map(m => [new Date(m["range_start"])].concat(ports.map(p => m[metric][p] || 0))) + }); + this.setState({ + metric, + series, + services, + timeRange: series.range(), + }); + log.debug(`Loaded statistics for metric "${metric}" for services [${ports}]`); + }; + + createStyler = () => { + 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({ + actionType: "timeline-update", + from: timeRange.begin(), + to: timeRange.end() + }); + this.selectionTimeout = null; + this.disableTimeSeriesChanges = false; + }, 1000); + }; + + aggregateSeries = (func) => { + const values = this.state.series.columns().map(c => this.state.series[func](c)); + return Math[func](...values); + }; + render() { return ( -