Files
ipwatch/mqtt/README.md
2026-02-07 16:57:37 +01:00

338 lines
8.7 KiB
Markdown

# 🔌 IPWatch MQTT - Contrôle à distance des équipements
Ce module permet de contrôler les équipements du réseau via MQTT (shutdown, reboot) de manière centralisée depuis IPWatch.
## 📋 Vue d'ensemble
L'architecture MQTT d'IPWatch permet de :
- **Éteindre** des machines à distance via commande MQTT
- **Redémarrer** des machines à distance via commande MQTT
- **Démarrer** des machines via Wake-on-LAN (WOL)
- **Monitorer** l'état des équipements en temps réel
- **Intégrer** avec Home Assistant pour la domotique
## 🏗️ Architecture
```
┌─────────────────┐ MQTT ┌──────────────────┐
│ IPWatch Web UI │ ──────────────────────► │ MQTT Broker │
│ (Frontend) │ │ (Mosquitto) │
└─────────────────┘ └──────────────────┘
│ │
│ HTTP API │ MQTT Topics
▼ ▼
┌─────────────────┐ ┌──────────────────┐
│ IPWatch Backend │ │ MQTT Agents │
│ (FastAPI) │ │ (sur machines) │
└─────────────────┘ └──────────────────┘
```
### Topics MQTT
- **Commandes** : `ipwatch/device/{IP_ADDRESS}/command`
- **Statut** : `ipwatch/device/{IP_ADDRESS}/status`
- **Disponibilité** : `ipwatch/device/{IP_ADDRESS}/availability`
- **Réponses** : `ipwatch/device/{IP_ADDRESS}/response`
### Format des messages
**Commande** :
```json
{
"command": "shutdown", // ou "reboot", "status"
"timestamp": "2025-12-23T10:30:00Z"
}
```
**Statut** :
```json
{
"hostname": "server-01",
"ip": "192.168.1.100",
"platform": "Linux",
"uptime": 86400,
"cpu_percent": 45.2,
"memory_percent": 62.5,
"timestamp": "2025-12-23T10:30:00Z"
}
```
## 🚀 Installation
### 1. Broker MQTT (serveur central)
```bash
# Installer Mosquitto
sudo apt update
sudo apt install mosquitto mosquitto-clients
# Démarrer le service
sudo systemctl enable mosquitto
sudo systemctl start mosquitto
# Vérifier le statut
sudo systemctl status mosquitto
```
### 2. Agent MQTT (sur chaque machine à contrôler)
```bash
# Copier l'agent
sudo cp mqtt/client/ipwatch_mqtt_agent.py /usr/local/bin/
sudo chmod +x /usr/local/bin/ipwatch_mqtt_agent.py
# Installer les dépendances Python
pip3 install paho-mqtt psutil netifaces
# Créer le dossier de configuration
sudo mkdir -p /etc/ipwatch
# Copier et éditer la configuration
sudo cp mqtt/client/mqtt-agent.conf.example /etc/ipwatch/mqtt-agent.conf
sudo nano /etc/ipwatch/mqtt-agent.conf
```
**Configuration** (`/etc/ipwatch/mqtt-agent.conf`) :
```ini
[mqtt]
broker = 192.168.1.10 # IP du serveur IPWatch
port = 1883
username = # Optionnel
password = # Optionnel
[agent]
hostname = auto
check_interval = 30
```
### 3. Service systemd
```bash
# Copier le service systemd
sudo cp mqtt/systemd/ipwatch-mqtt-agent.service /etc/systemd/system/
# Recharger systemd
sudo systemctl daemon-reload
# Activer et démarrer le service
sudo systemctl enable ipwatch-mqtt-agent
sudo systemctl start ipwatch-mqtt-agent
# Vérifier le statut
sudo systemctl status ipwatch-mqtt-agent
# Voir les logs
sudo journalctl -u ipwatch-mqtt-agent -f
```
### 4. Configuration IPWatch Backend
Dans le fichier `config.yaml` ou via variables d'environnement Docker :
```yaml
mqtt:
broker: localhost
port: 1883
username: ""
password: ""
```
Ou dans `docker-compose.yml` :
```yaml
environment:
- MQTT_BROKER=localhost
- MQTT_PORT=1883
- MQTT_USERNAME=
- MQTT_PASSWORD=
```
## 🔧 Configuration sudo (IMPORTANT)
Pour que l'agent puisse exécuter shutdown/reboot sans mot de passe :
```bash
# Éditer sudoers
sudo visudo
# Ajouter cette ligne (remplacer 'username' par l'utilisateur qui lance l'agent)
username ALL=(ALL) NOPASSWD: /sbin/shutdown, /sbin/reboot
```
Ou créer un fichier dédié :
```bash
echo "username ALL=(ALL) NOPASSWD: /sbin/shutdown, /sbin/reboot" | sudo tee /etc/sudoers.d/ipwatch-agent
sudo chmod 440 /etc/sudoers.d/ipwatch-agent
```
## 🧪 Tests
### Test de l'agent
```bash
# Mode test (affiche la config sans démarrer)
python3 /usr/local/bin/ipwatch_mqtt_agent.py --test
# Démarrage manuel (pour debug)
python3 /usr/local/bin/ipwatch_mqtt_agent.py
```
### Test manuel des commandes MQTT
```bash
# Publier une commande shutdown
mosquitto_pub -h localhost -t "ipwatch/device/192.168.1.100/command" -m '{"command":"shutdown"}'
# Publier une commande reboot
mosquitto_pub -h localhost -t "ipwatch/device/192.168.1.100/command" -m '{"command":"reboot"}'
# Demander le statut
mosquitto_pub -h localhost -t "ipwatch/device/192.168.1.100/command" -m '{"command":"status"}'
# Écouter les réponses
mosquitto_sub -h localhost -t "ipwatch/device/192.168.1.100/#" -v
```
## 📊 Utilisation depuis IPWatch
### Via l'interface Web
1. Accédez à la page **"Suivi"** (`/tracking`)
2. Cliquez sur le bouton **"Éteindre"** (rose) pour shutdown
3. Cliquez sur le bouton **"WOL"** (vert) pour démarrer
### Ajouter un bouton Reboot (optionnel)
Modifier `frontend/src/views/TrackingView.vue` pour ajouter un bouton reboot :
```vue
<button
@click="rebootDevice(ip)"
:disabled="ip.last_status === 'offline' || actionLoading[ip.ip]"
class="flex-1 px-3 py-2 rounded bg-monokai-orange text-monokai-bg font-bold hover:bg-yellow-600 transition-colors disabled:opacity-30"
title="Redémarrer l'équipement"
>
<span class="mdi mdi-restart"></span> Reboot
</button>
```
Et la fonction JavaScript :
```javascript
async function rebootDevice(ip) {
if (!confirm(`Voulez-vous vraiment redémarrer ${ip.name || ip.ip} ?`)) return
actionLoading.value[ip.ip] = 'reboot'
try {
await axios.post(`/api/tracking/reboot/${ip.ip}`)
alert(`✓ Commande reboot envoyée à ${ip.name || ip.ip}`)
setTimeout(() => fetchTrackedIPs(), 3000)
} catch (error) {
alert(`✗ Erreur reboot: ${error.response?.data?.detail || error.message}`)
} finally {
delete actionLoading.value[ip.ip]
}
}
```
## 🔐 Sécurité
### Authentification MQTT
```bash
# Créer un utilisateur MQTT
sudo mosquitto_passwd -c /etc/mosquitto/passwd ipwatch
# Configurer Mosquitto pour l'authentification
sudo nano /etc/mosquitto/mosquitto.conf
```
Ajouter :
```
allow_anonymous false
password_file /etc/mosquitto/passwd
```
Redémarrer Mosquitto :
```bash
sudo systemctl restart mosquitto
```
Mettre à jour la configuration des agents :
```ini
[mqtt]
broker = 192.168.1.10
port = 1883
username = ipwatch
password = VotreMotDePasse
```
### SSL/TLS (optionnel)
Pour sécuriser les communications MQTT :
```bash
# Générer un certificat
sudo openssl req -new -x509 -days 365 -extensions v3_ca -keyout /etc/mosquitto/ca.key -out /etc/mosquitto/ca.crt
```
Configuration Mosquitto avec SSL :
```
listener 8883
cafile /etc/mosquitto/ca.crt
certfile /etc/mosquitto/server.crt
keyfile /etc/mosquitto/server.key
```
## 📖 Documentation complémentaire
- [MQTT_ARCHITECTURE.md](docs/MQTT_ARCHITECTURE.md) - Architecture détaillée
- [MQTT_CODING_GUIDELINES.md](docs/MQTT_CODING_GUIDELINES.md) - Consignes de développement
- [HOMEASSISTANT_SPEC.md](docs/HOMEASSISTANT_SPEC.md) - Intégration Home Assistant
## 🐛 Dépannage
### L'agent ne se connecte pas
```bash
# Vérifier que Mosquitto écoute
sudo netstat -tlnp | grep 1883
# Vérifier les logs
sudo journalctl -u mosquitto -f
# Tester la connexion
mosquitto_sub -h localhost -t "test" -v
```
### Les commandes ne sont pas exécutées
```bash
# Vérifier les permissions sudo
sudo -l
# Vérifier les logs de l'agent
sudo journalctl -u ipwatch-mqtt-agent -f
# Tester manuellement
python3 /usr/local/bin/ipwatch_mqtt_agent.py
```
### Erreur "ModuleNotFoundError: No module named 'paho'"
```bash
# Réinstaller paho-mqtt
pip3 install --upgrade paho-mqtt
```
## 📞 Support
Pour toute question ou problème :
1. Consultez les logs : `sudo journalctl -u ipwatch-mqtt-agent -f`
2. Vérifiez la configuration : `python3 /usr/local/bin/ipwatch_mqtt_agent.py --test`
3. Testez manuellement avec `mosquitto_pub/sub`
## 🔄 Compatibilité Home Assistant
Ce système MQTT est conçu pour être compatible avec Home Assistant. Consultez [HOMEASSISTANT_SPEC.md](docs/HOMEASSISTANT_SPEC.md) pour l'intégration.
Les topics MQTT suivent la convention MQTT Discovery de Home Assistant pour une auto-découverte automatique.