Initial commit: Chrony NTP Server add-on for Home Assistant

- NTP client syncs from configurable pools and servers
- NTP server mode serves time to LAN clients
- Web UI dashboard showing sync status, sources, and clients
- Supports iburst and maxsources options

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Adam Harrison-Fuller
2026-01-14 22:34:06 +00:00
co-authored by Claude Opus 4.5
commit 8963c16212
18 changed files with 1003 additions and 0 deletions
@@ -0,0 +1,77 @@
#!/command/with-contenv bash
# Generate chrony configuration from add-on options
CONFIG_FILE="/etc/chrony/chrony.conf"
OPTIONS_FILE="/data/options.json"
echo "[INFO] Generating Chrony configuration..."
# Create config directory
mkdir -p /etc/chrony /var/lib/chrony /var/log/chrony
# Start with base config
cat > "$CONFIG_FILE" << 'EOF'
# Chrony configuration - generated by Home Assistant add-on
driftfile /var/lib/chrony/chrony.drift
makestep 1.0 3
rtcsync
logdir /var/log/chrony
EOF
# Parse options.json with jq
if [ -f "$OPTIONS_FILE" ]; then
# Add NTP pools
pool_count=$(jq '.ntp_pools | length' "$OPTIONS_FILE")
for i in $(seq 0 $((pool_count - 1))); do
pool_addr=$(jq -r ".ntp_pools[$i].pool" "$OPTIONS_FILE")
iburst=$(jq -r ".ntp_pools[$i].iburst" "$OPTIONS_FILE")
maxsources=$(jq -r ".ntp_pools[$i].maxsources" "$OPTIONS_FILE")
pool_line="pool ${pool_addr}"
[ "$iburst" = "true" ] && pool_line="${pool_line} iburst"
[ "$maxsources" != "null" ] && pool_line="${pool_line} maxsources ${maxsources}"
echo "$pool_line" >> "$CONFIG_FILE"
echo "[INFO] Added NTP pool: ${pool_addr}"
done
# Add NTP servers
server_count=$(jq '.ntp_servers | length' "$OPTIONS_FILE")
for i in $(seq 0 $((server_count - 1))); do
server_addr=$(jq -r ".ntp_servers[$i].server" "$OPTIONS_FILE")
iburst=$(jq -r ".ntp_servers[$i].iburst" "$OPTIONS_FILE")
if [ "$iburst" = "true" ]; then
echo "server ${server_addr} iburst" >> "$CONFIG_FILE"
else
echo "server ${server_addr}" >> "$CONFIG_FILE"
fi
echo "[INFO] Added NTP server: ${server_addr}"
done
# Configure as NTP server if enabled
enable_server=$(jq -r '.enable_ntp_server' "$OPTIONS_FILE")
if [ "$enable_server" = "true" ]; then
echo "[INFO] NTP server mode enabled"
# Add allowed client networks
for network in $(jq -r '.allow_clients[]' "$OPTIONS_FILE"); do
echo "allow ${network}" >> "$CONFIG_FILE"
echo "[INFO] Allowing clients from: ${network}"
done
fi
# Set logging
detailed_logging=$(jq -r '.detailed_logging' "$OPTIONS_FILE")
if [ "$detailed_logging" = "true" ]; then
echo "log tracking measurements statistics" >> "$CONFIG_FILE"
echo "[INFO] Detailed logging enabled"
else
echo "log tracking" >> "$CONFIG_FILE"
fi
fi
echo "[INFO] Chrony configuration generated successfully"
# Start chrony in foreground
exec chronyd -d -f "$CONFIG_FILE"
@@ -0,0 +1 @@
longrun
@@ -0,0 +1,4 @@
#!/command/with-contenv bash
cd /var/www
exec python3 /var/www/app.py
@@ -0,0 +1 @@
longrun
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Chrony NTP Server Web UI for Home Assistant."""
import json
import os
import subprocess
from flask import Flask, render_template, jsonify
app = Flask(__name__)
OPTIONS_FILE = "/data/options.json"
def get_options():
"""Load current options from Home Assistant."""
try:
with open(OPTIONS_FILE, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {
"ntp_pools": [
{"pool": "pool.ntp.org", "iburst": True}
],
"ntp_servers": [
{"server": "time.google.com", "iburst": True}
],
"allow_clients": ["192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12"],
"enable_ntp_server": True,
"detailed_logging": False
}
def get_chrony_status():
"""Get current chrony synchronization status."""
status = {
"tracking": {},
"sources": [],
"clients": []
}
try:
# Get tracking info
result = subprocess.run(
["chronyc", "-c", "tracking"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
fields = result.stdout.strip().split(',')
if len(fields) >= 14:
status["tracking"] = {
"reference_id": fields[0],
"reference_name": fields[1],
"stratum": fields[2],
"ref_time": fields[3],
"system_time": fields[4],
"last_offset": fields[5],
"rms_offset": fields[6],
"frequency": fields[7],
"residual_freq": fields[8],
"skew": fields[9],
"root_delay": fields[10],
"root_dispersion": fields[11],
"update_interval": fields[12],
"leap_status": fields[13]
}
# Get sources
result = subprocess.run(
["chronyc", "-c", "sources"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
for line in result.stdout.strip().split('\n'):
if line:
fields = line.split(',')
if len(fields) >= 10:
status["sources"].append({
"mode": fields[0],
"state": fields[1],
"name": fields[2],
"stratum": fields[3],
"poll": fields[4],
"reach": fields[5],
"last_rx": fields[6],
"last_sample_offset": fields[7],
"last_sample_error": fields[8]
})
# Get clients (if server mode enabled)
result = subprocess.run(
["chronyc", "-c", "clients"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
for line in result.stdout.strip().split('\n'):
if line:
fields = line.split(',')
if len(fields) >= 5:
status["clients"].append({
"hostname": fields[0],
"ntp_requests": fields[1],
"drop": fields[2],
"last_rx": fields[4]
})
except subprocess.TimeoutExpired:
status["error"] = "Timeout getting chrony status"
except Exception as e:
status["error"] = str(e)
return status
@app.route('/')
def index():
"""Main dashboard page."""
options = get_options()
status = get_chrony_status()
return render_template('index.html', options=options, status=status)
@app.route('/api/status')
def api_status():
"""API endpoint for current status."""
return jsonify(get_chrony_status())
@app.route('/api/options')
def api_options():
"""API endpoint for current options."""
return jsonify(get_options())
@app.route('/api/force-sync', methods=['POST'])
def force_sync():
"""Force immediate time synchronization."""
try:
result = subprocess.run(
["chronyc", "makestep"],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
return jsonify({"success": True, "message": "Time step applied"})
else:
return jsonify({"success": False, "message": result.stderr}), 500
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
@app.route('/api/burst', methods=['POST'])
def burst_sync():
"""Trigger burst mode for faster synchronization."""
try:
result = subprocess.run(
["chronyc", "burst", "4/4"],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
return jsonify({"success": True, "message": "Burst mode activated"})
else:
return jsonify({"success": False, "message": result.stderr}), 500
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
if __name__ == '__main__':
# Get ingress port from environment
port = int(os.environ.get('INGRESS_PORT', 8099))
app.run(host='0.0.0.0', port=port, debug=False)
@@ -0,0 +1,477 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chrony NTP Server</title>
<style>
:root {
--primary-color: #03a9f4;
--background-color: #1c1c1c;
--card-background: #2c2c2c;
--text-color: #e0e0e0;
--text-secondary: #9e9e9e;
--success-color: #4caf50;
--warning-color: #ff9800;
--error-color: #f44336;
--border-color: #404040;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background-color: var(--background-color);
color: var(--text-color);
line-height: 1.6;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 1px solid var(--border-color);
}
h1 {
font-size: 24px;
font-weight: 500;
display: flex;
align-items: center;
gap: 10px;
}
h1 .icon {
font-size: 28px;
}
.status-badge {
padding: 6px 12px;
border-radius: 20px;
font-size: 14px;
font-weight: 500;
}
.status-synced {
background-color: rgba(76, 175, 80, 0.2);
color: var(--success-color);
}
.status-warning {
background-color: rgba(255, 152, 0, 0.2);
color: var(--warning-color);
}
.status-error {
background-color: rgba(244, 67, 54, 0.2);
color: var(--error-color);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
gap: 20px;
margin-bottom: 20px;
}
.card {
background-color: var(--card-background);
border-radius: 12px;
padding: 20px;
border: 1px solid var(--border-color);
}
.card h2 {
font-size: 16px;
font-weight: 500;
color: var(--text-secondary);
margin-bottom: 15px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.stat-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 15px;
}
.stat {
padding: 10px 0;
}
.stat-label {
font-size: 12px;
color: var(--text-secondary);
margin-bottom: 4px;
}
.stat-value {
font-size: 18px;
font-weight: 500;
color: var(--text-color);
}
.stat-value.mono {
font-family: 'SF Mono', Monaco, 'Courier New', monospace;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
text-align: left;
padding: 12px 8px;
border-bottom: 1px solid var(--border-color);
}
th {
font-size: 12px;
color: var(--text-secondary);
font-weight: 500;
text-transform: uppercase;
}
td {
font-size: 14px;
}
.source-state {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 8px;
}
.source-state.synced { background-color: var(--success-color); }
.source-state.combined { background-color: #8bc34a; }
.source-state.candidate { background-color: var(--primary-color); }
.source-state.unreachable { background-color: var(--text-secondary); }
.source-state.falseticker { background-color: var(--error-color); }
.source-state.variable { background-color: var(--warning-color); }
.button-group {
display: flex;
gap: 10px;
margin-top: 15px;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background-color: var(--primary-color);
color: white;
}
.btn-primary:hover {
background-color: #0288d1;
}
.btn-secondary {
background-color: var(--border-color);
color: var(--text-color);
}
.btn-secondary:hover {
background-color: #505050;
}
.config-list {
list-style: none;
}
.config-list li {
padding: 8px 0;
border-bottom: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
}
.config-list li:last-child {
border-bottom: none;
}
.tag {
font-size: 12px;
padding: 2px 8px;
border-radius: 4px;
background-color: var(--border-color);
}
.tag.enabled {
background-color: rgba(76, 175, 80, 0.2);
color: var(--success-color);
}
.refresh-info {
font-size: 12px;
color: var(--text-secondary);
text-align: center;
margin-top: 20px;
}
.toast {
position: fixed;
bottom: 20px;
right: 20px;
padding: 12px 24px;
border-radius: 8px;
background-color: var(--card-background);
border: 1px solid var(--border-color);
display: none;
animation: slideIn 0.3s ease;
}
.toast.success { border-color: var(--success-color); }
.toast.error { border-color: var(--error-color); }
@keyframes slideIn {
from { transform: translateY(100px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>
<span class="icon">🕐</span>
Chrony NTP Server
</h1>
{% if status.tracking.stratum and status.tracking.stratum != '0' %}
<span class="status-badge status-synced">● Synchronized</span>
{% else %}
<span class="status-badge status-warning">● Synchronizing</span>
{% endif %}
</header>
<div class="grid">
<div class="card">
<h2>Time Synchronization Status</h2>
<div class="stat-grid">
<div class="stat">
<div class="stat-label">Reference Server</div>
<div class="stat-value">{{ status.tracking.reference_name or 'N/A' }}</div>
</div>
<div class="stat">
<div class="stat-label">Stratum</div>
<div class="stat-value">{{ status.tracking.stratum or 'N/A' }}</div>
</div>
<div class="stat">
<div class="stat-label">System Time Offset</div>
<div class="stat-value mono">{{ status.tracking.system_time or 'N/A' }}</div>
</div>
<div class="stat">
<div class="stat-label">Frequency</div>
<div class="stat-value mono">{{ status.tracking.frequency or 'N/A' }} ppm</div>
</div>
<div class="stat">
<div class="stat-label">Root Delay</div>
<div class="stat-value mono">{{ status.tracking.root_delay or 'N/A' }}</div>
</div>
<div class="stat">
<div class="stat-label">Update Interval</div>
<div class="stat-value mono">{{ status.tracking.update_interval or 'N/A' }}s</div>
</div>
</div>
<div class="button-group">
<button class="btn btn-primary" onclick="forceSync()">Force Sync</button>
<button class="btn btn-secondary" onclick="burstSync()">Burst Mode</button>
</div>
</div>
<div class="card">
<h2>Configuration</h2>
<ul class="config-list">
<li>
<span>NTP Server Mode</span>
{% if options.enable_ntp_server %}
<span class="tag enabled">Enabled</span>
{% else %}
<span class="tag">Disabled</span>
{% endif %}
</li>
<li>
<span>Detailed Logging</span>
{% if options.detailed_logging %}
<span class="tag enabled">Enabled</span>
{% else %}
<span class="tag">Disabled</span>
{% endif %}
</li>
<li>
<span>NTP Pools</span>
<span class="tag">{{ options.ntp_pools|default([])|length }}</span>
</li>
<li>
<span>NTP Servers</span>
<span class="tag">{{ options.ntp_servers|default([])|length }}</span>
</li>
<li>
<span>Allowed Networks</span>
<span class="tag">{{ options.allow_clients|length }}</span>
</li>
</ul>
<p style="margin-top: 15px; font-size: 13px; color: var(--text-secondary);">
To modify settings, go to Add-on Configuration in Home Assistant.
</p>
</div>
</div>
<div class="card">
<h2>NTP Sources</h2>
<table>
<thead>
<tr>
<th>Status</th>
<th>Server</th>
<th>Stratum</th>
<th>Poll</th>
<th>Reach</th>
<th>Offset</th>
</tr>
</thead>
<tbody>
{% for source in status.sources %}
<tr>
<td>
{% if source.state == '*' %}
<span class="source-state synced"></span>Synced
{% elif source.state == '+' %}
<span class="source-state combined"></span>Combined
{% elif source.state == '-' %}
<span class="source-state candidate"></span>Candidate
{% elif source.state == '?' %}
<span class="source-state unreachable"></span>Unreachable
{% elif source.state == 'x' %}
<span class="source-state falseticker"></span>Falseticker
{% elif source.state == '~' %}
<span class="source-state variable"></span>Variable
{% else %}
<span class="source-state unreachable"></span>Unknown
{% endif %}
</td>
<td>{{ source.name }}</td>
<td>{{ source.stratum }}</td>
<td>{{ (2 ** (source.poll | int)) }}s</td>
<td>{{ source.reach }}</td>
<td>{{ source.last_sample_offset }}</td>
</tr>
{% else %}
<tr>
<td colspan="6" style="text-align: center; color: var(--text-secondary);">
No sources available yet. Chrony may still be starting up.
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if options.enable_ntp_server %}
<div class="card" style="margin-top: 20px;">
<h2>Connected Clients</h2>
<table>
<thead>
<tr>
<th>Client</th>
<th>NTP Requests</th>
<th>Dropped</th>
<th>Last Seen</th>
</tr>
</thead>
<tbody>
{% for client in status.clients %}
<tr>
<td>{{ client.hostname }}</td>
<td>{{ client.ntp_requests }}</td>
<td>{{ client.drop }}</td>
<td>{{ client.last_rx }}</td>
</tr>
{% else %}
<tr>
<td colspan="4" style="text-align: center; color: var(--text-secondary);">
No clients have connected yet.
</td>
</tr>
{% endfor %}
</tbody>
</table>
<h3 style="margin-top: 20px; font-size: 14px; color: var(--text-secondary);">Allowed Networks</h3>
<ul class="config-list" style="margin-top: 10px;">
{% for network in options.allow_clients %}
<li>{{ network }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<p class="refresh-info">Page auto-refreshes every 30 seconds • Last updated: <span id="lastUpdate"></span></p>
</div>
<div id="toast" class="toast"></div>
<script>
// Get base path for API calls (handles HA ingress prefix)
const basePath = window.location.pathname.replace(/\/$/, '');
// Update timestamp
document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString();
// Auto-refresh every 30 seconds
setTimeout(() => location.reload(), 30000);
function showToast(message, type) {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.className = 'toast ' + type;
toast.style.display = 'block';
setTimeout(() => toast.style.display = 'none', 3000);
}
function forceSync() {
fetch(basePath + '/api/force-sync', { method: 'POST' })
.then(r => r.json())
.then(data => {
showToast(data.message, data.success ? 'success' : 'error');
if (data.success) setTimeout(() => location.reload(), 1000);
})
.catch(() => showToast('Failed to connect', 'error'));
}
function burstSync() {
fetch(basePath + '/api/burst', { method: 'POST' })
.then(r => r.json())
.then(data => {
showToast(data.message, data.success ? 'success' : 'error');
})
.catch(() => showToast('Failed to connect', 'error'));
}
</script>
</body>
</html>