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 TableCell from '@material-ui/core/TableCell';
import Grid from '@material-ui/core/Grid/Grid';
import Typography from '@material-ui/core/Typography';
import AreaChart from 'recharts/es6/chart/AreaChart';
import Tooltip from 'recharts/es6/component/Tooltip';
import Area from 'recharts/es6/cartesian/Area';
import {Icon as FontAwesome} from 'react-fa';
import CustomTooltip, {bytePlotter, multiplier} from 'CustomTooltip';
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.
export const inserter = (sampleLimit: number) => (update: NetworkType, prev: NetworkType) => {
@ -44,9 +48,10 @@ export const inserter = (sampleLimit: number) => (update: NetworkType, prev: Net
return;
}
switch (event.remove) {
case 'bundle':
case 'bundle': {
delete prev.peers.bundles[event.ip];
return;
}
case 'known': {
if (!event.id) {
console.error('Remove known peer event without ID', event.ip);
@ -97,21 +102,41 @@ export const inserter = (sampleLimit: number) => (update: NetworkType, prev: Net
});
return;
}
if (!bundle.knownPeers || !bundle.knownPeers[event.id]) {
if (!bundle.knownPeers) {
bundle.knownPeers = {};
}
if (!bundle.knownPeers[event.id]) {
bundle.knownPeers[event.id] = {
connected: [],
disconnected: [],
ingress: [],
egress: [],
active: false,
};
}
const peer = bundle.knownPeers[event.id];
if (event.connected) {
if (!peer.connected) {
console.warn('peer.connected should exist');
peer.connected = [];
}
peer.connected.push(event.connected);
}
if (event.disconnected) {
if (!peer.disconnected) {
console.warn('peer.disconnected should exist');
peer.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 (event.ingress.length !== event.egress.length) {
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.
const styles = {};
const styles = {
tableHead: {
height: 'auto',
},
tableRow: {
height: 'auto',
},
tableCell: {
paddingTop: 0,
paddingRight: 5,
paddingBottom: 0,
paddingLeft: 5,
border: 'none',
},
};
export type Props = {
container: Object,
@ -157,16 +196,67 @@ class Network extends Component<Props, State> {
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() {
return (
<Grid container direction='row' justify='space-between' spacing={24}>
<Grid item xs={6}>
<Grid container direction='row' justify='space-between'>
<Grid item>
<Typography variant='subtitle1' gutterBottom>
Known peers
</Typography>
<Table>
<TableHead>
<TableRow>
<TableCell>Node ID</TableCell>
<TableCell>Location</TableCell>
<TableCell>Traffic</TableCell>
<TableHead style={styles.tableHead}>
<TableRow style={styles.tableRow}>
<TableCell style={styles.tableCell} />
<TableCell style={styles.tableCell}>Node ID</TableCell>
<TableCell style={styles.tableCell}>Location</TableCell>
<TableCell style={styles.tableCell}>Traffic</TableCell>
</TableRow>
</TableHead>
<TableBody>
@ -174,50 +264,39 @@ class Network extends Component<Props, State> {
if (!bundle.knownPeers || Object.keys(bundle.knownPeers).length < 1) {
return null;
}
return Object.entries(bundle.knownPeers).map(([id, peer]) => (
<TableRow key={`known_${ip}_${id}`}>
<TableCell>
{id.substring(0, 10)}
</TableCell>
<TableCell>
{bundle.location ? (() => {
const l = bundle.location;
return `${l.country ? l.country : ''}${l.city ? `/${l.city}` : ''}`;
})() : ''}
</TableCell>
<TableCell>
<AreaChart
width={200} height={18}
syncId={'footerSyncId'}
data={peer.egress.map(({value}) => ({egress: 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='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>
));
return Object.entries(bundle.knownPeers).map(([id, peer]) => {
if (peer.active === false) {
return null;
}
return this.peerTableRow(ip, id, bundle, peer);
});
})}
</TableBody>
<TableBody>
{Object.entries(this.props.content.peers.bundles).map(([ip, bundle]) => {
if (!bundle.knownPeers || Object.keys(bundle.knownPeers).length < 1) {
return null;
}
return Object.entries(bundle.knownPeers).map(([id, peer]) => {
if (peer.active === true) {
return null;
}
return this.peerTableRow(ip, id, bundle, peer);
});
})}
</TableBody>
</Table>
</Grid>
<Grid item xs={6}>
<Grid item>
<Typography variant='subtitle1' gutterBottom>
Connection attempts
</Typography>
<Table>
<TableHead>
<TableRow>
<TableCell>IP</TableCell>
<TableCell>Location</TableCell>
<TableCell>Attempts</TableCell>
<TableHead style={styles.tableHead}>
<TableRow style={styles.tableRow}>
<TableCell style={styles.tableCell}>IP</TableCell>
<TableCell style={styles.tableCell}>Location</TableCell>
<TableCell style={styles.tableCell}>Nr</TableCell>
</TableRow>
</TableHead>
<TableBody>
@ -226,15 +305,15 @@ class Network extends Component<Props, State> {
return null;
}
return (
<TableRow key={`attempt_${ip}`}>
<TableCell>{ip}</TableCell>
<TableCell>
<TableRow key={`attempt_${ip}`} style={styles.tableRow}>
<TableCell style={styles.tableCell}>{ip}</TableCell>
<TableCell style={styles.tableCell}>
{bundle.location ? (() => {
const l = bundle.location;
return `${l.country ? l.country : ''}${l.city ? `/${l.city}` : ''}`;
})() : ''}
</TableCell>
<TableCell>
<TableCell style={styles.tableCell}>
{Object.values(bundle.attempts).length}
</TableCell>
</TableRow>

View file

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

View file

@ -30,7 +30,7 @@ import (
const (
eventBufferLimit = 128 // Maximum number of buffered peer events.
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,
// 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 map[string]*peerBundle `json:"bundles,omitempty"`
// activePeers contains the peers with opened connection in random order.
activePeers *list.List
activeCount int // Number of the still connected peers
// inactivePeers contains the peers with closed connection in chronological order.
inactivePeers *list.List
@ -100,7 +99,6 @@ type peerContainer struct {
func newPeerContainer(geodb *geoDB) *peerContainer {
return &peerContainer{
Bundles: make(map[string]*peerBundle),
activePeers: list.New(),
inactivePeers: list.New(),
attemptOrder: make([]string, 0, attemptLimit),
geodb: geodb,
@ -142,21 +140,37 @@ func (pc *peerContainer) extendKnown(event *peerEvent) []*peerEvent {
if first := len(peer.Connected) - sampleLimit; first > 0 {
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:
peer.Disconnected = append(peer.Disconnected, event.Disconnected)
if first := len(peer.Disconnected) - sampleLimit; first > 0 {
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.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 {
peer.listElement = pc.inactivePeers.PushBack(peer)
}
for pc.inactivePeers.Len() > 0 && pc.activeCount+pc.inactivePeers.Len() > knownPeerLimit {
// 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.
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")
}
}
for pc.activePeers.Len() > knownPeerLimit {
if removedPeer, ok := pc.activePeers.Remove(pc.activePeers.Front()).(*knownPeer); ok {
events = append(events, pc.removeKnown(removedPeer.ip, removedPeer.id)...)
} else {
log.Warn("Failed to parse the removed peer")
}
if pc.activeCount > knownPeerLimit {
log.Warn("Number of active peers is greater than the limit")
}
return events
}
@ -194,28 +204,6 @@ func (pc *peerContainer) handleAttempt(event *peerEvent) []*peerEvent {
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.
type peerBundle struct {
// 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
// given IP address and node ID from the peer tree.
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 _, ok := bundle.KnownPeers[id]; ok {
events = append(events, &peerEvent{
@ -251,6 +240,8 @@ func (pc *peerContainer) removeKnown(ip, id string) (events []*peerEvent) {
})
delete(pc.Bundles, ip)
}
} else {
log.Warn("No bundle to remove", "ip", ip)
}
return events
}
@ -321,6 +312,8 @@ type knownPeer struct {
Ingress ChartEntries `json:"ingress,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.
ip, id string // The IP and the ID by which the peer can be accessed in the tree.
prevIngress float64
@ -338,11 +331,15 @@ type peerAttempt struct {
}
type RemovedPeerType string
type ActivityType string
const (
RemoveKnown RemovedPeerType = "known"
RemoveAttempt RemovedPeerType = "attempt"
RemoveBundle RemovedPeerType = "bundle"
Active ActivityType = "active"
Inactive ActivityType = "inactive"
)
// 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.
Ingress ChartEntries `json:"ingress,omitempty"` // Ingress 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.
@ -475,30 +473,6 @@ func (db *Dashboard) collectPeerData() {
// Protect 'peers', because it is part of the history.
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
for i := 0; i < len(newPeerEvents); i++ {
if newPeerEvents[i].IP == "" {
@ -558,9 +532,11 @@ func (db *Dashboard) collectPeerData() {
}
db.peerLock.Unlock()
if len(diff) > 0 {
db.sendToAll(&Message{Network: &NetworkMessage{
Diff: diff,
}})
}
// Clear the traffic maps, and the event array,
// prepare them for the next metering.
*ingress, *egress = make(trafficMap), make(trafficMap)