dashboard: fix peer UI consistency issue, improve UI

This commit is contained in:
Kurkó Mihály 2019-01-24 17:18:44 +02:00
parent 993eb058f4
commit 5be7f9e274
5 changed files with 415 additions and 246 deletions

File diff suppressed because one or more lines are too long

View file

@ -24,11 +24,15 @@ import TableBody from '@material-ui/core/TableBody';
import TableRow from '@material-ui/core/TableRow'; import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell'; import TableCell from '@material-ui/core/TableCell';
import Grid from '@material-ui/core/Grid/Grid'; import Grid from '@material-ui/core/Grid/Grid';
import Typography from '@material-ui/core/Typography';
import AreaChart from 'recharts/es6/chart/AreaChart'; import AreaChart from 'recharts/es6/chart/AreaChart';
import Tooltip from 'recharts/es6/component/Tooltip'; import Tooltip from 'recharts/es6/component/Tooltip';
import Area from 'recharts/es6/cartesian/Area'; import Area from 'recharts/es6/cartesian/Area';
import {Icon as FontAwesome} from 'react-fa';
import CustomTooltip, {bytePlotter, multiplier} from 'CustomTooltip'; import CustomTooltip, {bytePlotter, multiplier} from 'CustomTooltip';
import type {Network as NetworkType, PeerEvent} from '../types/content'; import type {Network as NetworkType, PeerEvent} from '../types/content';
import {styles as commonStyles} from '../common';
// inserter is a state updater function for the main component, which handles the peers. // inserter is a state updater function for the main component, which handles the peers.
export const inserter = (sampleLimit: number) => (update: NetworkType, prev: NetworkType) => { export const inserter = (sampleLimit: number) => (update: NetworkType, prev: NetworkType) => {
@ -44,9 +48,10 @@ export const inserter = (sampleLimit: number) => (update: NetworkType, prev: Net
return; return;
} }
switch (event.remove) { switch (event.remove) {
case 'bundle': case 'bundle': {
delete prev.peers.bundles[event.ip]; delete prev.peers.bundles[event.ip];
return; return;
}
case 'known': { case 'known': {
if (!event.id) { if (!event.id) {
console.error('Remove known peer event without ID', event.ip); console.error('Remove known peer event without ID', event.ip);
@ -97,21 +102,41 @@ export const inserter = (sampleLimit: number) => (update: NetworkType, prev: Net
}); });
return; return;
} }
if (!bundle.knownPeers || !bundle.knownPeers[event.id]) { if (!bundle.knownPeers) {
bundle.knownPeers = {};
}
if (!bundle.knownPeers[event.id]) {
bundle.knownPeers[event.id] = { bundle.knownPeers[event.id] = {
connected: [], connected: [],
disconnected: [], disconnected: [],
ingress: [], ingress: [],
egress: [], egress: [],
active: false,
}; };
} }
const peer = bundle.knownPeers[event.id]; const peer = bundle.knownPeers[event.id];
if (event.connected) { if (event.connected) {
if (!peer.connected) {
console.warn('peer.connected should exist');
peer.connected = [];
}
peer.connected.push(event.connected); peer.connected.push(event.connected);
} }
if (event.disconnected) { if (event.disconnected) {
if (!peer.disconnected) {
console.warn('peer.disconnected should exist');
peer.disconnected = [];
}
peer.disconnected.push(event.disconnected); peer.disconnected.push(event.disconnected);
} }
switch (event.activity) {
case 'active':
peer.active = true;
break;
case 'inactive':
peer.active = false;
break;
}
if (Array.isArray(event.ingress) && Array.isArray(event.egress)) { if (Array.isArray(event.ingress) && Array.isArray(event.egress)) {
if (event.ingress.length !== event.egress.length) { if (event.ingress.length !== event.egress.length) {
console.error('Different traffic sample length', event); console.error('Different traffic sample length', event);
@ -132,7 +157,21 @@ export const inserter = (sampleLimit: number) => (update: NetworkType, prev: Net
}; };
// styles contains the constant styles of the component. // styles contains the constant styles of the component.
const styles = {}; const styles = {
tableHead: {
height: 'auto',
},
tableRow: {
height: 'auto',
},
tableCell: {
paddingTop: 0,
paddingRight: 5,
paddingBottom: 0,
paddingLeft: 5,
border: 'none',
},
};
export type Props = { export type Props = {
container: Object, container: Object,
@ -157,16 +196,67 @@ class Network extends Component<Props, State> {
return `${month}/${date}/${hours}:${minutes}:${seconds}`; return `${month}/${date}/${hours}:${minutes}:${seconds}`;
}; };
copyToClipboard = (id) => (event) => {
event.preventDefault();
navigator.clipboard.writeText(id).then(() => {}, () => {
console.error("Failed to copy node id", id);
});
};
// TODO (kurkomisi): add single tooltip and move it to the mouse position on copy button click.
// Tried with TooltipTrigger components for each button, but it seems to be a big load.
peerTableRow = (ip, id, bundle, peer) => (
<TableRow key={`known_${ip}_${id}`} style={styles.tableRow}>
<TableCell style={styles.tableCell}>
<FontAwesome name='circle' style={{color: peer.active ? 'green' : 'red'}} />
</TableCell>
<TableCell style={{fontFamily: 'monospace', ...styles.tableCell}}>
{id.substring(0, 10) + ' '}
<FontAwesome name='copy' style={commonStyles.light} onClick={this.copyToClipboard(id)} />
</TableCell>
<TableCell style={styles.tableCell}>
{bundle.location ? (() => {
const l = bundle.location;
return `${l.country ? l.country : ''}${l.city ? `/${l.city}` : ''}`;
})() : ''}
</TableCell>
<TableCell style={styles.tableCell}>
<AreaChart
width={200} height={18}
syncId={'footerSyncId'}
data={peer.ingress.map(({value}) => ({ingress: value || 0}))}
margin={{top: 5, right: 5, bottom: 0, left: 5}}
>
<Tooltip cursor={false} content={<CustomTooltip tooltip={bytePlotter('Download')} />} />
<Area isAnimationActive={false} type='monotone' dataKey='ingress' stroke='#8884d8' fill='#8884d8' />
</AreaChart>
<AreaChart
width={200} height={18}
syncId={'footerSyncId'}
data={peer.egress.map(({value}) => ({egress: -value || 0}))}
margin={{top: 0, right: 5, bottom: 5, left: 5}}
>
<Tooltip cursor={false} content={<CustomTooltip tooltip={bytePlotter('Upload', multiplier(-1))} />} />
<Area isAnimationActive={false} type='monotone' dataKey='egress' stroke='#82ca9d' fill='#82ca9d' />
</AreaChart>
</TableCell>
</TableRow>
);
render() { render() {
return ( return (
<Grid container direction='row' justify='space-between' spacing={24}> <Grid container direction='row' justify='space-between'>
<Grid item xs={6}> <Grid item>
<Typography variant='subtitle1' gutterBottom>
Known peers
</Typography>
<Table> <Table>
<TableHead> <TableHead style={styles.tableHead}>
<TableRow> <TableRow style={styles.tableRow}>
<TableCell>Node ID</TableCell> <TableCell style={styles.tableCell} />
<TableCell>Location</TableCell> <TableCell style={styles.tableCell}>Node ID</TableCell>
<TableCell>Traffic</TableCell> <TableCell style={styles.tableCell}>Location</TableCell>
<TableCell style={styles.tableCell}>Traffic</TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
@ -174,50 +264,39 @@ class Network extends Component<Props, State> {
if (!bundle.knownPeers || Object.keys(bundle.knownPeers).length < 1) { if (!bundle.knownPeers || Object.keys(bundle.knownPeers).length < 1) {
return null; return null;
} }
return Object.entries(bundle.knownPeers).map(([id, peer]) => ( return Object.entries(bundle.knownPeers).map(([id, peer]) => {
<TableRow key={`known_${ip}_${id}`}> if (peer.active === false) {
<TableCell> return null;
{id.substring(0, 10)} }
</TableCell> return this.peerTableRow(ip, id, bundle, peer);
<TableCell> });
{bundle.location ? (() => { })}
const l = bundle.location; </TableBody>
return `${l.country ? l.country : ''}${l.city ? `/${l.city}` : ''}`; <TableBody>
})() : ''} {Object.entries(this.props.content.peers.bundles).map(([ip, bundle]) => {
</TableCell> if (!bundle.knownPeers || Object.keys(bundle.knownPeers).length < 1) {
<TableCell> return null;
<AreaChart }
width={200} height={18} return Object.entries(bundle.knownPeers).map(([id, peer]) => {
syncId={'footerSyncId'} if (peer.active === true) {
data={peer.egress.map(({value}) => ({egress: value || 0}))} return null;
margin={{top: 5, right: 5, bottom: 0, left: 5}} }
> return this.peerTableRow(ip, id, bundle, peer);
<Tooltip cursor={false} content={<CustomTooltip tooltip={bytePlotter('Download')} />} /> });
<Area isAnimationActive={false} type='monotone' dataKey='egress' stroke='#8884d8' fill='#8884d8' />
</AreaChart>
<AreaChart
width={200} height={18}
syncId={'footerSyncId'}
data={peer.ingress.map(({value}) => ({ingress: -value || 0}))}
margin={{top: 0, right: 5, bottom: 5, left: 5}}
>
<Tooltip cursor={false} content={<CustomTooltip tooltip={bytePlotter('Upload', multiplier(-1))} />} />
<Area isAnimationActive={false} type='monotone' dataKey='ingress' stroke='#82ca9d' fill='#82ca9d' />
</AreaChart>
</TableCell>
</TableRow>
));
})} })}
</TableBody> </TableBody>
</Table> </Table>
</Grid> </Grid>
<Grid item xs={6}> <Grid item>
<Typography variant='subtitle1' gutterBottom>
Connection attempts
</Typography>
<Table> <Table>
<TableHead> <TableHead style={styles.tableHead}>
<TableRow> <TableRow style={styles.tableRow}>
<TableCell>IP</TableCell> <TableCell style={styles.tableCell}>IP</TableCell>
<TableCell>Location</TableCell> <TableCell style={styles.tableCell}>Location</TableCell>
<TableCell>Attempts</TableCell> <TableCell style={styles.tableCell}>Nr</TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
@ -226,15 +305,15 @@ class Network extends Component<Props, State> {
return null; return null;
} }
return ( return (
<TableRow key={`attempt_${ip}`}> <TableRow key={`attempt_${ip}`} style={styles.tableRow}>
<TableCell>{ip}</TableCell> <TableCell style={styles.tableCell}>{ip}</TableCell>
<TableCell> <TableCell style={styles.tableCell}>
{bundle.location ? (() => { {bundle.location ? (() => {
const l = bundle.location; const l = bundle.location;
return `${l.country ? l.country : ''}${l.city ? `/${l.city}` : ''}`; return `${l.country ? l.country : ''}${l.city ? `/${l.city}` : ''}`;
})() : ''} })() : ''}
</TableCell> </TableCell>
<TableCell> <TableCell style={styles.tableCell}>
{Object.values(bundle.attempts).length} {Object.values(bundle.attempts).length}
</TableCell> </TableCell>
</TableRow> </TableRow>

View file

@ -63,6 +63,7 @@ export type PeerEvent = {
disconnected: Date, disconnected: Date,
ingress: ChartEntries, ingress: ChartEntries,
egress: ChartEntries, egress: ChartEntries,
activity: string,
}; };
export type Peers = { export type Peers = {
@ -80,6 +81,7 @@ export type KnownPeer = {
disconnected: Array<Date>, disconnected: Array<Date>,
ingress: Array<ChartEntries>, ingress: Array<ChartEntries>,
egress: Array<ChartEntries>, egress: Array<ChartEntries>,
active: boolean,
}; };
export type UnknownPeer = { export type UnknownPeer = {

View file

@ -29,8 +29,8 @@ module.exports = merge(common, {
uglifyOptions: { uglifyOptions: {
compress: true, compress: true,
output: { output: {
comments: false, comments: false,
beautify: true, beautify: true,
}, },
// warnings: true, // warnings: true,
}, },

View file

@ -30,7 +30,7 @@ import (
const ( const (
eventBufferLimit = 128 // Maximum number of buffered peer events. eventBufferLimit = 128 // Maximum number of buffered peer events.
knownPeerLimit = 100 // Maximum number of stored peers, which successfully made the handshake. knownPeerLimit = 100 // Maximum number of stored peers, which successfully made the handshake.
attemptLimit = 100 // Maximum number of stored peers, which failed to make the handshake. attemptLimit = 200 // Maximum number of stored peers, which failed to make the handshake.
// eventLimit is the maximum number of the dashboard's custom peer events, // eventLimit is the maximum number of the dashboard's custom peer events,
// that are collected between two metering period and sent to the clients // that are collected between two metering period and sent to the clients
@ -78,8 +78,7 @@ type peerContainer struct {
// Bundles is the outer map using the peer's IP address as key. // Bundles is the outer map using the peer's IP address as key.
Bundles map[string]*peerBundle `json:"bundles,omitempty"` Bundles map[string]*peerBundle `json:"bundles,omitempty"`
// activePeers contains the peers with opened connection in random order. activeCount int // Number of the still connected peers
activePeers *list.List
// inactivePeers contains the peers with closed connection in chronological order. // inactivePeers contains the peers with closed connection in chronological order.
inactivePeers *list.List inactivePeers *list.List
@ -100,7 +99,6 @@ type peerContainer struct {
func newPeerContainer(geodb *geoDB) *peerContainer { func newPeerContainer(geodb *geoDB) *peerContainer {
return &peerContainer{ return &peerContainer{
Bundles: make(map[string]*peerBundle), Bundles: make(map[string]*peerBundle),
activePeers: list.New(),
inactivePeers: list.New(), inactivePeers: list.New(),
attemptOrder: make([]string, 0, attemptLimit), attemptOrder: make([]string, 0, attemptLimit),
geodb: geodb, geodb: geodb,
@ -142,21 +140,37 @@ func (pc *peerContainer) extendKnown(event *peerEvent) []*peerEvent {
if first := len(peer.Connected) - sampleLimit; first > 0 { if first := len(peer.Connected) - sampleLimit; first > 0 {
peer.Connected = peer.Connected[first:] peer.Connected = peer.Connected[first:]
} }
peer.Active = true
events = append(events, &peerEvent{
Activity: Active,
IP: peer.ip,
ID: peer.id,
})
pc.activeCount++
if peer.listElement != nil {
_ = pc.inactivePeers.Remove(peer.listElement)
peer.listElement = nil
}
case event.Disconnected != nil: case event.Disconnected != nil:
peer.Disconnected = append(peer.Disconnected, event.Disconnected) peer.Disconnected = append(peer.Disconnected, event.Disconnected)
if first := len(peer.Disconnected) - sampleLimit; first > 0 { if first := len(peer.Disconnected) - sampleLimit; first > 0 {
peer.Disconnected = peer.Disconnected[first:] peer.Disconnected = peer.Disconnected[first:]
} }
peer.Active = false
events = append(events, &peerEvent{
Activity: Inactive,
IP: peer.ip,
ID: peer.id,
})
pc.activeCount--
if peer.listElement != nil {
// If the peer is already in the list, remove and reinsert it.
_ = pc.inactivePeers.Remove(peer.listElement)
}
// Insert the peer into the list.
peer.listElement = pc.inactivePeers.PushBack(peer)
} }
if peer.listElement != nil { for pc.inactivePeers.Len() > 0 && pc.activeCount+pc.inactivePeers.Len() > knownPeerLimit {
// If the peer is already in the list, remove and reinsert it.
_ = pc.activePeers.Remove(peer.listElement)
_ = pc.inactivePeers.Remove(peer.listElement)
peer.listElement = nil
}
// Insert the peer into the list.
peer.listElement = pc.activePeers.PushBack(peer)
for pc.activePeers.Len()+pc.inactivePeers.Len() > knownPeerLimit {
// While the count of the known peers is greater than the limit, // While the count of the known peers is greater than the limit,
// remove the first element from the inactive peer list and from the map. // remove the first element from the inactive peer list and from the map.
if removedPeer, ok := pc.inactivePeers.Remove(pc.inactivePeers.Front()).(*knownPeer); ok { if removedPeer, ok := pc.inactivePeers.Remove(pc.inactivePeers.Front()).(*knownPeer); ok {
@ -165,12 +179,8 @@ func (pc *peerContainer) extendKnown(event *peerEvent) []*peerEvent {
log.Warn("Failed to parse the removed peer") log.Warn("Failed to parse the removed peer")
} }
} }
for pc.activePeers.Len() > knownPeerLimit { if pc.activeCount > knownPeerLimit {
if removedPeer, ok := pc.activePeers.Remove(pc.activePeers.Front()).(*knownPeer); ok { log.Warn("Number of active peers is greater than the limit")
events = append(events, pc.removeKnown(removedPeer.ip, removedPeer.id)...)
} else {
log.Warn("Failed to parse the removed peer")
}
} }
return events return events
} }
@ -194,28 +204,6 @@ func (pc *peerContainer) handleAttempt(event *peerEvent) []*peerEvent {
return events return events
} }
// setActive pushes the peer denoted by the given IP address and node ID
// into the active peer list. Takes no effect if the peer doesn't exist.
func (pc *peerContainer) setActive(ip, id string) {
if bundle, ok := pc.Bundles[ip]; ok {
if peer, ok := bundle.KnownPeers[id]; ok {
if peer.listElement != nil {
_ = pc.inactivePeers.Remove(peer.listElement)
_ = pc.activePeers.Remove(peer.listElement)
}
peer.listElement = pc.activePeers.PushBack(peer)
}
}
}
// resetActive pushes the active peers to the end of the inactive peer
// list, denoting that active peers are not considered active anymore.
func (pc *peerContainer) resetActive() {
for pc.activePeers.Front() != nil {
pc.inactivePeers.PushBack(pc.activePeers.Remove(pc.activePeers.Front()))
}
}
// peerBundle contains the peers belonging to a given IP address. // peerBundle contains the peers belonging to a given IP address.
type peerBundle struct { type peerBundle struct {
// Location contains the geographical location based on the bundle's IP address. // Location contains the geographical location based on the bundle's IP address.
@ -233,6 +221,7 @@ type peerBundle struct {
// removeKnown removes the known peer belonging to the // removeKnown removes the known peer belonging to the
// given IP address and node ID from the peer tree. // given IP address and node ID from the peer tree.
func (pc *peerContainer) removeKnown(ip, id string) (events []*peerEvent) { func (pc *peerContainer) removeKnown(ip, id string) (events []*peerEvent) {
// TODO (kurkomisi): Remove peers that don't have traffic samples anymore.
if bundle, ok := pc.Bundles[ip]; ok { if bundle, ok := pc.Bundles[ip]; ok {
if _, ok := bundle.KnownPeers[id]; ok { if _, ok := bundle.KnownPeers[id]; ok {
events = append(events, &peerEvent{ events = append(events, &peerEvent{
@ -251,6 +240,8 @@ func (pc *peerContainer) removeKnown(ip, id string) (events []*peerEvent) {
}) })
delete(pc.Bundles, ip) delete(pc.Bundles, ip)
} }
} else {
log.Warn("No bundle to remove", "ip", ip)
} }
return events return events
} }
@ -321,6 +312,8 @@ type knownPeer struct {
Ingress ChartEntries `json:"ingress,omitempty"` Ingress ChartEntries `json:"ingress,omitempty"`
Egress ChartEntries `json:"egress,omitempty"` Egress ChartEntries `json:"egress,omitempty"`
Active bool `json:"active"` // Denotes if the peer is still connected.
listElement *list.Element // Pointer to the peer element in the list. listElement *list.Element // Pointer to the peer element in the list.
ip, id string // The IP and the ID by which the peer can be accessed in the tree. ip, id string // The IP and the ID by which the peer can be accessed in the tree.
prevIngress float64 prevIngress float64
@ -338,11 +331,15 @@ type peerAttempt struct {
} }
type RemovedPeerType string type RemovedPeerType string
type ActivityType string
const ( const (
RemoveKnown RemovedPeerType = "known" RemoveKnown RemovedPeerType = "known"
RemoveAttempt RemovedPeerType = "attempt" RemoveAttempt RemovedPeerType = "attempt"
RemoveBundle RemovedPeerType = "bundle" RemoveBundle RemovedPeerType = "bundle"
Active ActivityType = "active"
Inactive ActivityType = "inactive"
) )
// peerEvent contains the attributes of a peer event. // peerEvent contains the attributes of a peer event.
@ -355,6 +352,7 @@ type peerEvent struct {
Disconnected *time.Time `json:"disconnected,omitempty"` // Timestamp of the disonnection moment. Disconnected *time.Time `json:"disconnected,omitempty"` // Timestamp of the disonnection moment.
Ingress ChartEntries `json:"ingress,omitempty"` // Ingress samples. Ingress ChartEntries `json:"ingress,omitempty"` // Ingress samples.
Egress ChartEntries `json:"egress,omitempty"` // Egress samples. Egress ChartEntries `json:"egress,omitempty"` // Egress samples.
Activity ActivityType `json:"activity,omitempty"` // Connection status change.
} }
// trafficMap is a container for the periodically collected peer traffic. // trafficMap is a container for the periodically collected peer traffic.
@ -475,30 +473,6 @@ func (db *Dashboard) collectPeerData() {
// Protect 'peers', because it is part of the history. // Protect 'peers', because it is part of the history.
db.peerLock.Lock() db.peerLock.Lock()
// Usually the active peers don't produce events, and marking
// them as active makes it sure that they won't be removed from
// the tree. Only the active peers are registered into the peer
// registry, so after the traffic collection the ingress and the
// egress maps contain all the active peers.
//
// It is important to mark the active ones before the merge with
// the diff, otherwise the active peers can be removed.
//
// After a metering period the active peers can become inactive,
// so at the beginning it is necessary to transpose them to the
// inactive list.
peers.resetActive()
for ip, bundle := range *ingress {
for id := range bundle {
// Only set the peers that are inserted both
// into the ingress and the egress maps.
if _, ok := (*egress)[ip][id]; ok {
peers.setActive(ip, id)
} else {
log.Warn("Peer missing traffic sample", "IP", ip, "ID", id)
}
}
}
var diff []*peerEvent var diff []*peerEvent
for i := 0; i < len(newPeerEvents); i++ { for i := 0; i < len(newPeerEvents); i++ {
if newPeerEvents[i].IP == "" { if newPeerEvents[i].IP == "" {
@ -558,9 +532,11 @@ func (db *Dashboard) collectPeerData() {
} }
db.peerLock.Unlock() db.peerLock.Unlock()
db.sendToAll(&Message{Network: &NetworkMessage{ if len(diff) > 0 {
Diff: diff, db.sendToAll(&Message{Network: &NetworkMessage{
}}) Diff: diff,
}})
}
// Clear the traffic maps, and the event array, // Clear the traffic maps, and the event array,
// prepare them for the next metering. // prepare them for the next metering.
*ingress, *egress = make(trafficMap), make(trafficMap) *ingress, *egress = make(trafficMap), make(trafficMap)