Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ With `timestamp: true`, you can choose the time range (1 h, 24 h, 7 d, 30 d or a

<p align="center"><img alt="succulent explore dashboard" width="800" src=".github/images/explore.png"></p>

If a password is set, the dashboard asks for it once and keeps the session in a cookie, so the password never appears in the URL. Sessions last until the server restarts; to keep them across restarts, set a `secret_key` in the configuration. Scripts can read `/explore/api/data` with the `Authorization: Bearer password` or `X-API-Key: password` header instead.
If a password is set, the dashboard asks for it once and keeps the session in a cookie, so the password never appears in the URL. Sessions stay valid across restarts and in every server process (e.g. several gunicorn workers); changing the password ends them. To choose the key for the session cookie yourself, set a `secret_key` in the configuration. Scripts can read `/explore/api/data` with the `Authorization: Bearer password` or `X-API-Key: password` header instead.

The dashboard only reads the stored data; data collection works exactly as without it. It needs no internet access (no external scripts or fonts), so it also works on a local network, and values sent by devices are always shown as text.

Expand Down
2 changes: 1 addition & 1 deletion docs/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,6 @@ Then navigate to `http://localhost:8080/explore <http://localhost:8080/explore>`

With ``timestamp: true``, you can choose the time range (1 h, 24 h, 7 d, 30 d or all). If export is enabled, the data can be downloaded as CSV from the dashboard.

If a password is set, the dashboard asks for it once and keeps the session in a cookie, so the password never appears in the URL. Sessions last until the server restarts; to keep them across restarts, set a ``secret_key`` in the configuration. Scripts can read ``/explore/api/data`` with the ``Authorization: Bearer password`` or ``X-API-Key: password`` header instead.
If a password is set, the dashboard asks for it once and keeps the session in a cookie, so the password never appears in the URL. Sessions stay valid across restarts and in every server process (e.g. several gunicorn workers); changing the password ends them. To choose the key for the session cookie yourself, set a ``secret_key`` in the configuration. Scripts can read ``/explore/api/data`` with the ``Authorization: Bearer password`` or ``X-API-Key: password`` header instead.

The dashboard only reads the stored data; data collection works exactly as without it. It needs no internet access (no external scripts or fonts), so it also works on a local network, and values sent by devices are always shown as text.
40 changes: 32 additions & 8 deletions succulent/explore.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
- enable: true
- refresh: 10 # auto-refresh interval in seconds (optional)
"""
import hashlib
import hmac
import math
import os
Expand Down Expand Up @@ -135,12 +136,27 @@ def enabled(cls, config):
"""
return cls.settings(config.get('explore')).get('enable') is True

def session_key(self):
"""Create the secret key for the dashboard's session cookie.

Returns:
str: A key derived from the password (the same in every server
process), or a random key if no password is set.
"""
if not self.processing.password:
return secrets.token_hex(32)
return hmac.new(str(self.processing.password).encode('utf-8'),
b'succulent explore session key', hashlib.sha256).hexdigest()

def register(self, app):
"""Register the dashboard routes on a Flask application.

A random secret key is set for the session cookie if the
application has none. Sessions then last until the server
restarts; set ``secret_key`` in the configuration to keep them.
If the application has no secret key for the session cookie, one is
derived from the password, so every process of the server (e.g.
several gunicorn workers) accepts the same sessions, and changing
the password ends all sessions. Without a password no session is
needed and a random key is used. Set ``secret_key`` in the
configuration to choose the key yourself.

Args:
app (Flask): The Flask application.
Expand All @@ -149,7 +165,7 @@ def register(self, app):
None
"""
if not app.secret_key:
app.secret_key = secrets.token_hex(32)
app.secret_key = self.session_key()
app.config.setdefault('SESSION_COOKIE_SAMESITE', 'Lax')
app.config.setdefault('SESSION_COOKIE_HTTPONLY', True)
app.register_blueprint(self.blueprint)
Expand Down Expand Up @@ -317,7 +333,7 @@ def clean(value):
Returns:
The value as a JSON-safe Python type (missing values as None).
"""
if value is None:
if value is None or value is pd.NaT:
return None
if isinstance(value, (pd.Timestamp, datetime)):
return value.strftime('%Y-%m-%d %H:%M:%S')
Expand Down Expand Up @@ -364,7 +380,10 @@ def api_data(self):
times = None
if has_time and 'timestamp' in df.columns and len(df):
times = pd.to_datetime(df['timestamp'], errors='coerce')
df = df.assign(_time=times).sort_values('_time', kind='stable')
# Rows without a timestamp (e.g. stored before 'timestamp' was
# enabled) are the oldest: keep them first, in file order. They
# are only included in the 'all' range.
df = df.assign(_time=times).sort_values('_time', kind='stable', na_position='first')
span = self.RANGES[selected]
if span is not None and df['_time'].notna().any():
df = df[df['_time'] >= df['_time'].max() - span]
Expand Down Expand Up @@ -410,8 +429,13 @@ def api_data(self):
for item in info:
if item['numeric']:
numbers = pd.to_numeric(df[item['name']], errors='coerce').reset_index(drop=True)
means = numbers.groupby(groups).mean()
series['values'][item['name']] = [self.clean(v) for v in means]
grouped = numbers.groupby(groups)
series['values'][item['name']] = [self.clean(v) for v in grouped.mean()]
if bucket > 1:
# Lowest and highest value per point, so short spikes
# (e.g. outside min/max) stay visible when averaged
series.setdefault('low', {})[item['name']] = [self.clean(v) for v in grouped.min()]
series.setdefault('high', {})[item['name']] = [self.clean(v) for v in grouped.max()]

# Latest raw rows, newest first
shown = ['timestamp'] if has_time and 'timestamp' in df.columns else []
Expand Down
1 change: 1 addition & 0 deletions succulent/explore_static/explore.css
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ a { color: var(--accent); }
.grid-line { stroke: var(--line); }
.bound-line { stroke: var(--bound); stroke-dasharray: 6 5; }
.series { stroke: var(--accent); }
.band { fill: var(--accent); fill-opacity: 0.14; stroke: none; }

.bound-label {
position: absolute;
Expand Down
35 changes: 28 additions & 7 deletions succulent/explore_static/explore.js
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,9 @@

function renderChart(column, data) {
var values = data.series.values[column.name] || [];
// With averaged points, the lowest and highest value of each point
var lows = (data.series.low || {})[column.name] || values;
var highs = (data.series.high || {})[column.name] || values;
var present = values.filter(isNumber);
var card = el('div', 'card chart');
var outsideText = column.outside ? ' · ' + column.outside + ' outside' : '';
Expand All @@ -363,8 +366,8 @@
return card;
}

var dataLo = Math.min.apply(null, present.concat(isNumber(column.min) ? [column.min] : []));
var dataHi = Math.max.apply(null, present.concat(isNumber(column.max) ? [column.max] : []));
var dataLo = Math.min.apply(null, lows.filter(isNumber).concat(isNumber(column.min) ? [column.min] : []));
var dataHi = Math.max.apply(null, highs.filter(isNumber).concat(isNumber(column.max) ? [column.max] : []));
var padding = (dataHi - dataLo) * 0.08 || Math.max(Math.abs(dataHi) * 0.1, 1);
// Do not go below zero for values that are never negative (e.g. light)
var scale = niceScale(dataLo >= 0 ? Math.max(0, dataLo - padding) : dataLo - padding, dataHi + padding);
Expand Down Expand Up @@ -393,6 +396,21 @@
if (isNumber(column.max)) boundPath += 'M0 ' + y(column.max).toFixed(1) + ' L1000 ' + y(column.max).toFixed(1) + ' ';
if (isNumber(column.min)) boundPath += 'M0 ' + y(column.min).toFixed(1) + ' L1000 ' + y(column.min).toFixed(1);
if (boundPath) svg.appendChild(svgEl('path', { d: boundPath.trim(), fill: 'none', 'stroke-width': '1.5', 'vector-effect': 'non-scaling-stroke', 'class': 'bound-line' }));
if (lows !== values) {
// Band from the lowest to the highest value of each averaged point
var band = '', top = [], bottom = [];
var flush = function () {
if (top.length) band += 'M' + top.join(' L') + ' L' + bottom.reverse().join(' L') + ' Z ';
top = []; bottom = [];
};
values.forEach(function (v, i) {
if (!isNumber(lows[i]) || !isNumber(highs[i])) { flush(); return; }
top.push(x(i).toFixed(1) + ' ' + y(highs[i]).toFixed(1));
bottom.push(x(i).toFixed(1) + ' ' + y(lows[i]).toFixed(1));
});
flush();
if (band) svg.appendChild(svgEl('path', { d: band.trim(), 'class': 'band' }));
}
svg.appendChild(svgEl('path', { d: d.trim(), fill: 'none', 'stroke-width': '2', 'stroke-linejoin': 'round', 'stroke-linecap': 'round', 'vector-effect': 'non-scaling-stroke', 'class': 'series' }));
plot.appendChild(svg);

Expand All @@ -403,15 +421,18 @@
plot.appendChild(label);
});

values.forEach(function (v, i) {
if (!isNumber(v)) return;
var out = (isNumber(column.max) && v > column.max) || (isNumber(column.min) && v < column.min);
if (!out) return;
// Mark values outside min/max. For averaged points, the lowest and
// highest value are checked, so short spikes are not lost.
var mark = function (v, i) {
var dot = el('span', 'outlier');
dot.style.left = (x(i) / 10).toFixed(2) + '%';
dot.style.top = (y(v) / 3).toFixed(2) + '%';
dot.title = column.name + ' ' + fmtCol(v, column) + ' · ' + xLabel(data.series.x[i], data);
plot.appendChild(dot);
};
values.forEach(function (v, i) {
if (isNumber(column.max) && isNumber(highs[i]) && highs[i] > column.max) mark(highs[i], i);
if (isNumber(column.min) && isNumber(lows[i]) && lows[i] < column.min) mark(lows[i], i);
});

var ticks = el('div', 'ticks');
Expand All @@ -424,7 +445,7 @@
labels.appendChild(el('span', null, xs.length ? xLabel(xs[Math.round(f * (xs.length - 1))], data) : ''));
});
card.appendChild(labels);
if (data.bucket > 1) card.appendChild(el('p', 'note', 'Averaged over ' + data.bucket + ' measurements per point.'));
if (data.bucket > 1) card.appendChild(el('p', 'note', 'Averaged over up to ' + data.bucket + ' measurements per point; the band shows their lowest and highest value.'));
return card;
}

Expand Down
82 changes: 82 additions & 0 deletions tests/test_explore.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,65 @@ def test_long_series_are_averaged(self):
self.assertEqual(data['series']['values']['temperature'][0], 4.5)
self.assertEqual(len(data['table']['rows']), 10)
self.assertEqual(data['interval'], 60.0)
# Lowest and highest value per averaged point
self.assertEqual(data['series']['low']['temperature'][0], 0)
self.assertEqual(data['series']['high']['temperature'][0], 9)

def test_short_spike_is_kept_when_averaged(self):
# One value above max (30) among normal ones: the average stays in
# range, but the highest value of that point shows the spike
self.api.explorer.MAX_POINTS = 10
start = datetime.now() - timedelta(hours=10)
self.write_rows([{'temperature': 99 if i == 42 else 20, 'humidity': 1, 'status': 'x',
'timestamp': (start + timedelta(minutes=i)).strftime('%Y-%m-%d %H:%M:%S')}
for i in range(100)])
data = strict_json(self.client.get('/explore/api/data?range=all'))
temperature = {c['name']: c for c in data['columns']}['temperature']
self.assertEqual(temperature['outside'], 1)
self.assertLessEqual(max(data['series']['values']['temperature']), 30)
self.assertEqual(data['series']['high']['temperature'][4], 99)

def test_no_low_high_without_averaging(self):
self.client.post('/measure', json={'temperature': 20})
data = strict_json(self.client.get('/explore/api/data'))
self.assertEqual(data['bucket'], 1)
self.assertNotIn('low', data['series'])
self.assertNotIn('high', data['series'])

def test_rows_without_timestamp(self):
# 'timestamp' enabled later: older rows have no time
now = datetime.now().replace(microsecond=0)
self.write_rows([
{'temperature': 18, 'humidity': 1, 'status': 'old', 'timestamp': None},
{'temperature': 19, 'humidity': None, 'status': 'old', 'timestamp': None},
{'temperature': 20, 'humidity': None, 'status': 'new',
'timestamp': (now - timedelta(minutes=20)).strftime('%Y-%m-%d %H:%M:%S')},
{'temperature': 21, 'humidity': None, 'status': 'new',
'timestamp': (now - timedelta(minutes=10)).strftime('%Y-%m-%d %H:%M:%S')},
])
for selected, count in [('all', 4), ('24h', 2), ('1h', 2)]:
with self.subTest(range=selected):
response = self.client.get(f'/explore/api/data?range={selected}')
self.assertEqual(response.status_code, 200)
data = strict_json(response)
self.assertEqual(data['count'], count)
self.assertEqual(data['last_time'], (now - timedelta(minutes=10)).strftime('%Y-%m-%d %H:%M:%S'))
# Newest first: the rows with a timestamp come first
self.assertEqual(data['table']['rows'][0]['temperature'], 21)

data = strict_json(self.client.get('/explore/api/data?range=all'))
humidity = {c['name']: c for c in data['columns']}['humidity']
# The last humidity value is in a row without a timestamp
self.assertEqual(humidity['last_valid'], 1)
self.assertIsNone(humidity['last_valid_time'])
self.assertEqual([r['timestamp'] for r in data['table']['rows']][-1], None)
self.assertEqual(data['series']['x'][:2], [None, None])

def test_only_rows_without_timestamp(self):
self.write_rows([{'temperature': 18, 'humidity': 1, 'status': 'a', 'timestamp': None}])
response = self.client.get('/explore/api/data?range=all')
self.assertEqual(response.status_code, 200)
self.assertIsNone(strict_json(response)['last_time'])

def test_export(self):
self.client.post('/measure', json={'temperature': 20})
Expand Down Expand Up @@ -279,6 +338,29 @@ def test_secret_key_from_config(self):
api, client = self.make_api(dict(TABLE_CONFIG, password='x', secret_key='fixed-key'))
self.assertEqual(api.app.secret_key, 'fixed-key')

def test_session_works_across_processes(self):
# Several gunicorn workers each create their own app: a session from
# one must be accepted by another
other, other_client = self.make_api(dict(TABLE_CONFIG, password='s3cret'))
self.assertEqual(self.api.app.secret_key, other.app.secret_key)

self.client.post('/explore/login', data={'password': 's3cret'})
cookie = self.client.get_cookie('session')
other_client.set_cookie('session', cookie.value)
self.assertEqual(other_client.get('/explore/api/data').status_code, 200)

def test_new_password_ends_sessions(self):
changed, changed_client = self.make_api(dict(TABLE_CONFIG, password='new'))
self.assertNotEqual(self.api.app.secret_key, changed.app.secret_key)

self.client.post('/explore/login', data={'password': 's3cret'})
changed_client.set_cookie('session', self.client.get_cookie('session').value)
self.assertEqual(changed_client.get('/explore/api/data').status_code, 401)

def test_key_is_not_the_password(self):
self.assertNotIn('s3cret', self.api.app.secret_key)
self.assertEqual(len(self.api.app.secret_key), 64)


class TestExploreImages(ExploreTestCase):

Expand Down
Loading