Add cutsheets: planned cabling checked against discovery
Lint / JS (eslint) (push) Successful in 7s
Lint / Python (flake8) (push) Successful in 1m36s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m40s
Lint / Python (flake8) (pull_request) Successful in 52s
Test / Python Tests (pytest) (push) Successful in 1m4s
Lint / JS (eslint) (pull_request) Successful in 7s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m13s
Test / Python Tests (pytest) (pull_request) Successful in 1m15s
Lint / JS (eslint) (push) Successful in 7s
Lint / Python (flake8) (push) Successful in 1m36s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m40s
Lint / Python (flake8) (pull_request) Successful in 52s
Test / Python Tests (pytest) (push) Successful in 1m4s
Lint / JS (eslint) (pull_request) Successful in 7s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m13s
Test / Python Tests (pytest) (pull_request) Successful in 1m15s
A new Cutsheet page records where every cable is meant to go and compares it with what Gandalf discovers. - Inventory for what discovery can't see: patch panels, wall jacks, shelves and rack positions. Panels and jacks pass through front to rear. - Cables with two endpoints, ID, type, length, color, status (planned, installed, dark, retired) and notes; the far end may be unterminated. - Each cable's full run is traced through panels and jacks, and runs ending on a switch port are checked against its discovered neighbor (LLDP, client table, or a DAC serial seen at both ends): matches, wrong neighbor, no link, missing port, port conflict, unverified, idle. - Undocumented links: live switch ports no cable mentions, one click to add with what Gandalf already knows. Port panels show the planned cable. - Labels to make: cable IDs and panel-port labels not yet applied, with a print view, for a handheld label maker. - CSV export, and all-or-nothing import that upserts by cable ID. - Cables, panels and jacks appear in the dashboard search. Editing needs the admin group and a JSON request body. Every change is written to cutsheet_history in the same transaction. Tables are created on first use. Refs #12 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
afc7aae580
commit
b9412ff6ba
13 files changed
+2468
-5
No files matched your search
@@ -20,6 +20,7 @@ from functools import wraps
|
||||
|
||||
from flask import Flask, jsonify, make_response, redirect, render_template, request, send_file, url_for
|
||||
|
||||
import cutsheet
|
||||
import db
|
||||
import devices
|
||||
import diagnose
|
||||
@@ -409,10 +410,38 @@ def api_modem():
|
||||
@app.route('/api/devices')
|
||||
@require_auth
|
||||
def api_devices():
|
||||
"""Device list for the home page search."""
|
||||
return jsonify({'devices': devices.build_index(
|
||||
"""Device list for the home page search, plus cutsheet panels, jacks and cables."""
|
||||
found = devices.build_index(
|
||||
_state_json('network_snapshot'), _state_json('link_stats'), _state_json('modem_stats'),
|
||||
)})
|
||||
)
|
||||
known = {d['name'] for d in found}
|
||||
try:
|
||||
_ensure_cutsheet_schema()
|
||||
data = db.cutsheet_load()
|
||||
except Exception as e:
|
||||
logger.error(f'Cutsheet unavailable for search: {e}')
|
||||
data = {'items': [], 'cables': []}
|
||||
for item in data['items']:
|
||||
if item['name'] in known:
|
||||
continue
|
||||
kind = item['kind'].replace('_', ' ')
|
||||
found.append({
|
||||
'name': item['name'], 'kind': kind, 'status': 'unknown', 'ip': '', 'mac': '', 'model': '',
|
||||
'url': f'/cutsheet#item-{item["id"]}', 'interface_count': item.get('port_count') or 0,
|
||||
'search': ' '.join(filter(None, [item['name'], kind, item.get('location'), 'cutsheet'])).lower(),
|
||||
})
|
||||
for cable in data['cables']:
|
||||
if not cable.get('label'):
|
||||
continue
|
||||
ends = ' '.join(filter(None, [cable['a_device'], cable['b_device']]))
|
||||
found.append({
|
||||
'name': cable['label'], 'kind': 'cable', 'status': 'unknown', 'ip': '', 'mac': '',
|
||||
'model': f'{cable["a_device"]} ↔ {cable["b_device"] or "unterminated"}',
|
||||
'url': f'/cutsheet#cable-{cable["id"]}', 'interface_count': 0,
|
||||
'search': ' '.join(filter(None, [cable['label'], ends, cable.get('cable_type'),
|
||||
cable.get('color'), 'cable cutsheet'])).lower(),
|
||||
})
|
||||
return jsonify({'devices': found})
|
||||
|
||||
|
||||
@app.route('/api/device/<path:name>')
|
||||
@@ -427,6 +456,11 @@ def api_device(name: str):
|
||||
events = db.get_events_for_target(name)
|
||||
_annotate_suppressions(events, db.get_active_suppressions())
|
||||
detail['events'] = events
|
||||
try:
|
||||
detail['cutsheet'] = _cutsheet_for_device(name)
|
||||
except Exception as e:
|
||||
logger.error(f'Cutsheet unavailable for {name}: {e}')
|
||||
detail['cutsheet'] = []
|
||||
return jsonify(detail)
|
||||
|
||||
|
||||
@@ -769,6 +803,247 @@ def api_avatar():
|
||||
return resp
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cutsheets
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_cutsheet_schema_ready = False
|
||||
_cutsheet_schema_lock = threading.Lock()
|
||||
|
||||
|
||||
def _ensure_cutsheet_schema() -> None:
|
||||
"""Create the cutsheet tables on first use, so deploys need no migration step."""
|
||||
global _cutsheet_schema_ready
|
||||
if _cutsheet_schema_ready:
|
||||
return
|
||||
with _cutsheet_schema_lock:
|
||||
if not _cutsheet_schema_ready:
|
||||
db.ensure_cutsheet_schema()
|
||||
_cutsheet_schema_ready = True
|
||||
|
||||
|
||||
def _node_json(node) -> dict:
|
||||
if node is None:
|
||||
return {'device': '', 'port': '', 'side': '', 'text': 'unterminated'}
|
||||
return {'device': node[0], 'port': node[1], 'side': node[2], 'text': cutsheet.describe_node(node)}
|
||||
|
||||
|
||||
def _cutsheet_catalog(link_stats: dict, items: list) -> list:
|
||||
"""Devices and their ports, for the cable form's suggestions."""
|
||||
catalog = []
|
||||
for name, sw in sorted((link_stats.get('unifi_switches') or {}).items()):
|
||||
ports = sorted((p for p in (sw.get('ports') or {}).items() if p[1].get('port_idx') is not None),
|
||||
key=lambda kv: kv[1]['port_idx'])
|
||||
catalog.append({'name': name, 'kind': 'switch', 'ports': [
|
||||
{'value': str(p['port_idx']), 'text': f'{p["port_idx"]} · {pname}'} for pname, p in ports]})
|
||||
for name, ifaces in sorted((link_stats.get('hosts') or {}).items()):
|
||||
catalog.append({'name': name, 'kind': 'host',
|
||||
'ports': [{'value': i, 'text': i} for i in sorted(ifaces)]})
|
||||
known = {c['name'] for c in catalog}
|
||||
for item in items:
|
||||
if item['name'] in known:
|
||||
continue
|
||||
ports = [{'value': str(n), 'text': str(n)} for n in range(1, (item.get('port_count') or 0) + 1)]
|
||||
catalog.append({'name': item['name'], 'kind': item['kind'], 'ports': ports})
|
||||
return catalog
|
||||
|
||||
|
||||
def _cutsheet_view() -> dict:
|
||||
"""Every cutsheet record with its traced path and plan-vs-actual verdict."""
|
||||
_ensure_cutsheet_schema()
|
||||
data = db.cutsheet_load()
|
||||
link_stats = _state_json('link_stats')
|
||||
switches = link_stats.get('unifi_switches') or {}
|
||||
items = {i['name']: i for i in data['items']}
|
||||
results = cutsheet.evaluate(data['cables'], items, switches)
|
||||
for cable in data['cables']:
|
||||
r = results[cable['id']]
|
||||
cable['verdict'] = r['verdict']
|
||||
cable['detail'] = r['detail']
|
||||
cable['problem'] = r['verdict'] in cutsheet.PROBLEM_VERDICTS
|
||||
cable['path'] = [
|
||||
{'cable_id': h} if isinstance(h, int) else _node_json(h) for h in r['path']['hops']
|
||||
]
|
||||
cable['a_text'] = cutsheet.describe_node(cutsheet._node(cable, 'a'))
|
||||
cable['b_text'] = cutsheet.describe_node(cutsheet._node(cable, 'b'))
|
||||
data['suggestions'] = cutsheet.undocumented(data['cables'], switches)
|
||||
data['labels'] = cutsheet.labels_to_make(data['cables'], items, data['port_labels'])
|
||||
data['next_label'] = cutsheet.next_label(data['cables'])
|
||||
data['catalog'] = _cutsheet_catalog(link_stats, data['items'])
|
||||
data['verdicts'] = cutsheet.VERDICTS
|
||||
data['options'] = {'kinds': cutsheet.ITEM_KINDS, 'passive_kinds': cutsheet.PASSIVE_KINDS,
|
||||
'statuses': cutsheet.STATUSES, 'cable_types': cutsheet.CABLE_TYPES}
|
||||
data['updated'] = link_stats.get('updated')
|
||||
return data
|
||||
|
||||
|
||||
def _cutsheet_for_device(name: str) -> list:
|
||||
"""The cables that end on one device, for its port panel."""
|
||||
view = _cutsheet_view()
|
||||
out = []
|
||||
for cable in view['cables']:
|
||||
for end in ('a', 'b'):
|
||||
if cable[f'{end}_device'] == name and cable['status'] != 'retired':
|
||||
out.append({
|
||||
'port': cable[f'{end}_port'], 'side': cable[f'{end}_side'], 'id': cable['id'],
|
||||
'label': cable['label'], 'status': cable['status'], 'verdict': cable['verdict'],
|
||||
'detail': cable['detail'], 'problem': cable['problem'], 'path': cable['path'],
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _json_body() -> dict:
|
||||
"""The request's JSON object. Requiring a JSON content type also keeps another
|
||||
site's plain form post from reaching these write endpoints (no CORS preflight)."""
|
||||
if not request.is_json:
|
||||
raise cutsheet.ValidationError('Send the request as JSON')
|
||||
data = request.get_json(silent=True)
|
||||
if not isinstance(data, dict):
|
||||
raise cutsheet.ValidationError('Request body must be a JSON object')
|
||||
return data
|
||||
|
||||
|
||||
def _cutsheet_write(fn):
|
||||
"""Turn validation and conflict errors from a write into 400 and 409 responses."""
|
||||
@wraps(fn)
|
||||
def wrapper(*args, **kwargs):
|
||||
try:
|
||||
_ensure_cutsheet_schema()
|
||||
return fn(*args, **kwargs)
|
||||
except cutsheet.ValidationError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
except db.CutsheetConflict as e:
|
||||
return jsonify({'error': str(e)}), 409
|
||||
return wrapper
|
||||
|
||||
|
||||
def _cutsheet_items() -> dict:
|
||||
return {i['name']: i for i in db.cutsheet_load()['items']}
|
||||
|
||||
|
||||
@app.route('/cutsheet')
|
||||
@require_auth
|
||||
def cutsheet_page():
|
||||
user = _get_user()
|
||||
return render_template('cutsheet.html', user=user, can_edit='admin' in user['groups'])
|
||||
|
||||
|
||||
@app.route('/api/cutsheet')
|
||||
@require_auth
|
||||
def api_cutsheet():
|
||||
view = _cutsheet_view()
|
||||
view['history'] = db.cutsheet_history(limit=100)
|
||||
return jsonify(view)
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/cables', methods=['POST'])
|
||||
@require_auth
|
||||
@require_admin
|
||||
@_cutsheet_write
|
||||
def api_cutsheet_create_cable():
|
||||
cable = cutsheet.validate_cable(_json_body(), _cutsheet_items())
|
||||
cable_id = db.cutsheet_create_cable(cable, _get_user()['username'])
|
||||
return jsonify({'success': True, 'id': cable_id})
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/cables/<int:cable_id>', methods=['PUT'])
|
||||
@require_auth
|
||||
@require_admin
|
||||
@_cutsheet_write
|
||||
def api_cutsheet_update_cable(cable_id: int):
|
||||
cable = cutsheet.validate_cable(_json_body(), _cutsheet_items())
|
||||
if not db.cutsheet_update_cable(cable_id, cable, _get_user()['username']):
|
||||
return jsonify({'error': 'No such cable'}), 404
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/cables/<int:cable_id>', methods=['DELETE'])
|
||||
@require_auth
|
||||
@require_admin
|
||||
@_cutsheet_write
|
||||
def api_cutsheet_delete_cable(cable_id: int):
|
||||
if not db.cutsheet_delete_cable(cable_id, _get_user()['username']):
|
||||
return jsonify({'error': 'No such cable'}), 404
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/items', methods=['POST'])
|
||||
@require_auth
|
||||
@require_admin
|
||||
@_cutsheet_write
|
||||
def api_cutsheet_create_item():
|
||||
item = cutsheet.validate_item(_json_body())
|
||||
item_id = db.cutsheet_create_item(item, _get_user()['username'])
|
||||
return jsonify({'success': True, 'id': item_id})
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/items/<int:item_id>', methods=['PUT'])
|
||||
@require_auth
|
||||
@require_admin
|
||||
@_cutsheet_write
|
||||
def api_cutsheet_update_item(item_id: int):
|
||||
item = cutsheet.validate_item(_json_body())
|
||||
if not db.cutsheet_update_item(item_id, item, _get_user()['username']):
|
||||
return jsonify({'error': 'No such item'}), 404
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/items/<int:item_id>', methods=['DELETE'])
|
||||
@require_auth
|
||||
@require_admin
|
||||
@_cutsheet_write
|
||||
def api_cutsheet_delete_item(item_id: int):
|
||||
if not db.cutsheet_delete_item(item_id, _get_user()['username']):
|
||||
return jsonify({'error': 'No such item'}), 404
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/items/<int:item_id>/ports/<port>', methods=['PUT'])
|
||||
@require_auth
|
||||
@require_admin
|
||||
@_cutsheet_write
|
||||
def api_cutsheet_port_label(item_id: int, port: str):
|
||||
data = _json_body()
|
||||
label = str(data.get('label') or '').strip()
|
||||
if len(label) > 64:
|
||||
raise cutsheet.ValidationError('Port label must be 64 characters or fewer')
|
||||
if len(port) > cutsheet.PORT_MAX:
|
||||
raise cutsheet.ValidationError('Port is too long')
|
||||
if not db.cutsheet_set_port_label(item_id, port, label, bool(data.get('applied')), _get_user()['username']):
|
||||
return jsonify({'error': 'No such item'}), 404
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/cables.csv')
|
||||
@require_auth
|
||||
def api_cutsheet_export():
|
||||
_ensure_cutsheet_schema()
|
||||
resp = make_response(cutsheet.cables_to_csv(db.cutsheet_load()['cables']))
|
||||
resp.headers['Content-Type'] = 'text/csv; charset=utf-8'
|
||||
resp.headers['Content-Disposition'] = 'attachment; filename="gandalf-cutsheet.csv"'
|
||||
return resp
|
||||
|
||||
|
||||
@app.route('/api/cutsheet/import', methods=['POST'])
|
||||
@require_auth
|
||||
@require_admin
|
||||
@_cutsheet_write
|
||||
def api_cutsheet_import():
|
||||
data = _json_body()
|
||||
text = data.get('csv')
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
raise cutsheet.ValidationError('Paste or choose a CSV file')
|
||||
if len(text) > 1_000_000:
|
||||
raise cutsheet.ValidationError('CSV is larger than 1 MB')
|
||||
cables, errors = cutsheet.parse_csv(text, _cutsheet_items())
|
||||
if errors:
|
||||
return jsonify({'error': 'Nothing was imported', 'errors': errors[:50]}), 400
|
||||
if data.get('dry_run'):
|
||||
return jsonify({'success': True, 'dry_run': True, 'rows': len(cables)})
|
||||
result = db.cutsheet_import_cables(cables, _get_user()['username'])
|
||||
return jsonify(dict(result, success=True))
|
||||
|
||||
|
||||
@app.route('/health')
|
||||
def health():
|
||||
"""Health check endpoint (no auth). Checks DB and monitor freshness."""
|
||||
|
||||
Reference in new issue
Block a user