Compare commits
48 Commits
d3ddb52125
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e6263c1ae2 | |||
| 4e7119297c | |||
| 5e3b5ee741 | |||
| 95a6bb10b1 | |||
| 42626f2204 | |||
| ac6b80cb69 | |||
| 88b0dd4e77 | |||
| 365c8e543f | |||
| 61ebf5a92f | |||
| 12a7495447 | |||
| 7de4c86feb | |||
| d48cb923eb | |||
| 2540a96a1e | |||
| fba9bc89e2 | |||
| 312ba59343 | |||
| 78e2f5ea1e | |||
| 790052dfe5 | |||
| 8074151300 | |||
| b2c083eb8d | |||
| 8b52a02b55 | |||
| 0aebf47f6b | |||
| 6541cefea0 | |||
| 3b05390ec4 | |||
| 35f3c6f5f7 | |||
| 763bc0ba48 | |||
| c9d6fd48ed | |||
| 3fd1c70bd7 | |||
| c280e4d5ac | |||
| adfe0ed282 | |||
| ae0c8f95cb | |||
| d31e193954 | |||
| 9e5d7456b6 | |||
| 1a612d0a4e | |||
| f2e86046d4 | |||
| 90925b4c5b | |||
| 6b8406ba3c | |||
| 9296b2f680 | |||
| 0ee29bf356 | |||
| 8a84be4f5a | |||
| 4e329c870f | |||
| a999510c6c | |||
| 4aaed529ea | |||
| 52f3c2ee6a | |||
| a972af5946 | |||
| b1088fc03d | |||
| 342703a727 | |||
| 4e8abc1d40 | |||
| 386d7f7ed6 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -19,3 +19,8 @@ Thumbs.db
|
||||
*.log
|
||||
__pycache__/
|
||||
.env
|
||||
|
||||
|
||||
prep.sh
|
||||
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
name: Generate SHA256 Hashes
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
hash:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Generate Hashes
|
||||
run: |
|
||||
# On boucle sur tous les fichiers .sh dans le dossier spécifique
|
||||
cd servers/linux/
|
||||
for file in *.sh; do
|
||||
sha256sum "$file" > "${file}.sha256"
|
||||
done
|
||||
|
||||
- name: Commit and Push
|
||||
run: |
|
||||
git config --global user.name "Gitea Action"
|
||||
git config --global user.email "actions@noreply.gitea.io"
|
||||
git add servers/linux/*.sha256
|
||||
git diff --quiet && git diff --staged --quiet || git commit -m "Auto-update SHA256 hashes"
|
||||
git push
|
||||
@@ -1,24 +0,0 @@
|
||||
name: Generate SHA256 Hashes
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
hash:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Generate Hashes
|
||||
run: |
|
||||
# On boucle sur tous les fichiers .sh dans le dossier spécifique
|
||||
cd servers/linux/
|
||||
for file in *.sh; do
|
||||
sha256sum "$file" > "${file}.sha256"
|
||||
done
|
||||
|
||||
- name: Commit and Push
|
||||
run: |
|
||||
git config --global user.name "Gitea Action"
|
||||
git config --global user.email "actions@noreply.gitea.io"
|
||||
git add servers/linux/*.sha256
|
||||
git diff --quiet && git diff --staged --quiet || git commit -m "Auto-update SHA256 hashes"
|
||||
git push
|
||||
@@ -10,16 +10,68 @@ fi
|
||||
|
||||
# --- 1. CONFIGURATION DYNAMIQUE ---
|
||||
HOSTNAME=$(hostname)
|
||||
SMTP_HOST="mail.acemail.fr"
|
||||
SMTP_PORT="587"
|
||||
SMTP_USER="srv@a5l.fr"
|
||||
DEST_EMAIL="cedric+${HOSTNAME}@abonnel.fr"
|
||||
|
||||
MSMTP_CONF="/etc/msmtprc"
|
||||
GLOBAL_CONF="/etc/sys_check.conf"
|
||||
|
||||
# Valeurs "Fallback" (anonymisées)
|
||||
DEFAULT_SMTP_HOST="smtp.exemple.fr"
|
||||
DEFAULT_SMTP_PORT="587"
|
||||
DEFAULT_SMTP_USER="alerte@exemple.fr"
|
||||
DEFAULT_DEST_EMAIL="admin+${HOSTNAME}@exemple.fr"
|
||||
SUBJECT_PREFIX="[$HOSTNAME]"
|
||||
|
||||
# Valeurs "Fallback" NTFY
|
||||
DEFAULT_NTFY_SERVER="https://ntfy.sh"
|
||||
DEFAULT_NTFY_TOPIC=""
|
||||
DEFAULT_NTFY_TOKEN=""
|
||||
|
||||
# Tentative d'extraction des valeurs actuelles si le fichier existe
|
||||
if [ -f "$MSMTP_CONF" ]; then
|
||||
CURRENT_HOST=$(grep -E "^host[[:space:]]+" "$MSMTP_CONF" | awk '{print $2}')
|
||||
CURRENT_PORT=$(grep -E "^port[[:space:]]+" "$MSMTP_CONF" | awk '{print $2}')
|
||||
CURRENT_USER=$(grep -E "^user[[:space:]]+" "$MSMTP_CONF" | awk '{print $2}')
|
||||
|
||||
# Si on a trouvé des infos, on les utilise comme nouvelles valeurs par défaut
|
||||
[ -n "$CURRENT_HOST" ] && DEFAULT_SMTP_HOST="$CURRENT_HOST"
|
||||
[ -n "$CURRENT_PORT" ] && DEFAULT_SMTP_PORT="$CURRENT_PORT"
|
||||
[ -n "$CURRENT_USER" ] && DEFAULT_SMTP_USER="$CURRENT_USER"
|
||||
fi
|
||||
|
||||
# Tentative d'extraction NTFY si le fichier global existe déjà
|
||||
if [ -f "$GLOBAL_CONF" ]; then
|
||||
source "$GLOBAL_CONF"
|
||||
[ -n "$NTFY_SERVER" ] && DEFAULT_NTFY_SERVER="$NTFY_SERVER"
|
||||
[ -n "$NTFY_TOPIC" ] && DEFAULT_NTFY_TOPIC="$NTFY_TOPIC"
|
||||
[ -n "$NTFY_TOKEN" ] && DEFAULT_NTFY_TOKEN="$NTFY_TOKEN"
|
||||
fi
|
||||
|
||||
|
||||
echo "=========================================================="
|
||||
echo " VÉRIFICATION SMTP & DÉPLOIEMENT - ${HOSTNAME}"
|
||||
echo "=========================================================="
|
||||
|
||||
# Fonction pour demander une valeur avec une valeur par défaut
|
||||
prompt_value() {
|
||||
local var_name=$1
|
||||
local prompt_text=$2
|
||||
local default_value=$3
|
||||
read -p "$prompt_text [$default_value] : " input
|
||||
eval "$var_name=\"${input:-$default_value}\""
|
||||
}
|
||||
|
||||
# Collecte interactive
|
||||
echo "--- Configuration Mail ---"
|
||||
prompt_value "SMTP_HOST" "Serveur SMTP" "$DEFAULT_SMTP_HOST"
|
||||
prompt_value "SMTP_PORT" "Port SMTP" "$DEFAULT_SMTP_PORT"
|
||||
prompt_value "SMTP_USER" "Utilisateur SMTP" "$DEFAULT_SMTP_USER"
|
||||
prompt_value "DEST_EMAIL" "Email de destination" "$DEFAULT_DEST_EMAIL"
|
||||
|
||||
echo -e "\n--- Configuration ntfy.sh (Optionnel) ---"
|
||||
prompt_value "NTFY_SERVER" "Serveur ntfy" "$DEFAULT_NTFY_SERVER"
|
||||
prompt_value "NTFY_TOPIC" "Topic ntfy (laisser vide pour désactiver)" "$DEFAULT_NTFY_TOPIC"
|
||||
prompt_value "NTFY_TOKEN" "Token ntfy (laisser vide si aucun)" "$DEFAULT_NTFY_TOKEN"
|
||||
|
||||
|
||||
# --- 2. INSTALLATION INITIALE ---
|
||||
DEBIAN_FRONTEND=noninteractive apt update
|
||||
@@ -29,22 +81,17 @@ DEBIAN_FRONTEND=noninteractive apt install -y curl bc
|
||||
|
||||
|
||||
# --- 3. RÉCUPÉRATION ET TEST DU MOT DE PASSE SMTP ---
|
||||
# Ici, PASS_FILE_ORI pointe probablement vers /etc/msmtprc ou une sauvegarde
|
||||
PASS_FILE_ORI="/etc/msmtprc"
|
||||
AUTH_OK=false
|
||||
|
||||
while [ "$AUTH_OK" = false ]; do
|
||||
# 1. Tentative d'extraction depuis le fichier de config existant
|
||||
if [ -f "$PASS_FILE_ORI" ]; then
|
||||
# On cherche la ligne commençant par 'password', on ignore les espaces/tabulations,
|
||||
# et on récupère la deuxième colonne.
|
||||
SMTP_PASS=$(grep -E "^password[[:space:]]+" "$PASS_FILE_ORI" | awk '{print $2}')
|
||||
if [ -f "$MSMTP_CONF" ] && [ "$SMTP_USER" = "$CURRENT_USER" ]; then
|
||||
SMTP_PASS=$(grep -E "^password[[:space:]]+" "$MSMTP_CONF" | awk '{print $2}')
|
||||
fi
|
||||
|
||||
if [ -n "$SMTP_PASS" ]; then
|
||||
echo "📄 Mot de passe extrait depuis $PASS_FILE_ORI."
|
||||
echo "📄 Mot de passe existant récupéré pour $SMTP_USER."
|
||||
else
|
||||
# 2. Sinon, saisie manuelle si le fichier n'existe pas ou ne contient pas de password
|
||||
echo -n "🔑 Mot de passe SMTP non trouvé. Entrez le pour ${SMTP_USER} : "
|
||||
read -s SMTP_PASS
|
||||
echo ""
|
||||
@@ -53,7 +100,8 @@ while [ "$AUTH_OK" = false ]; do
|
||||
echo "⏳ Vérification de la connexion SMTP..."
|
||||
|
||||
# Création config temporaire pour le test
|
||||
cat > /tmp/.msmtp_test <<EOF
|
||||
TMP_TEST=$(mktemp)
|
||||
cacat > "$TMP_TEST" <<EOF
|
||||
defaults
|
||||
auth on
|
||||
tls on
|
||||
@@ -66,24 +114,24 @@ user $SMTP_USER
|
||||
password $SMTP_PASS
|
||||
account default : test
|
||||
EOF
|
||||
chmod 600 /tmp/.msmtp_test
|
||||
chmod 600 "$TMP_TEST"
|
||||
|
||||
# Test d'envoi réel
|
||||
echo "Test de configuration" | msmtp --file=/tmp/.msmtp_test -t "$DEST_EMAIL" 2>/dev/null
|
||||
echo "Test de configuration" | msmtp --file="$TMP_TEST" -t "$DEST_EMAIL" 2>/dev/null
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "✅ Authentification SMTP réussie !"
|
||||
AUTH_OK=true
|
||||
rm /tmp/.msmtp_test
|
||||
rm -f "$TMP_TEST"
|
||||
else
|
||||
echo "❌ Échec de l'authentification SMTP."
|
||||
# Si le password extrait était mauvais, on vide la variable pour forcer la saisie au prochain tour
|
||||
if [ -f "$PASS_FILE_ORI" ]; then
|
||||
echo "⚠️ Le mot de passe extrait de $PASS_FILE_ORI est incorrect."
|
||||
if [ -f "$MSMTP_CONF" ]; then
|
||||
echo "⚠️ Le mot de passe extrait de $MSMTP_CONF est incorrect."
|
||||
SMTP_PASS=""
|
||||
PASS_FILE_ORI="/dev/null" # On "désactive" la lecture fichier pour ce tour
|
||||
MSMTP_CONF="/dev/null" # On "désactive" la lecture fichier pour ce tour
|
||||
fi
|
||||
rm /tmp/.msmtp_test
|
||||
rm -f "$TMP_TEST"
|
||||
fi
|
||||
done
|
||||
|
||||
@@ -179,7 +227,22 @@ fi
|
||||
# Nettoyage du fichier temporaire
|
||||
rm -f "$TMP_MSMTP"
|
||||
|
||||
h flo
|
||||
|
||||
# --- 5b. CONFIGURATION GLOBALE SCRIPTS ---
|
||||
echo "--- Génération de la configuration globale /etc/scripts-config.conf ---"
|
||||
cat > "$GLOBAL_CONF" <<EOF
|
||||
# Configuration générée le $(date)
|
||||
DEST="$DEST_EMAIL"
|
||||
NTFY_SERVER="$NTFY_SERVER"
|
||||
NTFY_TOPIC="$NTFY_TOPIC"
|
||||
NTFY_TOKEN="$NTFY_TOKEN"
|
||||
EOF
|
||||
|
||||
# Sécurisation du fichier (lecture seule pour root car peut contenir le token ntfy)
|
||||
chown root:root "$GLOBAL_CONF"
|
||||
chmod 600 "$GLOBAL_CONF"
|
||||
|
||||
|
||||
# --- 6. INTERCEPTION GLOBALE (LE WRAPPER) ---
|
||||
echo "--- 6. Création du wrapper sendmail pour préfixer les objets ---"
|
||||
# On crée un script qui va modifier le sujet à la volée
|
||||
|
||||
1
servers/linux/config_adminSys.sh.sha256
Normal file
1
servers/linux/config_adminSys.sh.sha256
Normal file
@@ -0,0 +1 @@
|
||||
97b479fe4da550d1f3712ac3fa2ab42aa0624442a09953432400f1b40e7c8806 config_adminSys.sh
|
||||
0
servers/linux/manifest.txt
Normal file
0
servers/linux/manifest.txt
Normal file
213
servers/linux/monitoring/LICENSE
Normal file
213
servers/linux/monitoring/LICENSE
Normal file
@@ -0,0 +1,213 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
TERMS AND CONDITIONS
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <https://www.gnu.org/licenses/>.
|
||||
89
servers/linux/monitoring/README.md
Normal file
89
servers/linux/monitoring/README.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# 🛡️ PHP Monitoring System by Cédrix
|
||||
|
||||
Ce projet est une solution de monitoring **légère**, **modulaire** et **auto-hébergée** pour serveurs Linux. Elle combine la simplicité de sondes Bash avec la puissance d'un moteur de traitement PHP pour centraliser les logs et envoyer des alertes intelligentes via **ntfy** ou **email**.
|
||||
|
||||
## 🚀 Fonctionnalités clés
|
||||
|
||||
* **Moteur PHP & Sondes Hybrides :** Traitement performant des alertes en PHP, tout en gardant des sondes système simples (Bash ou PHP).
|
||||
* **Alertes Intelligentes :** Envoi via **ntfy** (avec tags et priorités) ou **email**, incluant un système de **déduplication** pour éviter le spam.
|
||||
* **Logs JSONL :** Centralisation au format standard `JSON Lines` dans `/var/log/monitoring/events.jsonl` pour une exploitation facile.
|
||||
* **Configuration en cascade :** Système de fichiers `.local.conf.php` pour protéger vos réglages lors des mises à jour.
|
||||
* **Auto-update & Audit :** Mise à jour automatique via manifeste et script d'audit pour détecter les nouvelles options de configuration manquantes.
|
||||
|
||||
---
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
L'installation se fait via un script Bash qui configure l'environnement et installe les dépendances nécessaires (PHP, curl).
|
||||
|
||||
```bash
|
||||
# Passer en root
|
||||
sudo -s
|
||||
|
||||
# Télécharger et lancer l'installateur
|
||||
curl -sSL https://git.abonnel.fr/cedricAbonnel/scripts-bash/raw/branch/main/servers/linux/monitoring/bin/install-monitoring.sh | bash
|
||||
|
||||
```
|
||||
|
||||
### Structure du système :
|
||||
|
||||
* `/opt/monitoring/bin/` : Exécutables (sondes, moteur `alert-engine.php`, updater).
|
||||
* `/opt/monitoring/lib/` : Bibliothèque partagée (`monitoring-lib.php`).
|
||||
* `/opt/monitoring/conf/` : Fichiers de configuration PHP.
|
||||
* `/var/log/monitoring/` : Journal des événements (`events.jsonl`).
|
||||
* `/var/lib/monitoring/` : Index (offsets de lecture, états de déduplication).
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Configuration
|
||||
|
||||
Le système utilise des fichiers PHP pour la configuration afin de permettre une logique dynamique.
|
||||
|
||||
### 1. Alertes (ntfy / Mail)
|
||||
|
||||
Ne modifiez pas les fichiers `.conf.php` (risques d'écrasement). Créez vos fichiers locaux :
|
||||
`cp /opt/monitoring/conf/alert-engine.conf.php /opt/monitoring/conf/alert-engine.local.conf.php`
|
||||
|
||||
Éditez le fichier local pour renseigner :
|
||||
|
||||
* `NTFY_TOKEN` & `NTFY_TOPIC`.
|
||||
* `DEST` (votre email de réception).
|
||||
|
||||
### 2. Audit de configuration
|
||||
|
||||
Après une mise à jour, lancez l'outil d'audit pour vérifier si de nouvelles options sont disponibles :
|
||||
|
||||
```bash
|
||||
php /opt/monitoring/bin/monitoring-update-config.php
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🕒 Planification (Crontab)
|
||||
|
||||
Le système est conçu pour être piloté par `cron`. Voici la configuration recommandée :
|
||||
|
||||
| Tâche | Fréquence | Commande |
|
||||
| --- | --- | --- |
|
||||
| **Sondes (ex: Disque)** | Toutes les 5 min | `php /opt/monitoring/bin/check_disk.php` |
|
||||
| **Moteur d'alerte** | Chaque minute | `php /opt/monitoring/bin/alert-engine.php` |
|
||||
| **Mise à jour** | 1x par jour | `php /opt/monitoring/bin/monitoring-update.php` |
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Développer une nouvelle sonde
|
||||
|
||||
Le système est agnostique. Pour ajouter un check :
|
||||
|
||||
1. Créez un script qui écrit une ligne JSON dans `/var/log/monitoring/events.jsonl`.
|
||||
2. Format attendu : `{"time":"...", "level":"ERROR", "app":"my_app", "event":"disk_full", "msg":"..."}`.
|
||||
3. Le moteur PHP `alert-engine.php` traitera l'alerte automatiquement au prochain passage.
|
||||
|
||||
---
|
||||
|
||||
## ⚖️ Licence
|
||||
|
||||
Ce projet est distribué sous licence **GNU Affero General Public License (AGPLv3)**.
|
||||
|
||||
*Note : Si vous modifiez ce code pour l'utiliser via un réseau (SaaS), vous devez rendre vos modifications publiques.*
|
||||
253
servers/linux/monitoring/bin/alert-engine.php
Executable file
253
servers/linux/monitoring/bin/alert-engine.php
Executable file
@@ -0,0 +1,253 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* Alert Engine - PHP Version
|
||||
* Copyright (C) 2026 Cédric Abonnel
|
||||
* License: GNU Affero General Public License v3
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../lib/monitoring-lib.php';
|
||||
|
||||
// --- Initialisation de la configuration spécifique ---
|
||||
// On charge les fichiers de conf s'ils existent
|
||||
foreach (["/opt/monitoring/conf/alert-engine.conf.php", "/opt/monitoring/conf/alert-engine.conf.local.php"] as $conf) {
|
||||
if (file_exists($conf)) {
|
||||
$extra_conf = include $conf;
|
||||
if (is_array($extra_conf)) {
|
||||
$CONFIG = array_replace_recursive($CONFIG, $extra_conf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Chemins des fichiers
|
||||
$LOG_SOURCE = $CONFIG['LOG_FILE'] ?? '/var/log/monitoring/events.jsonl';
|
||||
$STATE_FILE = $CONFIG['ALERT_STATE_FILE'] ?? '/var/lib/monitoring/alert-engine.offset';
|
||||
$DEDUP_FILE = $CONFIG['ALERT_DEDUP_FILE'] ?? '/var/lib/monitoring/alert-engine.dedup';
|
||||
$DEDUP_WINDOW = $CONFIG['ALERT_DEDUP_WINDOW'] ?? 3600;
|
||||
|
||||
// Création des répertoires si nécessaire
|
||||
ensure_parent_dir($STATE_FILE);
|
||||
ensure_parent_dir($DEDUP_FILE);
|
||||
|
||||
/**
|
||||
* Nettoyage du fichier de déduplication
|
||||
* Supprime les entrées plus vieilles que la fenêtre de déduplication ($DEDUP_WINDOW)
|
||||
*/
|
||||
function cleanup_dedup_file() {
|
||||
global $DEDUP_FILE, $DEDUP_WINDOW;
|
||||
|
||||
// Si le fichier n'existe pas, rien à nettoyer
|
||||
if (!file_exists($DEDUP_FILE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$kept = [];
|
||||
$has_changed = false;
|
||||
|
||||
// Lecture du fichier
|
||||
$lines = file($DEDUP_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
if ($lines === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$parts = explode('|', $line);
|
||||
|
||||
// On vérifie si la ligne est valide et si le timestamp (index 1) est encore dans la fenêtre
|
||||
if (count($parts) >= 2) {
|
||||
$timestamp = (int)$parts[1];
|
||||
if (($now - $timestamp) <= (int)$DEDUP_WINDOW) {
|
||||
$kept[] = $line;
|
||||
} else {
|
||||
$has_changed = true; // On a trouvé au moins une ligne à supprimer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On ne réécrit le fichier que si des lignes ont été supprimées
|
||||
if ($has_changed) {
|
||||
$content = implode("\n", $kept);
|
||||
if (!empty($content)) {
|
||||
$content .= "\n";
|
||||
}
|
||||
|
||||
// LOCK_EX évite que deux instances n'écrivent en même temps
|
||||
file_put_contents($DEDUP_FILE, $content, LOCK_EX);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si une alerte doit être envoyée (Déduplication)
|
||||
* La clé attendue est : "hostname|app|level|event"
|
||||
*/
|
||||
function should_notify_dedup(string $key): bool {
|
||||
global $DEDUP_FILE, $DEDUP_WINDOW;
|
||||
|
||||
if (!file_exists($DEDUP_FILE)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$last_ts = 0;
|
||||
|
||||
$handle = fopen($DEDUP_FILE, 'r');
|
||||
if (!$handle) {
|
||||
return true; // En cas d'erreur de lecture, on autorise l'alerte par sécurité
|
||||
}
|
||||
|
||||
// On parcourt le fichier
|
||||
while (($line = fgets($handle)) !== false) {
|
||||
$line = trim($line);
|
||||
if (empty($line)) continue;
|
||||
|
||||
$p = explode('|', $line);
|
||||
|
||||
// Format du fichier : host|timestamp|app|level|event
|
||||
// On reconstruit la clé de comparaison (sans le timestamp index 1)
|
||||
if (count($p) >= 5) {
|
||||
$row_key = "{$p[0]}|{$p[2]}|{$p[3]}|{$p[4]}";
|
||||
|
||||
if ($row_key === $key) {
|
||||
$last_ts = (int)$p[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose($handle);
|
||||
|
||||
// Calcul de l'écart : vrai si on a dépassé la fenêtre ou si jamais vu (last_ts = 0)
|
||||
return ($now - $last_ts) >= (int)$DEDUP_WINDOW;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Envoi vers ntfy
|
||||
*/
|
||||
function send_ntfy($title, $body, $level) {
|
||||
global $CONFIG;
|
||||
if (!($CONFIG['ALERT_NTFY_ENABLED'] ?? true)) return true;
|
||||
if (empty($CONFIG['NTFY_SERVER']) || empty($CONFIG['NTFY_TOPIC'])) return false;
|
||||
|
||||
$priority = ['CRITICAL' => 'urgent', 'ERROR' => 'high', 'WARNING' => 'default'][$level] ?? 'default';
|
||||
$tags = ($CONFIG['NTFY_TAGS'][$level]) ?? 'warning';
|
||||
|
||||
$url = rtrim($CONFIG['NTFY_SERVER'], '/') . '/' . $CONFIG['NTFY_TOPIC'];
|
||||
$headers = ["Title: $title", "Priority: $priority", "Tags: $tags"];
|
||||
|
||||
if (!empty($CONFIG['NTFY_TOKEN'])) {
|
||||
$headers[] = "Authorization: Bearer " . $CONFIG['NTFY_TOKEN'];
|
||||
}
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt($ch, CURLOPT_POST, 1);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
|
||||
curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
return ($status >= 200 && $status < 300);
|
||||
}
|
||||
|
||||
/**
|
||||
* Envoi par mail
|
||||
*/
|
||||
function send_mail($subject, $body) {
|
||||
global $CONFIG;
|
||||
if (!($CONFIG['ALERT_MAIL_ENABLED'] ?? true)) return true;
|
||||
if (empty($CONFIG['DEST'])) return false;
|
||||
|
||||
$prefix = $CONFIG['ALERT_MAIL_SUBJECT_PREFIX'] ?? '[monitoring]';
|
||||
$headers = "From: monitoring@" . gethostname() . "\r\n" . "Content-Type: text/plain; charset=UTF-8";
|
||||
|
||||
return mail($CONFIG['DEST'], "$prefix $subject", $body, $headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Traitement d'une ligne de log
|
||||
*/
|
||||
function process_line($line) {
|
||||
global $CONFIG, $DEDUP_FILE;
|
||||
$data = json_decode($line, true);
|
||||
if (!$data || !isset($data['level'], $data['event'])) return;
|
||||
|
||||
$level = strtoupper($data['level']);
|
||||
$event = $data['event'];
|
||||
|
||||
// On garde uniquement l'ignore list explicite pour les événements
|
||||
if (in_array($event, ($CONFIG['ALERT_IGNORE_EVENTS'] ?? []))) return;
|
||||
|
||||
// Déduplication
|
||||
$key = "{$data['host']}|{$data['app']}|{$level}|{$event}";
|
||||
if (!should_notify_dedup($key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Détermination des canaux
|
||||
$channels_str = $CONFIG['RULES'][$event] ?? $CONFIG['DEFAULT_CHANNELS'][$level] ?? '';
|
||||
|
||||
// Si aucun canal n'est défini pour ce niveau, ALORS on s'arrête
|
||||
if (empty($channels_str)) return;
|
||||
|
||||
$channels = explode(',', $channels_str);
|
||||
|
||||
$title = "{$data['host']} [{$data['app']}] $level $event";
|
||||
$body = sprintf(
|
||||
"Date: %s\nHôte: %s\nScript: %s\nNiveau: %s\nÉvénement: %s\n\nMessage:\n%s",
|
||||
$data['ts'] ?? 'N/A', $data['host'], $data['app'], $level, $event, $data['message'] ?? ''
|
||||
);
|
||||
|
||||
foreach ($channels as $ch) {
|
||||
$ch = trim($ch);
|
||||
$success = false;
|
||||
if ($ch === 'ntfy') {
|
||||
$success = send_ntfy($title, $body, $level);
|
||||
$success ? log_info("alert_sent_ntfy", "Notification ntfy envoyée", ["event=$event"])
|
||||
: log_error("alert_ntfy_failed", "Échec ntfy", ["event=$event"]);
|
||||
} elseif ($ch === 'mail') {
|
||||
$success = send_mail($title, $body);
|
||||
$success ? log_info("alert_sent_mail", "Mail envoyé", ["event=$event"])
|
||||
: log_error("alert_mail_failed", "Échec mail", ["event=$event"]);
|
||||
}
|
||||
}
|
||||
|
||||
// Enregistrement déduplication
|
||||
$entry = sprintf("%s|%s|%s|%s|%s\n", $data['host'], time(), $data['app'], $level, $event);
|
||||
file_put_contents($DEDUP_FILE, $entry, FILE_APPEND);
|
||||
}
|
||||
|
||||
// --- Main ---
|
||||
|
||||
lock_or_exit("alert-engine");
|
||||
|
||||
if (!file_exists($LOG_SOURCE)) {
|
||||
log_notice("alert_log_missing", "Fichier de log absent", ["file=$LOG_SOURCE"]);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
$last_offset = file_exists($STATE_FILE) ? (int)file_get_contents($STATE_FILE) : 0;
|
||||
$current_size = filesize($LOG_SOURCE);
|
||||
|
||||
// Gestion de la rotation de log
|
||||
if ($last_offset > $current_size) {
|
||||
log_notice("alert_offset_reset", "Rotation détectée", ["old=$last_offset", "new=0"]);
|
||||
$last_offset = 0;
|
||||
}
|
||||
|
||||
cleanup_dedup_file();
|
||||
|
||||
$fp = fopen($LOG_SOURCE, 'r');
|
||||
if ($last_offset > 0) fseek($fp, $last_offset);
|
||||
|
||||
while (($line = fgets($fp)) !== false) {
|
||||
if (trim($line) !== '') {
|
||||
process_line($line);
|
||||
}
|
||||
}
|
||||
fclose($fp);
|
||||
|
||||
file_put_contents($STATE_FILE, $current_size);
|
||||
exit_with_status();
|
||||
61
servers/linux/monitoring/bin/check_disk.sh
Executable file
61
servers/linux/monitoring/bin/check_disk.sh
Executable file
@@ -0,0 +1,61 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2026 Cédric Abonnel
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
set -u
|
||||
|
||||
# --- Configuration (Seuils par défaut) ---
|
||||
WARNING=80
|
||||
CRITICAL=95
|
||||
MOUNTS=("/" "/var" "/home")
|
||||
LOG_BIN="/opt/monitoring/bin/log-cli.php"
|
||||
|
||||
# --- Vérification ROOT ---
|
||||
if [ "${EUID}" -ne 0 ]; then
|
||||
echo "ERREUR : Ce script doit être exécuté en tant que root." >&2
|
||||
$LOG_BIN ERROR "internal_error" "Tentative d'exécution sans privilèges root."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for mount in "${MOUNTS[@]}"; do
|
||||
if ! mountpoint -q "$mount"; then continue; fi
|
||||
|
||||
# --- 1. Espace Disque ---
|
||||
used_pct="$(df -P "$mount" 2>/dev/null | awk 'NR==2 {gsub("%","",$5); print $5}')"
|
||||
|
||||
if [[ ! "$used_pct" =~ ^[0-9]+$ ]]; then
|
||||
$LOG_BIN ERROR "check_failed" "Erreur lecture disque $mount."
|
||||
else
|
||||
if [ "$used_pct" -ge "$CRITICAL" ]; then
|
||||
$LOG_BIN CRITICAL "disk_usage_critical" "Disque $mount critique : $used_pct% utilisé."
|
||||
elif [ "$used_pct" -ge "$WARNING" ]; then
|
||||
$LOG_BIN WARNING "disk_usage_high" "Disque $mount élevé : $used_pct% utilisé."
|
||||
else
|
||||
$LOG_BIN INFO "disk_ok" "Disque $mount OK : $used_pct% utilisé."
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- 2. Inodes (Déplacé à l'intérieur de la boucle) ---
|
||||
inode_pct="$(df -iP "$mount" 2>/dev/null | awk 'NR==2 {gsub("%","",$5); print $5}')"
|
||||
|
||||
if [[ ! "$inode_pct" =~ ^[0-9]+$ ]]; then
|
||||
$LOG_BIN ERROR "check_failed" "Erreur lecture inodes $mount."
|
||||
else
|
||||
if [ "$inode_pct" -ge "$CRITICAL" ]; then
|
||||
$LOG_BIN CRITICAL "inode_usage_critical" "Inodes $mount critiques ($inode_pct%)."
|
||||
elif [ "$inode_pct" -ge "$WARNING" ]; then
|
||||
$LOG_BIN WARNING "inode_usage_high" "Inodes $mount élevés ($inode_pct%)."
|
||||
else
|
||||
$LOG_BIN INFO "inode_ok" "Inodes $mount OK ($inode_pct%)."
|
||||
fi
|
||||
fi
|
||||
done
|
||||
66
servers/linux/monitoring/bin/check_smart.sh
Executable file
66
servers/linux/monitoring/bin/check_smart.sh
Executable file
@@ -0,0 +1,66 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
LOG_BIN="/opt/monitoring/bin/log-cli.php"
|
||||
|
||||
# --- Vérification ROOT ---
|
||||
if [ "${EUID}" -ne 0 ]; then
|
||||
echo "ERREUR : Ce script doit être exécuté en tant que root." >&2
|
||||
$LOG_BIN ERROR "internal_error" "Tentative d'exécution sans privilèges root."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- Vérification et installation de smartctl ---
|
||||
if ! command -v smartctl >/dev/null 2>&1; then
|
||||
# On tente l'installation (nécessite root, ce qui est le cas via cron)
|
||||
if command -v apt-get >/dev/null 2>&1; then
|
||||
apt-get update && apt-get install -y smartmontools
|
||||
fi
|
||||
|
||||
# Re-vérification après tentative
|
||||
if ! command -v smartctl >/dev/null 2>&1; then
|
||||
$LOG_BIN ERROR "internal_error" "smartctl non trouvé et installation impossible."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# On récupère les disques qui ont un transport physique (SATA, NVMe, USB)
|
||||
# Cela exclut d'office les /dev/mapper, /dev/dm-X, /dev/loopX
|
||||
DISKS=$(lsblk -dno NAME,TRAN | awk '$2!="" {print "/dev/"$1}')
|
||||
|
||||
for disk in $DISKS; do
|
||||
# Vérification : est-ce que smartctl peut lire ce périphérique ?
|
||||
# --scan-open vérifie si le disque est capable de répondre
|
||||
if ! smartctl -i "$disk" | grep -q "SMART support is: Enabled" 2>/dev/null; then
|
||||
# On peut logguer en INFO que le disque est ignoré car non-SMART (ex: clé USB basique)
|
||||
continue
|
||||
fi
|
||||
|
||||
# 1. État de santé global
|
||||
smart_output=$(smartctl -H "$disk" 2>/dev/null)
|
||||
exit_code=$?
|
||||
|
||||
if [ $exit_code -ne 0 ]; then
|
||||
$LOG_BIN CRITICAL "smart_health_bad" "État de santé PHYSIQUE CRITIQUE sur $disk"
|
||||
else
|
||||
# 2. Température
|
||||
temp=$(smartctl -A "$disk" 2>/dev/null | awk '/Temperature_Celsius/ {print $10}' | head -n 1)
|
||||
[ -z "$temp" ] && temp=$(smartctl -a "$disk" 2>/dev/null | awk '/Temperature:/ {print $2}' | head -n 1)
|
||||
|
||||
if [ -n "$temp" ]; then
|
||||
if [ "$temp" -ge 60 ]; then
|
||||
$LOG_BIN WARNING "disk_temp_high" "Surchauffe physique sur $disk : ${temp}°C"
|
||||
fi
|
||||
fi
|
||||
$LOG_BIN INFO "smart_health_ok" "Disque physique $disk sain."
|
||||
fi
|
||||
done
|
||||
187
servers/linux/monitoring/bin/install-monitoring.sh
Executable file
187
servers/linux/monitoring/bin/install-monitoring.sh
Executable file
@@ -0,0 +1,187 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2026 Cédric Abonnel
|
||||
# License: GNU Affero General Public License v3
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# --- Configuration ---
|
||||
BASE_DIR="/opt/monitoring"
|
||||
CONF_DIR="${BASE_DIR}/conf"
|
||||
LOG_DIR="/var/log/monitoring"
|
||||
STATE_DIR="/var/lib/monitoring"
|
||||
LOCK_DIR="/var/lock/monitoring"
|
||||
TMP_DIR="/tmp/monitoring-install"
|
||||
# Journal des fichiers installés pour déinstallation/état des lieux
|
||||
INSTALLED_LOG="${STATE_DIR}/installed-files.log"
|
||||
|
||||
UPDATE_BASE_URL="https://git.abonnel.fr/cedricAbonnel/scripts-bash/raw/branch/main/servers/linux/monitoring"
|
||||
MANIFEST_URL="${UPDATE_BASE_URL}/manifest.txt"
|
||||
|
||||
INSTALL_DEPS="${INSTALL_DEPS:-true}"
|
||||
|
||||
# --- Fonctions d'affichage ---
|
||||
info() { echo -e "\e[34m[INFO]\e[0m $1"; }
|
||||
ok() { echo -e "\e[32m[OK]\e[0m $1"; }
|
||||
warn() { echo -e "\e[33m[WARN]\e[0m $1"; }
|
||||
err() { echo -e "\e[31m[ERR]\e[0m $1"; }
|
||||
|
||||
# --- Fonctions Techniques ---
|
||||
|
||||
require_root() {
|
||||
if [ "${EUID}" -ne 0 ]; then
|
||||
err "Ce script doit être exécuté en root."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
install_deps() {
|
||||
if [ "${INSTALL_DEPS}" != "true" ]; then return 0; fi
|
||||
info "Vérification des dépendances système..."
|
||||
if command -v apt-get >/dev/null 2>&1; then
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq curl coreutils findutils grep sed gawk util-linux ca-certificates php-cli php-curl php-common smartmontools > /dev/null
|
||||
ok "Dépendances installées."
|
||||
fi
|
||||
}
|
||||
|
||||
prepare_dirs() {
|
||||
info "Préparation de l'arborescence dans ${BASE_DIR}..."
|
||||
mkdir -p "${BASE_DIR}/bin" "${BASE_DIR}/lib" "${CONF_DIR}" "${LOG_DIR}" "${STATE_DIR}" "${LOCK_DIR}" "${TMP_DIR}"
|
||||
touch "$INSTALLED_LOG"
|
||||
}
|
||||
|
||||
fetch_manifest() {
|
||||
info "Téléchargement du manifeste distant..."
|
||||
curl -fsS "${MANIFEST_URL}" -o "${TMP_DIR}/manifest.txt"
|
||||
}
|
||||
|
||||
validate_manifest() {
|
||||
awk '
|
||||
NF == 3 &&
|
||||
$1 ~ /^[0-9a-fA-F]{64}$/ &&
|
||||
$2 ~ /^(644|755|600)$/ &&
|
||||
$3 ~ /^(bin|lib|conf)\/[A-Za-z0-9._\/-]+$/ &&
|
||||
$3 !~ /\.\./
|
||||
' "${TMP_DIR}/manifest.txt"
|
||||
}
|
||||
|
||||
download_and_install() {
|
||||
local expected_hash=$1 mode=$2 rel_path=$3
|
||||
local dst="${BASE_DIR}/${rel_path}"
|
||||
|
||||
if [ -f "$dst" ]; then
|
||||
local current_hash
|
||||
current_hash=$(sha256sum "$dst" | awk '{print $1}')
|
||||
[ "$current_hash" == "$expected_hash" ] && return 0
|
||||
info "Mise à jour : $rel_path"
|
||||
else
|
||||
info "Installation : $rel_path"
|
||||
fi
|
||||
|
||||
local tmp_file
|
||||
tmp_file="$(mktemp "${TMP_DIR}/file.XXXXXX")"
|
||||
|
||||
if ! curl -fsS "${UPDATE_BASE_URL}/${rel_path}" -o "$tmp_file"; then
|
||||
err "Échec du téléchargement pour $rel_path"
|
||||
rm -f "$tmp_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local got_hash
|
||||
got_hash=$(sha256sum "$tmp_file" | awk '{print $1}')
|
||||
if [ "$got_hash" != "$expected_hash" ]; then
|
||||
err "Hash invalide pour $rel_path"
|
||||
rm -f "$tmp_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
mkdir -p "$(dirname "$dst")"
|
||||
mv -f "$tmp_file" "$dst"
|
||||
chmod "$mode" "$dst"
|
||||
}
|
||||
|
||||
# --- NOUVEAUTÉ : Gestion du journal et purge propre ---
|
||||
|
||||
update_installed_log() {
|
||||
# On sauvegarde la liste des chemins relatifs du manifeste validé dans le journal permanent
|
||||
awk '{print $3}' "${TMP_DIR}/manifest-valid.txt" > "$INSTALLED_LOG"
|
||||
ok "Journal des fichiers déployés mis à jour ($INSTALLED_LOG)."
|
||||
}
|
||||
|
||||
purge_obsolete_files() {
|
||||
info "Analyse des fichiers obsolètes (Synchronisation avec le journal)..."
|
||||
|
||||
# On compare ce qui était installé (journal) avec ce qui est dans le nouveau manifeste
|
||||
if [ ! -s "$INSTALLED_LOG" ]; then
|
||||
warn "Journal vide, passage en mode scan classique."
|
||||
# Fallback sur le scan de dossier si le journal n'existe pas encore
|
||||
find "${BASE_DIR}/bin" "${BASE_DIR}/lib" "${BASE_DIR}/conf" -type f 2>/dev/null | while read -r local_file; do
|
||||
local rel_path="${local_file#$BASE_DIR/}"
|
||||
[[ "$rel_path" == *".local."* ]] && continue
|
||||
if ! grep -qw "$rel_path" "${TMP_DIR}/manifest-valid.txt"; then
|
||||
warn "Suppression : $rel_path"
|
||||
rm -f "$local_file"
|
||||
fi
|
||||
done
|
||||
return
|
||||
fi
|
||||
|
||||
# Mode Journal : On lit l'ancien journal pour voir ce qui doit disparaître
|
||||
while read -r old_file; do
|
||||
# Si le fichier du journal n'est plus dans le nouveau manifeste
|
||||
if ! grep -qw "$old_file" "${TMP_DIR}/manifest-valid.txt"; then
|
||||
if [ -f "${BASE_DIR}/$old_file" ]; then
|
||||
# Protection ultime des fichiers .local (au cas où ils auraient été loggués par erreur)
|
||||
if [[ "$old_file" != *".local."* ]]; then
|
||||
warn "Suppression du fichier obsolète : $old_file"
|
||||
rm -f "${BASE_DIR}/$old_file"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done < "$INSTALLED_LOG"
|
||||
}
|
||||
|
||||
# --- Main ---
|
||||
|
||||
main() {
|
||||
require_root
|
||||
install_deps
|
||||
prepare_dirs
|
||||
fetch_manifest
|
||||
|
||||
if ! validate_manifest > "${TMP_DIR}/manifest-valid.txt"; then
|
||||
err "Le manifeste est invalide ou corrompu."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "--------------------------------------------------"
|
||||
info "Phase 1 : Installation et mises à jour"
|
||||
while read -r hash mode rel_path; do
|
||||
[ -n "${hash:-}" ] || continue
|
||||
download_and_install "$hash" "$mode" "$rel_path"
|
||||
done < "${TMP_DIR}/manifest-valid.txt"
|
||||
|
||||
echo "--------------------------------------------------"
|
||||
info "Phase 2 : Nettoyage et Journalisation"
|
||||
purge_obsolete_files
|
||||
update_installed_log
|
||||
|
||||
rm -rf "${TMP_DIR}"
|
||||
echo "--------------------------------------------------"
|
||||
ok "Opération terminée avec succès."
|
||||
|
||||
# --- Vérification de la configuration ---
|
||||
local_conf="${CONF_DIR}/monitoring.local.conf.php"
|
||||
orig_conf="${CONF_DIR}/monitoring.conf.php"
|
||||
|
||||
if [ -f "$local_conf" ] && [ -f "$orig_conf" ]; then
|
||||
if [ "$(sha256sum "$local_conf" | awk '{print $1}')" == "$(sha256sum "$orig_conf" | awk '{print $1}')" ]; then
|
||||
echo -e "\n\e[33m[ATTENTION]\e[0m Votre fichier de configuration est identique à l'original."
|
||||
warn "Pensez à éditer ${local_conf}."
|
||||
else
|
||||
ok "Configuration locale personnalisée détectée."
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
main "$@"
|
||||
23
servers/linux/monitoring/bin/log-cli.php
Executable file
23
servers/linux/monitoring/bin/log-cli.php
Executable file
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* Pont de logging pour scripts Bash
|
||||
*/
|
||||
require_once __DIR__ . '/../lib/monitoring-lib.php';
|
||||
|
||||
if ($argc < 4) {
|
||||
fwrite(STDERR, "Usage: log-cli.php <LEVEL> <EVENT> <MESSAGE> [CONTEXT...]\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$level = strtoupper($argv[1]);
|
||||
$event = $argv[2];
|
||||
$message = $argv[3];
|
||||
$context = [];
|
||||
|
||||
// On récupère les arguments restants comme contexte
|
||||
for ($i = 4; $i < $argc; $i++) {
|
||||
$context[] = $argv[$i];
|
||||
}
|
||||
|
||||
log_event($level, $event, $message, $context);
|
||||
104
servers/linux/monitoring/bin/monitoring-update-config.php
Executable file
104
servers/linux/monitoring/bin/monitoring-update-config.php
Executable file
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* Audit de dérive des configurations PHP
|
||||
* Copyright (C) 2026 Cédric Abonnel
|
||||
* License: GNU Affero General Public License v3
|
||||
*/
|
||||
|
||||
// --- Initialisation & Sécurité ---
|
||||
|
||||
if (posix_getuid() !== 0) {
|
||||
fwrite(STDERR, "Ce script doit être exécuté en root.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
const CONF_DIR = '/opt/monitoring/conf';
|
||||
|
||||
/**
|
||||
* Extrait les clés d'un fichier de configuration PHP (tableau return [])
|
||||
* sans exécuter le fichier pour éviter les effets de bord, via Regex.
|
||||
*/
|
||||
function extract_keys($file) {
|
||||
$content = file_get_contents($file);
|
||||
// On cherche les patterns : 'KEY' => ou "KEY" =>
|
||||
preg_match_all('/[\'"]([A-Z0-9_]+)[\'"]\s*=>/i', $content, $matches);
|
||||
$keys = $matches[1] ?? [];
|
||||
sort($keys);
|
||||
return array_unique($keys);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logique de logging
|
||||
*/
|
||||
function log_audit($level, $event, $msg) {
|
||||
echo sprintf("[%s] %s: %s\n", strtoupper($level), $event, $msg);
|
||||
}
|
||||
|
||||
function check_config_drift() {
|
||||
$found_issue = false;
|
||||
$reviewed_files = 0;
|
||||
$files_requiring_action = 0;
|
||||
|
||||
log_audit('info', 'audit_start', "Début de l'audit des configurations PHP");
|
||||
|
||||
// On cherche les fichiers .php qui ne sont pas des .local.php
|
||||
$base_files = glob(CONF_DIR . '/*.php');
|
||||
$base_files = array_filter($base_files, function($f) {
|
||||
return !str_ends_with($f, '.local.php');
|
||||
});
|
||||
|
||||
foreach ($base_files as $base_conf) {
|
||||
$reviewed_files++;
|
||||
$base_name = basename($base_conf);
|
||||
$local_conf = str_replace('.php', '.local.php', $base_conf);
|
||||
$local_name = basename($local_conf);
|
||||
|
||||
// 1. Si le fichier local n'existe pas
|
||||
if (!file_exists($local_conf)) {
|
||||
if (copy($base_conf, $local_conf)) {
|
||||
chmod($local_conf, 0600);
|
||||
log_audit('notice', 'audit_missing_local', "Le fichier $local_name a été créé par copie de $base_name");
|
||||
} else {
|
||||
log_audit('error', 'audit_create_local_failed', "Impossible de créer $local_name");
|
||||
$found_issue = true;
|
||||
$files_requiring_action++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2. Comparaison des clés
|
||||
$keys_base = extract_keys($base_conf);
|
||||
$keys_local = extract_keys($local_conf);
|
||||
|
||||
$missing = array_diff($keys_base, $keys_local); // Présent dans base mais pas local
|
||||
$obsolete = array_diff($keys_local, $keys_base); // Présent dans local mais plus dans base
|
||||
|
||||
if (!empty($missing) || !empty($obsolete)) {
|
||||
$found_issue = true;
|
||||
$files_requiring_action++;
|
||||
|
||||
log_audit('warning', 'audit_file_requires_action', "Vérification requise pour $local_name");
|
||||
|
||||
if (!empty($missing)) {
|
||||
log_audit('warning', 'audit_keys_missing', "Options absentes de $local_name : " . implode(', ', $missing));
|
||||
}
|
||||
|
||||
if (!empty($obsolete)) {
|
||||
log_audit('info', 'audit_keys_obsolete', "Options obsolètes ou personnalisées dans $local_name : " . implode(', ', $obsolete));
|
||||
}
|
||||
} else {
|
||||
log_audit('info', 'audit_file_ok', "Le fichier $local_name est synchronisé avec $base_name");
|
||||
}
|
||||
}
|
||||
|
||||
// Résumé final
|
||||
if (!$found_issue) {
|
||||
log_audit('info', 'audit_success', "Toutes les configurations sont à jour ($reviewed_files fichiers vérifiés)");
|
||||
} else {
|
||||
log_audit('warning', 'audit_requires_action', "Action requise sur $files_requiring_action fichier(s) sur $reviewed_files");
|
||||
}
|
||||
}
|
||||
|
||||
// --- Main ---
|
||||
check_config_drift();
|
||||
179
servers/linux/monitoring/bin/monitoring-update.php
Executable file
179
servers/linux/monitoring/bin/monitoring-update.php
Executable file
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* Moteur de mise à jour
|
||||
* Pilotage du script Bash + Initialisation des Configs + Cron + Ménage
|
||||
* Copyright (C) 2026 Cédric Abonnel
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../lib/monitoring-lib.php';
|
||||
|
||||
// Sécurité : Un seul update à la fois
|
||||
lock_or_exit("monitoring-update");
|
||||
|
||||
echo "\e[1m--- Début de la mise à jour système ---\e[0m\n";
|
||||
|
||||
// 1. Avant l'update, on mémorise la liste des fichiers actuellement installés (L'AVANT)
|
||||
$installed_log = $CONFIG['INSTALLED_LOG'] ?? '/var/lib/monitoring/installed-files.log';
|
||||
$old_installed_files = [];
|
||||
if (file_exists($installed_log)) {
|
||||
$old_installed_files = file($installed_log, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
}
|
||||
|
||||
// 2. Exécution du moteur de synchronisation Bash
|
||||
$install_script = __DIR__ . '/install-monitoring.sh';
|
||||
|
||||
if (!file_exists($install_script)) {
|
||||
log_error("update_script_missing", "Script d'installation introuvable", ["path" => $install_script]);
|
||||
echo "\e[31m[ERR]\e[0m Script d'installation introuvable : $install_script\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Exécution du moteur de synchronisation Bash
|
||||
$command = "bash " . escapeshellarg($install_script) . " --auto 2>&1";
|
||||
$handle = popen($command, 'r');
|
||||
|
||||
if ($handle) {
|
||||
while (!feof($handle)) {
|
||||
$line = fgets($handle);
|
||||
if ($line) echo $line;
|
||||
}
|
||||
$exit_code = pclose($handle);
|
||||
} else {
|
||||
$exit_code = 1;
|
||||
}
|
||||
|
||||
if ($exit_code !== 0) {
|
||||
log_error("update_failed", "Le script Bash a échoué");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// 3. Après l'update, on récupère la nouvelle liste (L'APRÈS)
|
||||
$new_installed_files = [];
|
||||
if (file_exists($installed_log)) {
|
||||
$new_installed_files = file($installed_log, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
}
|
||||
|
||||
// Détermination des fichiers qui ont été SUPPRIMÉS lors de cette mise à jour (dynamique)
|
||||
$deleted_files = array_diff($old_installed_files, $new_installed_files);
|
||||
|
||||
echo "\e[1m--- Finalisation des configurations ---\e[0m\n";
|
||||
ensure_local_configs();
|
||||
ensure_crontab_entries($deleted_files);
|
||||
|
||||
echo "\e[32m[OK]\e[0m Système à jour.\n";
|
||||
|
||||
/**
|
||||
* Nettoyage et Mise à jour du Crontab
|
||||
* @param array $deleted_files Liste des chemins de fichiers supprimés du déploiement
|
||||
*/
|
||||
function ensure_crontab_entries($deleted_files) {
|
||||
global $CONFIG, $MONITORING_BASE_DIR;
|
||||
|
||||
// --- CONFIGURATION DU MÉNAGE STATIQUE ---
|
||||
// On ajoute ici les vieux chemins orphelins à éjecter impérativement
|
||||
$static_cleanup_patterns = [
|
||||
'/usr/local/bin/sys_check.sh',
|
||||
'bin/check_disk.php', // Ancienne erreur de nommage
|
||||
'bin/check-disk.sh' // Ancienne erreur de séparateur
|
||||
];
|
||||
|
||||
// Préparation des jobs requis
|
||||
$required_jobs = array_map(function($job) use ($MONITORING_BASE_DIR) {
|
||||
return str_replace('{BASE_DIR}', $MONITORING_BASE_DIR, $job);
|
||||
}, $CONFIG['CRON_JOBS'] ?? [
|
||||
"*/5 * * * * bash {$MONITORING_BASE_DIR}/bin/check_disk.sh > /dev/null 2>&1",
|
||||
"*/15 * * * * bash {$MONITORING_BASE_DIR}/bin/check_smart.sh > /dev/null 2>&1",
|
||||
"10 3 * * * php {$MONITORING_BASE_DIR}/bin/monitoring-update.php > /dev/null 2>&1",
|
||||
"* * * * * php {$MONITORING_BASE_DIR}/bin/alert-engine.php > /dev/null 2>&1"
|
||||
]);
|
||||
|
||||
$current_cron = shell_exec("crontab -l 2>/dev/null") ?: "";
|
||||
$lines = explode("\n", trim($current_cron));
|
||||
$new_lines = [];
|
||||
$has_changed = false;
|
||||
|
||||
// --- PHASE A : Nettoyage (Dynamique + Statique) ---
|
||||
foreach ($lines as $line) {
|
||||
$trim_line = trim($line);
|
||||
if (empty($trim_line)) continue;
|
||||
|
||||
$keep = true;
|
||||
|
||||
// 1. Nettoyage Dynamique (basé sur le log Git)
|
||||
foreach ($deleted_files as $deleted_path) {
|
||||
if (strpos($trim_line, $deleted_path) !== false) {
|
||||
echo "\e[33m[CLEAN]\e[0m Script supprimé du déploiement : " . basename($deleted_path) . "\n";
|
||||
$keep = false;
|
||||
$has_changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Nettoyage Statique (basé sur ta liste forcée)
|
||||
if ($keep) {
|
||||
foreach ($static_cleanup_patterns as $pattern) {
|
||||
if (strpos($trim_line, $pattern) !== false) {
|
||||
echo "\e[33m[CLEAN]\e[0m Suppression du résidu historique : $pattern\n";
|
||||
$keep = false;
|
||||
$has_changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($keep) $new_lines[] = $trim_line;
|
||||
}
|
||||
|
||||
// --- PHASE B : Ajout des nouveaux jobs ---
|
||||
foreach ($required_jobs as $job) {
|
||||
// Extraction du chemin du script pour éviter les doublons
|
||||
preg_match('/\/bin\/([a-z0-9_-]+\.(php|sh))/i', $job, $matches);
|
||||
$script_path = $matches[0] ?? "";
|
||||
|
||||
$found = false;
|
||||
foreach ($new_lines as $line) {
|
||||
if (strpos($line, $script_path) !== false) {
|
||||
$found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$found && !empty($script_path)) {
|
||||
$new_lines[] = $job;
|
||||
$has_changed = true;
|
||||
echo "\e[32m[OK]\e[0m Ajout au cron : " . basename($script_path) . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
// --- PHASE C : Application ---
|
||||
if ($has_changed) {
|
||||
$content = implode("\n", array_filter($new_lines, 'trim')) . "\n";
|
||||
$tmp_cron = tempnam(sys_get_temp_dir(), 'cron');
|
||||
file_put_contents($tmp_cron, $content);
|
||||
exec("crontab " . escapeshellarg($tmp_cron));
|
||||
unlink($tmp_cron);
|
||||
echo "\e[32m[OK]\e[0m Crontab synchronisé.\n";
|
||||
} else {
|
||||
echo "[INFO] Crontab déjà à jour.\n";
|
||||
}
|
||||
}
|
||||
|
||||
function ensure_local_configs() {
|
||||
global $MONITORING_CONF_DIR;
|
||||
$configs = [
|
||||
'monitoring.conf.php' => 'monitoring.local.conf.php',
|
||||
'alert-engine.conf.php' => 'alert-engine.conf.local.php',
|
||||
'autoupdate.conf.php' => 'autoupdate.local.conf.php'
|
||||
];
|
||||
foreach ($configs as $src => $dst) {
|
||||
$dst_path = $MONITORING_CONF_DIR . '/' . $dst;
|
||||
if (!file_exists($dst_path)) {
|
||||
$src_path = $MONITORING_CONF_DIR . '/' . $src;
|
||||
if (file_exists($src_path)) {
|
||||
copy($src_path, $dst_path);
|
||||
chmod($dst_path, 0600);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
168
servers/linux/monitoring/bin/monitoring.php
Executable file
168
servers/linux/monitoring/bin/monitoring.php
Executable file
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* Monitoring Update Engine - PHP Version
|
||||
* Copyright (C) 2026 Cédric Abonnel
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../lib/monitoring-lib.php';
|
||||
|
||||
// --- Configuration ---
|
||||
// Note : La lib a déjà chargé $CONFIG['UPDATE_BASE_URL'] etc. depuis monitoring.local.conf.php
|
||||
// On ne charge les fichiers spécifiques que s'ils apportent des règles de mise à jour uniques.
|
||||
foreach (["/opt/monitoring/conf/autoupdate.conf.php", "/opt/monitoring/conf/autoupdate.local.conf.php"] as $conf) {
|
||||
if (file_exists($conf)) {
|
||||
$extra_conf = include $conf;
|
||||
if (is_array($extra_conf)) {
|
||||
$CONFIG = array_replace_recursive($CONFIG, $extra_conf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Variables par défaut (fallback si absent de la config globale)
|
||||
$UPDATE_ENABLED = $CONFIG['UPDATE_ENABLED'] ?? true;
|
||||
$UPDATE_TMP_DIR = $CONFIG['UPDATE_TMP_DIR'] ?? '/tmp/monitoring-update';
|
||||
$UPDATE_TIMEOUT_TOTAL = $CONFIG['UPDATE_TIMEOUT_TOTAL'] ?? 15;
|
||||
$UPDATE_MANIFEST_URL = $CONFIG['UPDATE_MANIFEST_URL'] ?? '';
|
||||
$UPDATE_BASE_URL = $CONFIG['UPDATE_BASE_URL'] ?? '';
|
||||
$UPDATE_ALLOW_DELETE = $CONFIG['UPDATE_ALLOW_DELETE'] ?? false;
|
||||
$MONITORING_BASE_DIR = $MONITORING_BASE_DIR; // Provient de la lib
|
||||
|
||||
// --- Initialisation ---
|
||||
lock_or_exit("monitoring-update");
|
||||
|
||||
if (!$UPDATE_ENABLED) {
|
||||
log_notice("update_disabled", "Mise à jour désactivée");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if (!is_dir($UPDATE_TMP_DIR)) {
|
||||
mkdir($UPDATE_TMP_DIR, 0755, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Télécharge et valide le manifeste
|
||||
*/
|
||||
function fetch_manifest($url) {
|
||||
global $UPDATE_TIMEOUT_TOTAL;
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => $UPDATE_TIMEOUT_TOTAL,
|
||||
CURLOPT_FAILONERROR => true,
|
||||
CURLOPT_FOLLOWLOCATION => true
|
||||
]);
|
||||
|
||||
$content = curl_exec($ch);
|
||||
if (curl_errno($ch)) {
|
||||
log_error("manifest_download_failed", "Échec téléchargement manifeste", ["url" => $url, "err" => curl_error($ch)]);
|
||||
return false;
|
||||
}
|
||||
curl_close($ch);
|
||||
|
||||
$manifest_entries = [];
|
||||
$lines = explode("\n", trim($content));
|
||||
|
||||
foreach ($lines as $line) {
|
||||
if (preg_match('/^([0-9a-fA-F]{64})\s+(644|755)\s+((bin|lib|conf)\/[A-Za-z0-9._\/-]+)$/', trim($line), $matches)) {
|
||||
$manifest_entries[] = ['hash' => $matches[1], 'mode' => $matches[2], 'path' => $matches[3]];
|
||||
}
|
||||
}
|
||||
return $manifest_entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour un fichier
|
||||
*/
|
||||
function update_one_file($entry) {
|
||||
global $MONITORING_BASE_DIR, $UPDATE_BASE_URL, $UPDATE_TMP_DIR, $UPDATE_TIMEOUT_TOTAL;
|
||||
|
||||
$rel_path = $entry['path'];
|
||||
$target_file = $MONITORING_BASE_DIR . '/' . $rel_path;
|
||||
$remote_url = rtrim($UPDATE_BASE_URL, '/') . '/' . $rel_path;
|
||||
$expected_hash = strtolower($entry['hash']);
|
||||
|
||||
if (file_exists($target_file) && hash_file('sha256', $target_file) === $expected_hash) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$tmp_file = $UPDATE_TMP_DIR . '/' . basename($rel_path) . '.' . uniqid();
|
||||
$ch = curl_init($remote_url);
|
||||
$fp = fopen($tmp_file, 'wb');
|
||||
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_FILE => $fp,
|
||||
CURLOPT_TIMEOUT => $UPDATE_TIMEOUT_TOTAL,
|
||||
CURLOPT_FAILONERROR => true,
|
||||
CURLOPT_FOLLOWLOCATION => true
|
||||
]);
|
||||
|
||||
$success = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
fclose($fp);
|
||||
|
||||
if (!$success || hash_file('sha256', $tmp_file) !== $expected_hash) {
|
||||
log_error("update_failed", "Fichier invalide ou corrompu", ["file" => $rel_path]);
|
||||
@unlink($tmp_file);
|
||||
return false;
|
||||
}
|
||||
|
||||
ensure_parent_dir($target_file);
|
||||
chmod($tmp_file, octdec($entry['mode']));
|
||||
safe_mv($tmp_file, $target_file); // Utilise la fonction safe_mv de ta lib
|
||||
|
||||
log_notice("file_updated", "Mise à jour appliquée", ["file" => $rel_path]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoyage
|
||||
*/
|
||||
function delete_extra_files($remote_files) {
|
||||
global $UPDATE_ALLOW_DELETE, $MONITORING_BASE_DIR, $SCRIPT_PATH;
|
||||
if (!$UPDATE_ALLOW_DELETE) return;
|
||||
|
||||
foreach (['bin', 'lib', 'conf'] as $dir) {
|
||||
$full_path = $MONITORING_BASE_DIR . '/' . $dir;
|
||||
if (!is_dir($full_path)) continue;
|
||||
|
||||
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($full_path, RecursiveDirectoryIterator::SKIP_DOTS));
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
$path = $file->getPathname();
|
||||
$rel_path = substr($path, strlen($MONITORING_BASE_DIR) + 1);
|
||||
|
||||
// PROTECTIONS
|
||||
if (in_array($rel_path, $remote_files)) continue;
|
||||
if (str_contains($rel_path, '.local.')) continue; // Protection fichiers locaux
|
||||
if ($path === $SCRIPT_PATH) continue; // Ne pas se suicider
|
||||
|
||||
if (@unlink($path)) {
|
||||
log_notice("file_deleted", "Fichier obsolète supprimé", ["file" => $rel_path]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Main ---
|
||||
$manifest = fetch_manifest($UPDATE_MANIFEST_URL);
|
||||
if (!$manifest) exit(2);
|
||||
|
||||
$remote_paths = [];
|
||||
$updated = 0; $failed = 0;
|
||||
|
||||
foreach ($manifest as $entry) {
|
||||
$remote_paths[] = $entry['path'];
|
||||
update_one_file($entry) ? $updated++ : $failed++;
|
||||
}
|
||||
|
||||
delete_extra_files($remote_paths);
|
||||
|
||||
if ($failed > 0) {
|
||||
log_warning("update_partial", "Mise à jour terminée avec erreurs", ["failed" => $failed]);
|
||||
} else {
|
||||
log_info("update_ok", "Mise à jour terminée avec succès");
|
||||
}
|
||||
|
||||
exit_with_status();
|
||||
74
servers/linux/monitoring/conf/alert-engine.conf.php
Normal file
74
servers/linux/monitoring/conf/alert-engine.conf.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
/**
|
||||
* Configuration Alert Engine
|
||||
* Copyright (C) 2026 Cédric Abonnel
|
||||
* License: GNU Affero General Public License v3
|
||||
* NE PAS ÉDITER - Utilisez alert-engine.local.conf.php pour vos surcharges
|
||||
* RISQUE D'ECRASEMENT - RISQUE D'EFFACEMENT
|
||||
*/
|
||||
|
||||
// On définit les variables de base (équivalent de l'environnement)
|
||||
$monitoring_state_dir = getenv('MONITORING_STATE_DIR') ?: '/var/lib/monitoring';
|
||||
|
||||
return [
|
||||
// --- Fichiers d'état ---
|
||||
'ALERT_STATE_FILE' => $monitoring_state_dir . '/alert-engine.offset',
|
||||
'ALERT_DEDUP_FILE' => $monitoring_state_dir . '/alert-engine.dedup',
|
||||
|
||||
// --- Activation des canaux ---
|
||||
'ALERT_NTFY_ENABLED' => true,
|
||||
'ALERT_MAIL_ENABLED' => true,
|
||||
|
||||
// --- Configuration Mail ---
|
||||
'ALERT_MAIL_BIN' => '/usr/sbin/sendmail',
|
||||
'ALERT_MAIL_SUBJECT_PREFIX' => '[monitoring]',
|
||||
'DEST' => 'admin@example.com', // N'oubliez pas de définir le destinataire
|
||||
|
||||
// --- Déduplication ---
|
||||
'ALERT_DEDUP_WINDOW' => 3600, // en secondes
|
||||
|
||||
// --- Événements à ignorer ---
|
||||
'ALERT_IGNORE_EVENTS' => [
|
||||
'update_not_needed',
|
||||
'alert_sent_ntfy',
|
||||
'alert_sent_mail'
|
||||
],
|
||||
|
||||
// --- Canaux par défaut selon le niveau ---
|
||||
'DEFAULT_CHANNELS' => [
|
||||
'INFO' => 'ntfy',
|
||||
'NOTICE' => 'ntfy',
|
||||
'WARNING' => 'ntfy',
|
||||
'ERROR' => 'ntfy,mail',
|
||||
'CRITICAL' => 'ntfy,mail',
|
||||
],
|
||||
|
||||
// --- Tags : Une icône pour chaque état possible ---
|
||||
'NTFY_TAGS' => [
|
||||
'DEBUG' => 'gear', // ⚙️
|
||||
'INFO' => 'information_source', // ℹ️
|
||||
'NOTICE' => 'bell', // 🔔
|
||||
'SUCCESS' => 'white_check_mark', // ✅
|
||||
'WARNING' => 'warning', // ⚠️
|
||||
'ERROR' => 'rotating_light,warning', // 🚨
|
||||
'CRITICAL' => 'skull,warning', // 💀
|
||||
'ALERT' => 'ambulance,rotating_light',// 🚑
|
||||
'EMERGENCY' => 'fire,sos,skull', // 🔥
|
||||
'AUDIT' => 'mag', // 🔍
|
||||
],
|
||||
|
||||
// --- Règles spécifiques par événement ---
|
||||
// Si un événement est listé ici, il outrepasse les DEFAULT_CHANNELS
|
||||
'RULES' => [
|
||||
'disk_usage_high' => 'ntfy',
|
||||
'disk_usage_critical' => 'ntfy,mail',
|
||||
'check_failed' => 'ntfy,mail',
|
||||
'internal_error' => 'ntfy,mail',
|
||||
'update_hash_unavailable' => 'ntfy',
|
||||
'update_download_failed' => 'ntfy,mail',
|
||||
'update_hash_mismatch' => 'ntfy,mail',
|
||||
'manifest_download_failed' => 'ntfy,mail',
|
||||
'manifest_invalid' => 'ntfy,mail',
|
||||
'update_finished_with_errors' => 'ntfy,mail',
|
||||
],
|
||||
];
|
||||
63
servers/linux/monitoring/conf/monitoring.conf.php
Normal file
63
servers/linux/monitoring/conf/monitoring.conf.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
/**
|
||||
* Configuration globale par défaut
|
||||
* Copyright (C) 2026 Cédric Abonnel
|
||||
* License: GNU Affero General Public License v3
|
||||
* NE PAS ÉDITER - Utilisez monitoring.local.conf.php pour vos surcharges
|
||||
* RISQUE D'ECRASEMENT - RISQUE D'EFFACEMENT
|
||||
*/
|
||||
|
||||
// Détection dynamique du hostname (équivalent de $(hostname -f))
|
||||
$hostname_fqdn = getenv('HOSTNAME_FQDN') ?: (gethostname() ?: 'localhost');
|
||||
|
||||
// On définit les répertoires de base
|
||||
$monitoring_base = '/opt/monitoring';
|
||||
$monitoring_log_dir = '/var/log/monitoring';
|
||||
$monitoring_state_dir = '/var/lib/monitoring';
|
||||
$monitoring_lock_dir = '/var/lock/monitoring';
|
||||
|
||||
// Initialisation automatique des répertoires (équivalent du mkdir -p à la fin du bash)
|
||||
foreach ([$monitoring_log_dir, $monitoring_state_dir, $monitoring_lock_dir] as $dir) {
|
||||
if (!is_dir($dir)) {
|
||||
@mkdir($dir, 0755, true);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
// --- Chemins ---
|
||||
'MONITORING_BASE' => $monitoring_base,
|
||||
'MONITORING_LOG_DIR' => $monitoring_log_dir,
|
||||
'MONITORING_STATE_DIR' => $monitoring_state_dir,
|
||||
'MONITORING_LOCK_DIR' => $monitoring_lock_dir,
|
||||
'LOG_FILE' => $monitoring_log_dir . '/events.jsonl',
|
||||
|
||||
// --- Identification ---
|
||||
'HOSTNAME_FQDN' => $hostname_fqdn,
|
||||
'DEST' => 'root',
|
||||
|
||||
// --- ntfy ---
|
||||
'NTFY_SERVER' => 'https://ntfy.sh', // Correction du nfy.sh en ntfy.sh
|
||||
'NTFY_TOPIC' => 'TPOSOB84sBJ6HTZ7',
|
||||
'NTFY_TOKEN' => '',
|
||||
|
||||
// --- Mises à jour (Update) ---
|
||||
'UPDATE_ENABLED' => true,
|
||||
'UPDATE_BASE_URL' => 'https://git.abonnel.fr/cedricAbonnel/scripts-bash/raw/branch/main/servers/linux/monitoring',
|
||||
'UPDATE_MANIFEST_URL' => 'https://git.abonnel.fr/cedricAbonnel/scripts-bash/raw/branch/main/servers/linux/monitoring/manifest.txt',
|
||||
'UPDATE_TIMEOUT_CONNECT' => 3,
|
||||
'UPDATE_TIMEOUT_TOTAL' => 15,
|
||||
'UPDATE_TMP_DIR' => '/tmp/monitoring-update',
|
||||
'UPDATE_ALLOW_DELETE' => false,
|
||||
|
||||
// --- Logs ---
|
||||
'LOG_LEVEL' => 'INFO', // DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL
|
||||
|
||||
'STATE_DIR' => '/var/lib/monitoring',
|
||||
'INSTALLED_LOG' => '/var/lib/monitoring/installed-files.log',
|
||||
'CRON_JOBS' => [
|
||||
"*/5 * * * * bash {BASE_DIR}/bin/check_disk.sh > /dev/null 2>&1",
|
||||
"*/15 * * * * bash {BASE_DIR}/bin/check_smart.sh > /dev/null 2>&1",
|
||||
"10 3 * * * php {BASE_DIR}/bin/monitoring-update.php > /dev/null 2>&1",
|
||||
"* * * * * php {BASE_DIR}/bin/alert-engine.php > /dev/null 2>&1"
|
||||
],
|
||||
];
|
||||
166
servers/linux/monitoring/lib/monitoring-lib.php
Normal file
166
servers/linux/monitoring/lib/monitoring-lib.php
Normal file
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
/**
|
||||
* Monitoring Library - PHP Version
|
||||
* Copyright (C) 2026 Cédric Abonnel
|
||||
* License: GNU Affero General Public License v3
|
||||
*/
|
||||
|
||||
// --- Chemins et Constantes ---
|
||||
$MONITORING_LIB_DIR = __DIR__;
|
||||
$MONITORING_BASE_DIR = dirname($MONITORING_LIB_DIR);
|
||||
$MONITORING_CONF_DIR = $MONITORING_BASE_DIR . '/conf';
|
||||
|
||||
// États globaux
|
||||
$STATUS_OK = 0;
|
||||
$STATUS_WARNING = 1;
|
||||
$STATUS_ERROR = 2;
|
||||
$STATUS_INTERNAL = 3;
|
||||
|
||||
$CURRENT_STATUS = $STATUS_OK;
|
||||
|
||||
// --- Chargement de la Config ---
|
||||
$CONFIG = [
|
||||
'LOG_FILE' => '/var/log/monitoring/events.jsonl',
|
||||
'MONITORING_LOCK_DIR' => '/var/lock/monitoring',
|
||||
'LOG_LEVEL' => 'INFO'
|
||||
];
|
||||
|
||||
// 1. On charge la configuration GLOBALE (La vérité est ici)
|
||||
$global_conf = $MONITORING_CONF_DIR . "/monitoring.local.conf.php";
|
||||
if (file_exists($global_conf)) {
|
||||
$CONFIG = array_replace_recursive($CONFIG, include $global_conf);
|
||||
}
|
||||
|
||||
// 2. On charge ensuite la config spécifique au script (si besoin de surcharger)
|
||||
// $specific_conf est défini par le script qui appelle la lib
|
||||
if (isset($specific_conf) && file_exists($specific_conf)) {
|
||||
$CONFIG = array_replace_recursive($CONFIG, include $specific_conf);
|
||||
}
|
||||
|
||||
// Variables d'exécution
|
||||
$SCRIPT_NAME = basename($_SERVER['SCRIPT_FILENAME'] ?? $argv[0]);
|
||||
$SCRIPT_PATH = realpath($_SERVER['SCRIPT_FILENAME'] ?? $argv[0]);
|
||||
|
||||
// --- Fonctions de Log ---
|
||||
|
||||
/**
|
||||
* Log un événement au format JSONL
|
||||
*/
|
||||
function log_event(string $level, string $event, string $message, array $extra_kv = []) {
|
||||
global $CONFIG, $SCRIPT_NAME;
|
||||
|
||||
$ts = date('c'); // ISO-8601
|
||||
|
||||
// Détection Hostname
|
||||
$host = getenv('HOSTNAME_FQDN') ?: (gethostname() ?: 'unknown');
|
||||
|
||||
$log_data = [
|
||||
"ts" => $ts,
|
||||
"host" => $host,
|
||||
"app" => $SCRIPT_NAME,
|
||||
"level" => $level,
|
||||
"event" => $event,
|
||||
"message" => $message
|
||||
];
|
||||
|
||||
// Fusion des paires clé=valeur supplémentaires
|
||||
foreach ($extra_kv as $kv) {
|
||||
if (strpos($kv, '=') !== false) {
|
||||
list($k, $v) = explode('=', $kv, 2);
|
||||
$log_data[$k] = $v;
|
||||
}
|
||||
}
|
||||
|
||||
$json_line = json_encode($log_data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
$log_file = $CONFIG['LOG_FILE'];
|
||||
ensure_parent_dir($log_file);
|
||||
|
||||
file_put_contents($log_file, $json_line . "\n", FILE_APPEND | LOCK_EX);
|
||||
}
|
||||
|
||||
function set_status(int $new_status) {
|
||||
global $CURRENT_STATUS;
|
||||
if ($new_status > $CURRENT_STATUS) {
|
||||
$CURRENT_STATUS = $new_status;
|
||||
}
|
||||
}
|
||||
|
||||
// Helpers de logs
|
||||
function log_debug($e, $m, $x = []) { log_event("DEBUG", $e, $m, $x); }
|
||||
function log_info($e, $m, $x = []) { log_event("INFO", $e, $m, $x); }
|
||||
function log_notice($e, $m, $x = []) { log_event("NOTICE", $e, $m, $x); }
|
||||
function log_warning($e, $m, $x = []) { log_event("WARNING", $e, $m, $x); set_status(1); }
|
||||
function log_error($e, $m, $x = []) { log_event("ERROR", $e, $m, $x); set_status(2); }
|
||||
function log_critical($e, $m, $x = []) { log_event("CRITICAL", $e, $m, $x); set_status(2); }
|
||||
|
||||
function fail_internal(string $msg) {
|
||||
log_event("ERROR", "internal_error", $msg);
|
||||
exit(3); // STATUS_INTERNAL
|
||||
}
|
||||
|
||||
function exit_with_status() {
|
||||
global $CURRENT_STATUS;
|
||||
exit($CURRENT_STATUS);
|
||||
}
|
||||
|
||||
// --- Utilitaires Système ---
|
||||
|
||||
/**
|
||||
* Vérifie la présence de commandes système
|
||||
*/
|
||||
function require_cmd(...$cmds) {
|
||||
foreach ($cmds as $cmd) {
|
||||
$output = [];
|
||||
$res = 0;
|
||||
exec("command -v " . escapeshellarg($cmd), $output, $res);
|
||||
if ($res !== 0) {
|
||||
fail_internal("Commande requise absente: $cmd");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gestion du verrouillage (Lock)
|
||||
*/
|
||||
function lock_or_exit(?string $lock_name = null) {
|
||||
global $CONFIG, $SCRIPT_NAME;
|
||||
$name = $lock_name ?: $SCRIPT_NAME;
|
||||
$lock_file = ($CONFIG['MONITORING_LOCK_DIR'] ?? '/var/lock/monitoring') . "/{$name}.lock";
|
||||
|
||||
ensure_parent_dir($lock_file);
|
||||
$fp = fopen($lock_file, "w+");
|
||||
|
||||
if (!$fp || !flock($fp, LOCK_EX | LOCK_NB)) {
|
||||
log_notice("already_running", "Une autre instance est déjà en cours", ["lock=$lock_file"]);
|
||||
exit(0);
|
||||
}
|
||||
// On garde le descripteur ouvert pour maintenir le lock
|
||||
return $fp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Évalue un niveau selon des seuils
|
||||
*/
|
||||
function threshold_level($value, $warning, $critical) {
|
||||
if ($value >= $critical) return 'CRITICAL';
|
||||
if ($value >= $warning) return 'WARNING';
|
||||
return 'INFO';
|
||||
}
|
||||
|
||||
function ensure_parent_dir(string $file) {
|
||||
$dir = dirname($file);
|
||||
if (!is_dir($dir)) {
|
||||
if (!mkdir($dir, 0755, true)) {
|
||||
// Ici on ne peut pas appeler log_event si c'est le répertoire de log qui échoue
|
||||
error_log("Impossible de créer le répertoire : $dir");
|
||||
exit(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function safe_mv(string $src, string $dst) {
|
||||
if (!rename($src, $dst)) {
|
||||
fail_internal("Échec du déplacement de $src vers $dst");
|
||||
}
|
||||
}
|
||||
11
servers/linux/monitoring/manifest.txt
Normal file
11
servers/linux/monitoring/manifest.txt
Normal file
@@ -0,0 +1,11 @@
|
||||
5b4ea784d2cbe73f6e829e35f23b0b4dbe12df55cc1abc8eba6602da36c724ef 755 bin/alert-engine.php
|
||||
fdcea6720186795538f48c08b99103b320273dbdd0ea5246a2da9d81a1eecc6c 755 bin/check_disk.sh
|
||||
ead10d3be3aac48c6406a734dee1bddf9a8abb1e21de102ce72fa92fdecbaf22 755 bin/check_smart.sh
|
||||
8f95824b568b5de7dbdc2d6ab87fc6fd8076dcb8ad20de3e72a53391e97f8484 755 bin/install-monitoring.sh
|
||||
97a91b13b0776acb3326010821ffcc163e96a97e3c326ea77f11efdb7baf159a 755 bin/log-cli.php
|
||||
02bd43ed2a9b92acc013274c716e6bc50120a8103ccf3d9c4e6f345a0b22d6a0 755 bin/monitoring.php
|
||||
97d407d75a26bd2ebbb86a2e5f8dab8b24639e8a9164f42bd554ba7728ab8cb5 755 bin/monitoring-update-config.php
|
||||
910a7c3a4423fb5456233d0c6cbcfc7f511c94947580972c42286762142e5ce6 755 bin/monitoring-update.php
|
||||
dc70c1184da4aa32eebdeaee57cfed23e91397c94a6243e0ac8664968078f0c7 644 conf/alert-engine.conf.php
|
||||
324038d28f24f3f4d1f6def73752ff703d4ce8b532a663c6628611923748b1f5 644 conf/monitoring.conf.php
|
||||
9bb7f5438edc5fb6a5b899ee21be2a5a559eb0697a028a4e991fc82362eaa460 644 lib/monitoring-lib.php
|
||||
65
servers/linux/monitoring/old-bin/alert-engine.conf
Normal file
65
servers/linux/monitoring/old-bin/alert-engine.conf
Normal file
@@ -0,0 +1,65 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2026 Cédric Abonnel
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# Fichiers d'état
|
||||
ALERT_STATE_FILE="${MONITORING_STATE_DIR}/alert-engine.offset"
|
||||
ALERT_DEDUP_FILE="${MONITORING_STATE_DIR}/alert-engine.dedup"
|
||||
|
||||
# Activation des canaux
|
||||
ALERT_NTFY_ENABLED="true"
|
||||
ALERT_MAIL_ENABLED="true"
|
||||
|
||||
# Mail
|
||||
ALERT_MAIL_BIN="/usr/sbin/sendmail"
|
||||
ALERT_MAIL_SUBJECT_PREFIX="[monitoring]"
|
||||
|
||||
# ntfy
|
||||
NTFY_SERVER="https://ntfy.sh"
|
||||
NTFY_TOPIC="TPOSOB84sBJ6HTZ7"
|
||||
NTFY_TOKEN=""
|
||||
|
||||
# Déduplication en secondes
|
||||
ALERT_DEDUP_WINDOW=3600
|
||||
|
||||
# Événements à ignorer
|
||||
ALERT_IGNORE_EVENTS="update_not_needed alert_sent_ntfy alert_sent_mail"
|
||||
|
||||
# Règles par défaut selon le niveau
|
||||
ALERT_DEFAULT_CHANNELS_WARNING="ntfy"
|
||||
ALERT_DEFAULT_CHANNELS_ERROR="ntfy,mail"
|
||||
ALERT_DEFAULT_CHANNELS_CRITICAL="ntfy,mail"
|
||||
|
||||
# Règles spécifiques par événement
|
||||
ALERT_RULE_disk_usage_high="ntfy"
|
||||
ALERT_RULE_disk_usage_critical="ntfy,mail"
|
||||
ALERT_RULE_check_failed="ntfy,mail"
|
||||
ALERT_RULE_internal_error="ntfy,mail"
|
||||
|
||||
ALERT_RULE_update_hash_unavailable="ntfy"
|
||||
ALERT_RULE_update_download_failed="ntfy,mail"
|
||||
ALERT_RULE_update_hash_mismatch="ntfy,mail"
|
||||
ALERT_RULE_manifest_download_failed="ntfy,mail"
|
||||
ALERT_RULE_manifest_invalid="ntfy,mail"
|
||||
ALERT_RULE_update_finished_with_errors="ntfy,mail"
|
||||
|
||||
# Optionnel : certains événements peuvent être forcés en ntfy uniquement
|
||||
# ALERT_RULE_disk_ok=""
|
||||
# ALERT_RULE_update_finished=""
|
||||
|
||||
# Optionnel : URL ouverte quand on clique sur la notif ntfy
|
||||
NTFY_CLICK_URL=""
|
||||
|
||||
# Optionnel : tags par niveau pour ntfy
|
||||
NTFY_TAGS_WARNING="warning"
|
||||
NTFY_TAGS_ERROR="warning,rotating_light"
|
||||
NTFY_TAGS_CRITICAL="skull,warning"
|
||||
352
servers/linux/monitoring/old-bin/alert-engine.sh
Executable file
352
servers/linux/monitoring/old-bin/alert-engine.sh
Executable file
@@ -0,0 +1,352 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2026 Cédric Abonnel
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
set -u
|
||||
|
||||
SCRIPT_NAME="$(basename "$0")"
|
||||
SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")"
|
||||
|
||||
# shellcheck source=/opt/monitoring/lib/monitoring-lib.sh
|
||||
. /opt/monitoring/lib/monitoring-lib.sh || exit 3
|
||||
|
||||
load_conf_if_exists "/opt/monitoring/conf/alert-engine.conf"
|
||||
load_conf_if_exists "/opt/monitoring/conf/alert-engine.local.conf"
|
||||
|
||||
lock_or_exit "alert-engine"
|
||||
require_cmd awk sed grep date tail stat cut tr
|
||||
|
||||
LOG_SOURCE="${LOG_FILE:-/var/log/monitoring/events.jsonl}"
|
||||
STATE_FILE="${ALERT_STATE_FILE:-/var/lib/monitoring/alert-engine.offset}"
|
||||
DEDUP_FILE="${ALERT_DEDUP_FILE:-/var/lib/monitoring/alert-engine.dedup}"
|
||||
|
||||
mkdir -p "$(dirname "$STATE_FILE")" "$(dirname "$DEDUP_FILE")" || fail_internal "Impossible de créer les répertoires d'état"
|
||||
touch "$STATE_FILE" "$DEDUP_FILE" || fail_internal "Impossible d'initialiser les fichiers d'état"
|
||||
|
||||
json_get() {
|
||||
local key="$1"
|
||||
local line="$2"
|
||||
|
||||
printf '%s\n' "$line" \
|
||||
| sed -n "s/.*\"${key}\":\"\([^\"]*\)\".*/\1/p" \
|
||||
| head -n1
|
||||
}
|
||||
|
||||
json_get_number() {
|
||||
local key="$1"
|
||||
local line="$2"
|
||||
|
||||
printf '%s\n' "$line" \
|
||||
| sed -n "s/.*\"${key}\":\([0-9][0-9]*\).*/\1/p" \
|
||||
| head -n1
|
||||
}
|
||||
|
||||
get_last_offset() {
|
||||
local offset
|
||||
offset="$(cat "$STATE_FILE" 2>/dev/null || true)"
|
||||
if [[ "$offset" =~ ^[0-9]+$ ]]; then
|
||||
printf '%s\n' "$offset"
|
||||
else
|
||||
printf '0\n'
|
||||
fi
|
||||
}
|
||||
|
||||
set_last_offset() {
|
||||
printf '%s\n' "$1" > "$STATE_FILE"
|
||||
}
|
||||
|
||||
current_log_size() {
|
||||
stat -c '%s' "$LOG_SOURCE" 2>/dev/null || printf '0\n'
|
||||
}
|
||||
|
||||
cleanup_dedup_file() {
|
||||
local now window tmp
|
||||
now="$(date +%s)"
|
||||
window="${ALERT_DEDUP_WINDOW:-3600}"
|
||||
tmp="$(mktemp "${MONITORING_STATE_DIR}/alert-engine.dedup.XXXXXX")" || return 0
|
||||
|
||||
awk -F'|' -v now="$now" -v window="$window" '
|
||||
NF >= 2 {
|
||||
if ((now - $2) <= window) print $0
|
||||
}
|
||||
' "$DEDUP_FILE" > "$tmp" 2>/dev/null || true
|
||||
|
||||
mv -f "$tmp" "$DEDUP_FILE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
dedup_key() {
|
||||
local host="$1"
|
||||
local app="$2"
|
||||
local level="$3"
|
||||
local event="$4"
|
||||
printf '%s|%s|%s|%s\n' "$host" "$app" "$level" "$event"
|
||||
}
|
||||
|
||||
should_notify_dedup() {
|
||||
local key="$1"
|
||||
local now window found_ts
|
||||
now="$(date +%s)"
|
||||
window="${ALERT_DEDUP_WINDOW:-3600}"
|
||||
|
||||
found_ts="$(awk -F'|' -v k="$key" '
|
||||
$1 "|" $3 "|" $4 "|" $5 == k {print $2}
|
||||
' "$DEDUP_FILE" | tail -n1)"
|
||||
|
||||
if [[ "$found_ts" =~ ^[0-9]+$ ]]; then
|
||||
if [ $((now - found_ts)) -lt "$window" ]; then
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
save_dedup_entry() {
|
||||
local host="$1"
|
||||
local app="$2"
|
||||
local level="$3"
|
||||
local event="$4"
|
||||
local now
|
||||
now="$(date +%s)"
|
||||
printf '%s|%s|%s|%s|%s\n' "$host" "$now" "$app" "$level" "$event" >> "$DEDUP_FILE"
|
||||
}
|
||||
|
||||
event_is_ignored() {
|
||||
local event="$1" ignored
|
||||
for ignored in ${ALERT_IGNORE_EVENTS:-}; do
|
||||
[ "$ignored" = "$event" ] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
channels_for_event() {
|
||||
local level="$1"
|
||||
local event="$2"
|
||||
local varname value
|
||||
|
||||
varname="ALERT_RULE_${event}"
|
||||
value="${!varname:-}"
|
||||
|
||||
if [ -n "$value" ]; then
|
||||
printf '%s\n' "$value"
|
||||
return 0
|
||||
fi
|
||||
|
||||
case "$level" in
|
||||
WARNING)
|
||||
printf '%s\n' "${ALERT_DEFAULT_CHANNELS_WARNING:-ntfy}"
|
||||
;;
|
||||
ERROR)
|
||||
printf '%s\n' "${ALERT_DEFAULT_CHANNELS_ERROR:-ntfy,mail}"
|
||||
;;
|
||||
CRITICAL)
|
||||
printf '%s\n' "${ALERT_DEFAULT_CHANNELS_CRITICAL:-ntfy,mail}"
|
||||
;;
|
||||
*)
|
||||
printf '\n'
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
tags_for_level() {
|
||||
case "$1" in
|
||||
WARNING) printf '%s\n' "${NTFY_TAGS_WARNING:-warning}" ;;
|
||||
ERROR) printf '%s\n' "${NTFY_TAGS_ERROR:-warning,rotating_light}" ;;
|
||||
CRITICAL) printf '%s\n' "${NTFY_TAGS_CRITICAL:-skull,warning}" ;;
|
||||
*) printf '\n' ;;
|
||||
esac
|
||||
}
|
||||
|
||||
|
||||
send_ntfy() {
|
||||
|
||||
local title="$1"
|
||||
local body="$2"
|
||||
local priority="$3"
|
||||
|
||||
[ "${ALERT_NTFY_ENABLED:-true}" = "true" ] || return 0
|
||||
[ -n "${NTFY_SERVER:-}" ] || return 1
|
||||
[ -n "${NTFY_TOPIC:-}" ] || return 1
|
||||
|
||||
local url="${NTFY_SERVER%/}/${NTFY_TOPIC}"
|
||||
|
||||
local curl_args=(
|
||||
-fsS
|
||||
-X POST
|
||||
-H "Title: ${title}"
|
||||
-H "Priority: ${priority}"
|
||||
-H "Tags: warning"
|
||||
-d "$body"
|
||||
)
|
||||
|
||||
# topic protégé
|
||||
if [ -n "${NTFY_TOKEN:-}" ]; then
|
||||
curl_args+=(-H "Authorization: Bearer ${NTFY_TOKEN}")
|
||||
fi
|
||||
|
||||
curl "${curl_args[@]}" "$url" >/dev/null
|
||||
}
|
||||
|
||||
send_mail() {
|
||||
local subject="$1"
|
||||
local body="$2"
|
||||
|
||||
[ "${ALERT_MAIL_ENABLED:-true}" = "true" ] || return 0
|
||||
[ -n "${DEST:-}" ] || return 1
|
||||
[ -x "${ALERT_MAIL_BIN:-/usr/sbin/sendmail}" ] || return 1
|
||||
|
||||
{
|
||||
printf 'To: %s\n' "${DEST}"
|
||||
printf 'Subject: %s %s\n' "${ALERT_MAIL_SUBJECT_PREFIX:-[monitoring]}" "$subject"
|
||||
printf 'Content-Type: text/plain; charset=UTF-8\n'
|
||||
printf '\n'
|
||||
printf '%s\n' "$body"
|
||||
} | "${ALERT_MAIL_BIN:-/usr/sbin/sendmail}" -t
|
||||
}
|
||||
|
||||
priority_for_level() {
|
||||
case "$1" in
|
||||
CRITICAL) printf 'urgent\n' ;;
|
||||
ERROR) printf 'high\n' ;;
|
||||
WARNING) printf 'default\n' ;;
|
||||
*) printf 'default\n' ;;
|
||||
esac
|
||||
}
|
||||
|
||||
build_title() {
|
||||
local host="$1"
|
||||
local app="$2"
|
||||
local level="$3"
|
||||
local event="$4"
|
||||
printf '%s [%s] %s %s\n' "$host" "$app" "$level" "$event"
|
||||
}
|
||||
|
||||
build_body() {
|
||||
local ts="$1"
|
||||
local host="$2"
|
||||
local app="$3"
|
||||
local level="$4"
|
||||
local event="$5"
|
||||
local message="$6"
|
||||
local line="$7"
|
||||
|
||||
cat <<EOF
|
||||
Date: $ts
|
||||
Hôte: $host
|
||||
Script: $app
|
||||
Niveau: $level
|
||||
Événement: $event
|
||||
|
||||
Message:
|
||||
$message
|
||||
|
||||
EOF
|
||||
}
|
||||
|
||||
process_line() {
|
||||
|
||||
local line="$1"
|
||||
local ts host app level event message channels title body prio ch key
|
||||
|
||||
ts="$(json_get "ts" "$line")"
|
||||
host="$(json_get "host" "$line")"
|
||||
app="$(json_get "app" "$line")"
|
||||
level="$(json_get "level" "$line")"
|
||||
event="$(json_get "event" "$line")"
|
||||
message="$(json_get "message" "$line")"
|
||||
|
||||
local tags
|
||||
tags="$(tags_for_level "$level")"
|
||||
|
||||
[ -n "$level" ] || return 0
|
||||
[ -n "$event" ] || return 0
|
||||
|
||||
case "$level" in
|
||||
DEBUG|INFO|NOTICE)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
if event_is_ignored "$event"; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
key="$(dedup_key "$host" "$app" "$level" "$event")"
|
||||
if ! should_notify_dedup "$key"; then
|
||||
log_debug "alert_suppressed_dedup" "Alerte supprimée par déduplication" \
|
||||
"event=$event" "level=$level" "host=$host" "app=$app"
|
||||
return 0
|
||||
fi
|
||||
|
||||
channels="$(channels_for_event "$level" "$event")"
|
||||
[ -n "$channels" ] || return 0
|
||||
|
||||
title="$(build_title "$host" "$app" "$level" "$event")"
|
||||
body="$(build_body "$ts" "$host" "$app" "$level" "$event" "$message" "$line")"
|
||||
prio="$(priority_for_level "$level")"
|
||||
|
||||
IFS=',' read -r -a channel_array <<< "$channels"
|
||||
for ch in "${channel_array[@]}"; do
|
||||
case "$ch" in
|
||||
ntfy)
|
||||
if send_ntfy "$title" "$body" "$prio" "$tags"; then
|
||||
log_info "alert_sent_ntfy" "Notification ntfy envoyée" \
|
||||
"event=$event" "level=$level" "host=$host" "app=$app"
|
||||
else
|
||||
log_error "alert_ntfy_failed" "Échec d'envoi ntfy" \
|
||||
"event=$event" "level=$level" "host=$host" "app=$app"
|
||||
fi
|
||||
;;
|
||||
mail)
|
||||
if send_mail "$title" "$body"; then
|
||||
log_info "alert_sent_mail" "Mail d'alerte envoyé" \
|
||||
"event=$event" "level=$level" "host=$host" "app=$app"
|
||||
else
|
||||
log_error "alert_mail_failed" "Échec d'envoi mail" \
|
||||
"event=$event" "level=$level" "host=$host" "app=$app"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
save_dedup_entry "$host" "$app" "$level" "$event"
|
||||
}
|
||||
|
||||
main() {
|
||||
local last_offset log_size
|
||||
last_offset="$(get_last_offset)"
|
||||
log_size="$(current_log_size)"
|
||||
|
||||
if [ ! -f "$LOG_SOURCE" ]; then
|
||||
log_notice "alert_log_missing" "Fichier de log absent, rien à traiter" "file=$LOG_SOURCE"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$last_offset" -gt "$log_size" ]; then
|
||||
log_notice "alert_offset_reset" "Offset réinitialisé après rotation ou troncature du log" \
|
||||
"old_offset=$last_offset" "new_offset=0"
|
||||
last_offset=0
|
||||
fi
|
||||
|
||||
cleanup_dedup_file
|
||||
|
||||
tail -c +$((last_offset + 1)) "$LOG_SOURCE" | while IFS= read -r line; do
|
||||
[ -n "$line" ] || continue
|
||||
process_line "$line"
|
||||
done
|
||||
|
||||
set_last_offset "$log_size"
|
||||
}
|
||||
|
||||
main
|
||||
exit_with_status
|
||||
147
servers/linux/monitoring/old-bin/monitoring-lib.sh
Normal file
147
servers/linux/monitoring/old-bin/monitoring-lib.sh
Normal file
@@ -0,0 +1,147 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2026 Cédric Abonnel
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
MONITORING_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
MONITORING_BASE_DIR="$(cd "${MONITORING_LIB_DIR}/.." && pwd)"
|
||||
MONITORING_CONF_DIR="${MONITORING_BASE_DIR}/conf"
|
||||
|
||||
# Chargement config globale
|
||||
if [ -f "${MONITORING_CONF_DIR}/monitoring.conf" ]; then
|
||||
# shellcheck source=/dev/null
|
||||
. "${MONITORING_CONF_DIR}/monitoring.conf"
|
||||
fi
|
||||
|
||||
SCRIPT_NAME="${SCRIPT_NAME:-$(basename "$0")}"
|
||||
SCRIPT_PATH="${SCRIPT_PATH:-$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")}"
|
||||
|
||||
STATUS_OK=0
|
||||
STATUS_WARNING=1
|
||||
STATUS_ERROR=2
|
||||
STATUS_INTERNAL=3
|
||||
|
||||
CURRENT_STATUS=$STATUS_OK
|
||||
|
||||
LOG_LEVEL=${LOG_LEVEL:-INFO}
|
||||
|
||||
json_escape() {
|
||||
local s="${1:-}"
|
||||
s="${s//\\/\\\\}"
|
||||
s="${s//\"/\\\"}"
|
||||
s="${s//$'\n'/\\n}"
|
||||
s="${s//$'\r'/\\r}"
|
||||
s="${s//$'\t'/\\t}"
|
||||
printf '%s' "$s"
|
||||
}
|
||||
|
||||
log_event() {
|
||||
local level="$1"
|
||||
local event="$2"
|
||||
local message="$3"
|
||||
shift 3
|
||||
|
||||
local ts extra key value kv host
|
||||
ts="$(date --iso-8601=seconds)"
|
||||
|
||||
# Détection dynamique du hostname si HOSTNAME_FQDN n'est pas défini
|
||||
# On utilise 'hostname -f' pour le nom complet ou 'hostname' en secours
|
||||
host="${HOSTNAME_FQDN:-$(hostname -f 2>/dev/null || hostname)}"
|
||||
|
||||
extra=""
|
||||
|
||||
for kv in "$@"; do
|
||||
key="${kv%%=*}"
|
||||
value="${kv#*=}"
|
||||
extra="${extra},\"$(json_escape "$key")\":\"$(json_escape "$value")\""
|
||||
done
|
||||
|
||||
# Utilisation de la variable 'host' détectée ci-dessus
|
||||
printf '{"ts":"%s","host":"%s","app":"%s","level":"%s","event":"%s","message":"%s"%s}\n' \
|
||||
"$(json_escape "$ts")" \
|
||||
"$(json_escape "$host")" \
|
||||
"$(json_escape "$SCRIPT_NAME")" \
|
||||
"$(json_escape "$level")" \
|
||||
"$(json_escape "$event")" \
|
||||
"$(json_escape "$message")" \
|
||||
"$extra" >> "${LOG_FILE:-/var/log/monitoring/events.jsonl}"
|
||||
}
|
||||
|
||||
set_status() {
|
||||
local new_status="$1"
|
||||
if [ "$new_status" -gt "$CURRENT_STATUS" ]; then
|
||||
CURRENT_STATUS="$new_status"
|
||||
fi
|
||||
}
|
||||
|
||||
log_debug() { log_event "DEBUG" "$@"; }
|
||||
log_info() { log_event "INFO" "$@"; }
|
||||
log_notice() { log_event "NOTICE" "$@"; }
|
||||
log_warning() { log_event "WARNING" "$@"; set_status "$STATUS_WARNING"; }
|
||||
log_error() { log_event "ERROR" "$@"; set_status "$STATUS_ERROR"; }
|
||||
log_critical() { log_event "CRITICAL" "$@"; set_status "$STATUS_ERROR"; }
|
||||
|
||||
fail_internal() {
|
||||
log_event "ERROR" "internal_error" "$1"
|
||||
exit "$STATUS_INTERNAL"
|
||||
}
|
||||
|
||||
exit_with_status() {
|
||||
exit "$CURRENT_STATUS"
|
||||
}
|
||||
|
||||
require_cmd() {
|
||||
local cmd
|
||||
for cmd in "$@"; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || fail_internal "Commande requise absente: $cmd"
|
||||
done
|
||||
}
|
||||
|
||||
load_conf_if_exists() {
|
||||
local conf="$1"
|
||||
[ -f "$conf" ] && . "$conf"
|
||||
}
|
||||
|
||||
lock_or_exit() {
|
||||
local lock_name="${1:-$SCRIPT_NAME}"
|
||||
local lock_file="${MONITORING_LOCK_DIR:-/var/lock/monitoring}/${lock_name}.lock"
|
||||
|
||||
exec 9>"$lock_file" || fail_internal "Impossible d'ouvrir le lock $lock_file"
|
||||
flock -n 9 || {
|
||||
log_notice "already_running" "Une autre instance est déjà en cours" "lock=$lock_file"
|
||||
exit 0
|
||||
}
|
||||
}
|
||||
|
||||
threshold_level() {
|
||||
local value="$1"
|
||||
local warning="$2"
|
||||
local critical="$3"
|
||||
|
||||
if [ "$value" -ge "$critical" ]; then
|
||||
printf 'CRITICAL'
|
||||
elif [ "$value" -ge "$warning" ]; then
|
||||
printf 'WARNING'
|
||||
else
|
||||
printf 'INFO'
|
||||
fi
|
||||
}
|
||||
|
||||
safe_mv() {
|
||||
local src="$1"
|
||||
local dst="$2"
|
||||
mv -f "$src" "$dst" || fail_internal "Échec du déplacement de $src vers $dst"
|
||||
}
|
||||
|
||||
ensure_parent_dir() {
|
||||
local file="$1"
|
||||
mkdir -p "$(dirname "$file")" || fail_internal "Impossible de créer le répertoire parent de $file"
|
||||
}
|
||||
112
servers/linux/monitoring/old-bin/monitoring-update-config.sh
Executable file
112
servers/linux/monitoring/old-bin/monitoring-update-config.sh
Executable file
@@ -0,0 +1,112 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2026 Cédric Abonnel
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
set -u
|
||||
|
||||
SCRIPT_NAME="$(basename "$0")"
|
||||
. /opt/monitoring/lib/monitoring-lib.sh || exit 3
|
||||
|
||||
# On s'assure d'avoir les permissions root
|
||||
if [ "${EUID}" -ne 0 ]; then
|
||||
echo "Ce script doit être exécuté en root." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
extract_keys() {
|
||||
local file="$1"
|
||||
grep -E '^[A-Za-z_][A-Za-z0-9_]*=' "$file" | cut -d'=' -f1 | sort -u
|
||||
}
|
||||
|
||||
check_config_drift() {
|
||||
local conf_dir="/opt/monitoring/conf"
|
||||
local base_conf local_conf
|
||||
local found_issue=false
|
||||
local reviewed_files=0
|
||||
local files_requiring_action=0
|
||||
|
||||
log_info "audit_start" "Début de l'audit des configurations locales"
|
||||
|
||||
while IFS= read -r base_conf; do
|
||||
reviewed_files=$((reviewed_files + 1))
|
||||
|
||||
local_conf="${base_conf%.conf}.local.conf"
|
||||
local file_name local_file_name
|
||||
file_name="$(basename "$base_conf")"
|
||||
local_file_name="$(basename "$local_conf")"
|
||||
|
||||
if [ ! -f "$local_conf" ]; then
|
||||
cp "$base_conf" "$local_conf" || {
|
||||
log_error "audit_create_local_failed" \
|
||||
"Impossible de créer ${local_file_name} à partir de ${file_name}"
|
||||
found_issue=true
|
||||
files_requiring_action=$((files_requiring_action + 1))
|
||||
continue
|
||||
}
|
||||
chmod 600 "$local_conf" 2>/dev/null || true
|
||||
|
||||
log_notice "audit_missing_local" \
|
||||
"Le fichier ${local_file_name} n'existait pas ; il a été créé par copie de ${file_name}"
|
||||
continue
|
||||
fi
|
||||
|
||||
local tmp_base tmp_local
|
||||
tmp_base="$(mktemp)" || fail_internal "mktemp a échoué"
|
||||
tmp_local="$(mktemp)" || fail_internal "mktemp a échoué"
|
||||
|
||||
extract_keys "$base_conf" > "$tmp_base"
|
||||
extract_keys "$local_conf" > "$tmp_local"
|
||||
|
||||
local missing obsolete
|
||||
missing="$(comm -23 "$tmp_base" "$tmp_local" | xargs)"
|
||||
obsolete="$(comm -13 "$tmp_base" "$tmp_local" | xargs)"
|
||||
|
||||
if [ -n "$missing" ] || [ -n "$obsolete" ]; then
|
||||
found_issue=true
|
||||
files_requiring_action=$((files_requiring_action + 1))
|
||||
|
||||
log_warning "audit_file_requires_action" \
|
||||
"Le fichier ${local_file_name} nécessite une vérification"
|
||||
|
||||
if [ -n "$missing" ]; then
|
||||
log_warning "audit_keys_missing" \
|
||||
"Dans ${local_file_name}, options disponibles dans ${file_name} mais absentes du local : ${missing}"
|
||||
fi
|
||||
|
||||
if [ -n "$obsolete" ]; then
|
||||
log_info "audit_keys_obsolete" \
|
||||
"Dans ${local_file_name}, options présentes uniquement dans le local et à vérifier ou supprimer : ${obsolete}"
|
||||
fi
|
||||
else
|
||||
log_info "audit_file_ok" \
|
||||
"Le fichier ${local_file_name} contient les mêmes options que ${file_name}"
|
||||
fi
|
||||
|
||||
rm -f "$tmp_base" "$tmp_local"
|
||||
done < <(find "$conf_dir" -maxdepth 1 -type f -name "*.conf" ! -name "*.local.conf" | sort)
|
||||
|
||||
if [ "$found_issue" = false ]; then
|
||||
log_info "audit_success" \
|
||||
"Toutes les configurations locales sont à jour (${reviewed_files} fichier(s) vérifié(s))"
|
||||
else
|
||||
log_warning "audit_requires_action" \
|
||||
"Certaines configurations locales doivent être mises à jour (${files_requiring_action} fichier(s) à vérifier sur ${reviewed_files})"
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
lock_or_exit "monitoring-audit"
|
||||
check_config_drift
|
||||
}
|
||||
|
||||
main
|
||||
exit_with_status
|
||||
247
servers/linux/monitoring/old-bin/monitoring-update.sh
Executable file
247
servers/linux/monitoring/old-bin/monitoring-update.sh
Executable file
@@ -0,0 +1,247 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2026 Cédric Abonnel
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# Moteur de mise à jour des programmes et fichiers connexes
|
||||
|
||||
set -u
|
||||
|
||||
SCRIPT_NAME="$(basename "$0")"
|
||||
SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")"
|
||||
|
||||
# shellcheck source=/opt/monitoring/lib/monitoring-lib.sh
|
||||
. /opt/monitoring/lib/monitoring-lib.sh || exit 3
|
||||
|
||||
load_conf_if_exists "/opt/monitoring/conf/autoupdate.conf"
|
||||
load_conf_if_exists "/opt/monitoring/conf/autoupdate.local.conf"
|
||||
|
||||
# Définir les variables par défaut si elles ne sont pas dans les fichiers .conf
|
||||
UPDATE_TMP_DIR="${UPDATE_TMP_DIR:-/tmp/monitoring-update}"
|
||||
UPDATE_TIMEOUT_CONNECT="${UPDATE_TIMEOUT_CONNECT:-3}"
|
||||
UPDATE_TIMEOUT_TOTAL="${UPDATE_TIMEOUT_TOTAL:-15}"
|
||||
UPDATE_MANIFEST_URL="${UPDATE_MANIFEST_URL:-}"
|
||||
UPDATE_BASE_URL="${UPDATE_BASE_URL:-}"
|
||||
|
||||
lock_or_exit "monitoring-update"
|
||||
require_cmd curl sha256sum awk mktemp chmod dirname mv rm grep sed sort comm cut tr find
|
||||
|
||||
[ "${UPDATE_ENABLED:-true}" = "true" ] || {
|
||||
log_notice "update_disabled" "Mise à jour désactivée par configuration"
|
||||
exit 0
|
||||
}
|
||||
|
||||
mkdir -p "${UPDATE_TMP_DIR:-/tmp/monitoring-update}" || fail_internal "Impossible de créer le répertoire temporaire"
|
||||
|
||||
TMP_MANIFEST="$(mktemp "${UPDATE_TMP_DIR}/manifest.XXXXXX")" || fail_internal "mktemp a échoué"
|
||||
TMP_LOCAL_LIST="$(mktemp "${UPDATE_TMP_DIR}/local.XXXXXX")" || fail_internal "mktemp a échoué"
|
||||
TMP_REMOTE_LIST="$(mktemp "${UPDATE_TMP_DIR}/remote.XXXXXX")" || fail_internal "mktemp a échoué"
|
||||
|
||||
cleanup() {
|
||||
rm -f "$TMP_MANIFEST" "$TMP_LOCAL_LIST" "$TMP_REMOTE_LIST"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
fetch_manifest() {
|
||||
if ! curl -fsS \
|
||||
--connect-timeout "${UPDATE_TIMEOUT_CONNECT:-3}" \
|
||||
--max-time "${UPDATE_TIMEOUT_TOTAL:-15}" \
|
||||
"${UPDATE_MANIFEST_URL}" \
|
||||
-o "$TMP_MANIFEST"; then
|
||||
log_error "manifest_download_failed" \
|
||||
"Impossible de télécharger le manifeste" \
|
||||
"url=${UPDATE_MANIFEST_URL}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! awk '
|
||||
NF == 3 &&
|
||||
$1 ~ /^[0-9a-fA-F]{64}$/ &&
|
||||
$2 ~ /^(644|755)$/ &&
|
||||
$3 ~ /^(bin|lib|conf)\/[A-Za-z0-9._\/-]+$/ &&
|
||||
$3 !~ /\.\./
|
||||
' "$TMP_MANIFEST" >/dev/null; then
|
||||
log_error "manifest_invalid" \
|
||||
"Le manifeste distant est invalide" \
|
||||
"url=${UPDATE_MANIFEST_URL}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "manifest_downloaded" "Manifeste téléchargé" "url=${UPDATE_MANIFEST_URL}"
|
||||
return 0
|
||||
}
|
||||
|
||||
list_remote_files() {
|
||||
awk '{print $3}' "$TMP_MANIFEST" | sort -u > "$TMP_REMOTE_LIST"
|
||||
}
|
||||
|
||||
list_local_files() {
|
||||
find "${MONITORING_BASE_DIR}/bin" "${MONITORING_BASE_DIR}/lib" "${MONITORING_BASE_DIR}/conf" \
|
||||
-type f 2>/dev/null \
|
||||
| sed "s#^${MONITORING_BASE_DIR}/##" \
|
||||
| sort -u > "$TMP_LOCAL_LIST"
|
||||
}
|
||||
|
||||
apply_mode() {
|
||||
local mode="$1"
|
||||
local file="$2"
|
||||
|
||||
case "$mode" in
|
||||
755) chmod 755 "$file" ;;
|
||||
644) chmod 644 "$file" ;;
|
||||
*) fail_internal "Mode non supporté: $mode" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
update_one_file() {
|
||||
local expected_hash="$1"
|
||||
local mode="$2"
|
||||
local rel_path="$3"
|
||||
|
||||
local local_file="${MONITORING_BASE_DIR}/${rel_path}"
|
||||
local remote_file="${UPDATE_BASE_URL}/${rel_path}"
|
||||
local tmp_file local_hash downloaded_hash
|
||||
|
||||
tmp_file="$(mktemp "${UPDATE_TMP_DIR}/$(basename "$rel_path").XXXXXX")" || fail_internal "mktemp a échoué"
|
||||
|
||||
if [ -f "$local_file" ]; then
|
||||
local_hash="$(sha256sum "$local_file" | awk '{print $1}')"
|
||||
else
|
||||
local_hash=""
|
||||
fi
|
||||
|
||||
if [ "$local_hash" = "$expected_hash" ]; then
|
||||
log_debug "update_not_needed" "Fichier déjà à jour" "file=$rel_path"
|
||||
rm -f "$tmp_file"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if ! curl -fsS \
|
||||
--connect-timeout "${UPDATE_TIMEOUT_CONNECT:-3}" \
|
||||
--max-time "${UPDATE_TIMEOUT_TOTAL:-15}" \
|
||||
"$remote_file" \
|
||||
-o "$tmp_file"; then
|
||||
log_error "update_download_failed" \
|
||||
"Téléchargement impossible" \
|
||||
"file=$rel_path" "url=$remote_file"
|
||||
rm -f "$tmp_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
downloaded_hash="$(sha256sum "$tmp_file" | awk '{print $1}')"
|
||||
if [ "$downloaded_hash" != "$expected_hash" ]; then
|
||||
log_error "update_hash_mismatch" \
|
||||
"Hash téléchargé invalide" \
|
||||
"file=$rel_path" "expected=$expected_hash" "got=$downloaded_hash"
|
||||
rm -f "$tmp_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
ensure_parent_dir "$local_file"
|
||||
apply_mode "$mode" "$tmp_file"
|
||||
safe_mv "$tmp_file" "$local_file"
|
||||
|
||||
if [ -z "$local_hash" ]; then
|
||||
log_notice "file_created" \
|
||||
"Fichier créé depuis le manifeste" \
|
||||
"file=$rel_path" "mode=$mode" "hash=$expected_hash"
|
||||
else
|
||||
log_notice "update_applied" \
|
||||
"Mise à jour appliquée" \
|
||||
"file=$rel_path" "mode=$mode" "old_hash=$local_hash" "new_hash=$expected_hash"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
delete_extra_local_files() {
|
||||
[ "${UPDATE_ALLOW_DELETE:-false}" = "true" ] || return 0
|
||||
|
||||
comm -23 "$TMP_LOCAL_LIST" "$TMP_REMOTE_LIST" | while IFS= read -r rel_path; do
|
||||
[ -n "$rel_path" ] || continue
|
||||
|
||||
# Protection globale de TOUS les fichiers .local.conf
|
||||
if [[ "$rel_path" == *.local.conf ]]; then
|
||||
log_notice "delete_skipped" \
|
||||
"Fichier local protégé (ignoré)" \
|
||||
"file=$rel_path"
|
||||
continue
|
||||
fi
|
||||
|
||||
# Sécurité supplémentaire pour ne pas supprimer les répertoires vitaux
|
||||
rm -f "${MONITORING_BASE_DIR}/${rel_path}" \
|
||||
&& log_notice "file_deleted" \
|
||||
"Fichier obsolète supprimé" \
|
||||
"file=$rel_path" \
|
||||
|| log_error "delete_failed" \
|
||||
"Échec suppression" \
|
||||
"file=$rel_path"
|
||||
done
|
||||
}
|
||||
|
||||
run_local_conf_sync() {
|
||||
|
||||
local sync_script="${MONITORING_BASE_DIR}/bin/sync-local-confs.sh"
|
||||
|
||||
if [ -x "$sync_script" ]; then
|
||||
log_info "local_conf_sync_start" \
|
||||
"Synchronisation des fichiers .local.conf"
|
||||
|
||||
if "$sync_script"; then
|
||||
log_info "local_conf_sync_done" \
|
||||
"Synchronisation terminée"
|
||||
else
|
||||
log_warning "local_conf_sync_failed" \
|
||||
"La synchronisation des .local.conf a échoué"
|
||||
fi
|
||||
else
|
||||
log_notice "local_conf_sync_missing" \
|
||||
"Script de synchronisation absent" \
|
||||
"script=$sync_script"
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
local total=0 updated_or_checked=0 failed=0
|
||||
local hash mode path
|
||||
|
||||
fetch_manifest || exit 2
|
||||
list_remote_files
|
||||
list_local_files
|
||||
|
||||
while read -r hash mode path; do
|
||||
[ -n "${hash:-}" ] || continue
|
||||
total=$((total + 1))
|
||||
|
||||
if update_one_file "$hash" "$mode" "$path"; then
|
||||
updated_or_checked=$((updated_or_checked + 1))
|
||||
else
|
||||
failed=$((failed + 1))
|
||||
fi
|
||||
done < "$TMP_MANIFEST"
|
||||
|
||||
delete_extra_local_files
|
||||
|
||||
run_local_conf_sync
|
||||
|
||||
if [ "$failed" -gt 0 ]; then
|
||||
log_warning "update_finished_with_errors" \
|
||||
"Mise à jour terminée avec erreurs" \
|
||||
"total=$total" "updated_or_checked=$updated_or_checked" "failed=$failed"
|
||||
else
|
||||
log_info "update_finished" \
|
||||
"Mise à jour terminée" \
|
||||
"total=$total" "updated_or_checked=$updated_or_checked" "failed=0"
|
||||
fi
|
||||
}
|
||||
|
||||
main
|
||||
exit_with_status
|
||||
27
servers/linux/monitoring/old-bin/monitoring.conf
Normal file
27
servers/linux/monitoring/old-bin/monitoring.conf
Normal file
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# Configuration globale par défaut - NE PAS ÉDITER (Utilisez .local.conf)
|
||||
|
||||
MONITORING_BASE="/opt/monitoring"
|
||||
MONITORING_LOG_DIR="/var/log/monitoring"
|
||||
MONITORING_STATE_DIR="/var/lib/monitoring"
|
||||
MONITORING_LOCK_DIR="/var/lock/monitoring"
|
||||
|
||||
LOG_FILE="${MONITORING_LOG_DIR}/events.jsonl"
|
||||
|
||||
HOSTNAME_FQDN="$(hostname -f 2>/dev/null || hostname)"
|
||||
|
||||
DEST="root"
|
||||
|
||||
NTFY_SERVER="nfy.sh"
|
||||
NTFY_TOPIC="TPOSOB84sBJ6HTZ7"
|
||||
NTFY_TOKEN=""
|
||||
|
||||
UPDATE_ENABLED="true"
|
||||
UPDATE_BASE_URL="https://git.abonnel.fr/cedricAbonnel/scripts-bash/raw/branch/main/servers/linux/monitoring"
|
||||
UPDATE_MANIFEST_URL="${UPDATE_BASE_URL}/manifest.txt"
|
||||
UPDATE_TIMEOUT_CONNECT=3
|
||||
UPDATE_TIMEOUT_TOTAL=15
|
||||
UPDATE_TMP_DIR="/tmp/monitoring-update"
|
||||
UPDATE_ALLOW_DELETE="false"
|
||||
|
||||
mkdir -p "$MONITORING_LOG_DIR" "$MONITORING_STATE_DIR" "$MONITORING_LOCK_DIR" 2>/dev/null || true
|
||||
208
servers/linux/monitoring/old-bin/monitoring.sh
Executable file
208
servers/linux/monitoring/old-bin/monitoring.sh
Executable file
@@ -0,0 +1,208 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2026 Cédric Abonnel
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# lit le fichier log
|
||||
|
||||
set -u
|
||||
|
||||
SCRIPT_NAME="$(basename "$0")"
|
||||
SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")"
|
||||
|
||||
# shellcheck source=/opt/monitoring/lib/monitoring-lib.sh
|
||||
. /opt/monitoring/lib/monitoring-lib.sh || exit 3
|
||||
|
||||
load_conf_if_exists "/opt/monitoring/conf/autoupdate.conf"
|
||||
|
||||
lock_or_exit "monitoring-update"
|
||||
require_cmd curl sha256sum awk mktemp chmod dirname mv rm grep sed sort comm cut tr
|
||||
|
||||
[ "${UPDATE_ENABLED:-true}" = "true" ] || {
|
||||
log_notice "update_disabled" "Mise à jour désactivée par configuration"
|
||||
exit 0
|
||||
}
|
||||
|
||||
mkdir -p "${UPDATE_TMP_DIR:-/tmp/monitoring-update}" || fail_internal "Impossible de créer le répertoire temporaire"
|
||||
|
||||
TMP_MANIFEST="$(mktemp "${UPDATE_TMP_DIR}/manifest.XXXXXX")" || fail_internal "mktemp a échoué"
|
||||
TMP_LOCAL_LIST="$(mktemp "${UPDATE_TMP_DIR}/local.XXXXXX")" || fail_internal "mktemp a échoué"
|
||||
TMP_REMOTE_LIST="$(mktemp "${UPDATE_TMP_DIR}/remote.XXXXXX")" || fail_internal "mktemp a échoué"
|
||||
|
||||
cleanup() {
|
||||
rm -f "$TMP_MANIFEST" "$TMP_LOCAL_LIST" "$TMP_REMOTE_LIST"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
fetch_manifest() {
|
||||
if ! curl -fsS \
|
||||
--connect-timeout "${UPDATE_TIMEOUT_CONNECT:-3}" \
|
||||
--max-time "${UPDATE_TIMEOUT_TOTAL:-15}" \
|
||||
"${UPDATE_MANIFEST_URL}" \
|
||||
-o "$TMP_MANIFEST"; then
|
||||
log_error "manifest_download_failed" "Impossible de télécharger le manifeste" "url=${UPDATE_MANIFEST_URL}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! awk '
|
||||
NF == 3 &&
|
||||
$1 ~ /^[0-9a-fA-F]{64}$/ &&
|
||||
$2 ~ /^(644|755)$/ &&
|
||||
$3 ~ /^(bin|lib|conf)\/[A-Za-z0-9._\/-]+$/ &&
|
||||
$3 !~ /\.\./
|
||||
' "$TMP_MANIFEST" >/dev/null; then
|
||||
log_error "manifest_invalid" "Le manifeste distant est invalide" "url=${UPDATE_MANIFEST_URL}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "manifest_downloaded" "Manifeste téléchargé" "url=${UPDATE_MANIFEST_URL}"
|
||||
return 0
|
||||
}
|
||||
|
||||
list_remote_files() {
|
||||
awk '{print $3}' "$TMP_MANIFEST" | sort -u > "$TMP_REMOTE_LIST"
|
||||
}
|
||||
|
||||
list_local_files() {
|
||||
find "${MONITORING_BASE_DIR}/bin" "${MONITORING_BASE_DIR}/lib" "${MONITORING_BASE_DIR}/conf" \
|
||||
-type f 2>/dev/null \
|
||||
| sed "s#^${MONITORING_BASE_DIR}/##" \
|
||||
| sort -u > "$TMP_LOCAL_LIST"
|
||||
}
|
||||
|
||||
apply_mode() {
|
||||
local mode="$1"
|
||||
local file="$2"
|
||||
|
||||
case "$mode" in
|
||||
755) chmod 755 "$file" ;;
|
||||
644) chmod 644 "$file" ;;
|
||||
*) fail_internal "Mode non supporté: $mode" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
update_one_file() {
|
||||
local expected_hash="$1"
|
||||
local mode="$2"
|
||||
local rel_path="$3"
|
||||
|
||||
local local_file="${MONITORING_BASE_DIR}/${rel_path}"
|
||||
local remote_file="${UPDATE_BASE_URL}/${rel_path}"
|
||||
local tmp_file local_hash downloaded_hash
|
||||
|
||||
tmp_file="$(mktemp "${UPDATE_TMP_DIR}/$(basename "$rel_path").XXXXXX")" || fail_internal "mktemp a échoué"
|
||||
|
||||
if [ -f "$local_file" ]; then
|
||||
local_hash="$(sha256sum "$local_file" | awk '{print $1}')"
|
||||
else
|
||||
local_hash=""
|
||||
fi
|
||||
|
||||
if [ "$local_hash" = "$expected_hash" ]; then
|
||||
log_debug "update_not_needed" "Fichier déjà à jour" "file=$rel_path"
|
||||
rm -f "$tmp_file"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if ! curl -fsS \
|
||||
--connect-timeout "${UPDATE_TIMEOUT_CONNECT:-3}" \
|
||||
--max-time "${UPDATE_TIMEOUT_TOTAL:-15}" \
|
||||
"$remote_file" \
|
||||
-o "$tmp_file"; then
|
||||
log_error "update_download_failed" "Téléchargement impossible" "file=$rel_path" "url=$remote_file"
|
||||
rm -f "$tmp_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
downloaded_hash="$(sha256sum "$tmp_file" | awk '{print $1}')"
|
||||
if [ "$downloaded_hash" != "$expected_hash" ]; then
|
||||
log_error "update_hash_mismatch" "Hash téléchargé invalide" \
|
||||
"file=$rel_path" "expected=$expected_hash" "got=$downloaded_hash"
|
||||
rm -f "$tmp_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
ensure_parent_dir "$local_file"
|
||||
apply_mode "$mode" "$tmp_file"
|
||||
safe_mv "$tmp_file" "$local_file"
|
||||
|
||||
if [ -z "$local_hash" ]; then
|
||||
log_notice "file_created" "Fichier créé depuis le manifeste" \
|
||||
"file=$rel_path" "mode=$mode" "hash=$expected_hash"
|
||||
else
|
||||
log_notice "update_applied" "Mise à jour appliquée" \
|
||||
"file=$rel_path" "mode=$mode" "old_hash=$local_hash" "new_hash=$expected_hash"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
delete_extra_local_files() {
|
||||
|
||||
[ "${UPDATE_ALLOW_DELETE:-false}" = "true" ] || return 0
|
||||
|
||||
comm -23 "$TMP_LOCAL_LIST" "$TMP_REMOTE_LIST" | while IFS= read -r rel_path; do
|
||||
|
||||
[ -n "$rel_path" ] || continue
|
||||
|
||||
case "$rel_path" in
|
||||
conf/autoupdate.conf|conf/alert-engine.local.conf)
|
||||
log_notice "delete_skipped" \
|
||||
"Suppression ignorée pour fichier local protégé" \
|
||||
"file=$rel_path"
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
rm -f "${MONITORING_BASE_DIR}/${rel_path}" \
|
||||
&& log_notice "file_deleted" \
|
||||
"Fichier supprimé car absent du manifeste" \
|
||||
"file=$rel_path" \
|
||||
|| log_error "delete_failed" \
|
||||
"Impossible de supprimer fichier local" \
|
||||
"file=$rel_path"
|
||||
|
||||
done
|
||||
}
|
||||
|
||||
main() {
|
||||
local total=0 updated=0 failed=0 hash mode path
|
||||
|
||||
fetch_manifest || exit 2
|
||||
list_remote_files
|
||||
list_local_files
|
||||
|
||||
while read -r hash mode path; do
|
||||
[ -n "${hash:-}" ] || continue
|
||||
total=$((total + 1))
|
||||
|
||||
if update_one_file "$hash" "$mode" "$path"; then
|
||||
updated=$((updated + 1))
|
||||
else
|
||||
failed=$((failed + 1))
|
||||
fi
|
||||
done < "$TMP_MANIFEST"
|
||||
|
||||
delete_extra_local_files
|
||||
|
||||
if [ "$failed" -gt 0 ]; then
|
||||
log_warning "update_finished_with_errors" \
|
||||
"Mise à jour terminée avec erreurs" \
|
||||
"total=$total" "updated_or_checked=$updated" "failed=$failed"
|
||||
else
|
||||
log_info "update_finished" \
|
||||
"Mise à jour terminée" \
|
||||
"total=$total" "updated_or_checked=$updated" "failed=0"
|
||||
fi
|
||||
}
|
||||
|
||||
main
|
||||
exit_with_status
|
||||
1
servers/linux/setup_firewall_ui.sh.sha256
Normal file
1
servers/linux/setup_firewall_ui.sh.sha256
Normal file
@@ -0,0 +1 @@
|
||||
89f1c5a498ae189a696ebda775d044c0330326641cf8072f218018c30aca772c setup_firewall_ui.sh
|
||||
@@ -1,216 +1,41 @@
|
||||
#!/bin/bash
|
||||
# Copyright (C) 2024 Cédric Abonnel
|
||||
# Script de transition automatique AGPL v3
|
||||
|
||||
# --- CONFIGURATION ---
|
||||
THRESHOLD=80
|
||||
LOAD_THRESHOLD=5.0
|
||||
PROC_THRESHOLD=500
|
||||
TMP_THRESHOLD=90
|
||||
CONN_THRESHOLD=500
|
||||
HOST=$(hostname)
|
||||
SCRIPT_PATH="$0"
|
||||
SCRIPT_NAME=$(basename "$SCRIPT_PATH")
|
||||
set -euo pipefail
|
||||
|
||||
# On envoie à 'root', le système fera la redirection grâce aux aliases
|
||||
DEST="root"
|
||||
INSTALLER_URL="https://git.abonnel.fr/cedricAbonnel/scripts-bash/raw/branch/main/servers/linux/monitoring/bin/install-monitoring.sh"
|
||||
BASE_DIR="/opt/monitoring"
|
||||
|
||||
REPORT=""
|
||||
ALERT=false
|
||||
echo "[$(date)] Début de la vérification du monitoring..."
|
||||
|
||||
|
||||
# Fonction pour ajouter une ligne au rapport avec une icône
|
||||
add_to_report() {
|
||||
REPORT="${REPORT}$1\n"
|
||||
}
|
||||
|
||||
|
||||
|
||||
# --- Configuration de l'auto-update ---
|
||||
|
||||
BASE_URL="https://git.abonnel.fr/cedricAbonnel/scripts-bash/raw/branch/main/servers/linux"
|
||||
URL_SCRIPT="${BASE_URL}/${SCRIPT_NAME}"
|
||||
URL_HASH="${URL_SCRIPT}.sha256" # On suppose qu'un fichier .sha256 existe
|
||||
TMP_FILE="/tmp/${SCRIPT_NAME}.new"
|
||||
|
||||
# --- Fonction de mise à jour ---
|
||||
update_script() {
|
||||
# 1. Récupérer le hash distant avec timeout
|
||||
REMOTE_HASH=$(curl -s -f --connect-timeout 3 --max-time 5 "$URL_HASH" | awk '{print $1}')
|
||||
# 1. Vérifier si le nouveau système est déjà là
|
||||
if [ ! -d "$BASE_DIR" ]; then
|
||||
echo "[Transition] Nouveau système absent. Installation forcée..."
|
||||
# On télécharge et on lance l'installateur
|
||||
curl -sSL "$INSTALLER_URL" | bash
|
||||
|
||||
# Si on n'arrive pas à lire le hash distant, on ignore l'update
|
||||
[[ -z "$REMOTE_HASH" ]] && return 1
|
||||
|
||||
# 2. Calculer le hash local
|
||||
LOCAL_HASH=$(sha256sum "$SCRIPT_PATH" | awk '{print $1}')
|
||||
|
||||
# 3. Comparaison
|
||||
if [ "$LOCAL_HASH" != "$REMOTE_HASH" ]; then
|
||||
echo "[Update] Nouvelle version détectée..."
|
||||
|
||||
# 4. Téléchargement du nouveau script
|
||||
if curl -s -f --connect-timeout 5 --max-time 10 "$URL_SCRIPT" -o "$TMP_FILE"; then
|
||||
|
||||
# 5. Vérification du hash du fichier téléchargé (Sécurité)
|
||||
DOWNLOADED_HASH=$(sha256sum "$TMP_FILE" | awk '{print $1}')
|
||||
|
||||
if [ "$DOWNLOADED_HASH" == "$REMOTE_HASH" ]; then
|
||||
mv "$TMP_FILE" "$SCRIPT_PATH"
|
||||
chmod +x "$SCRIPT_PATH"
|
||||
echo "[Update] Mise à jour appliquée. Relance..."
|
||||
exec "$SCRIPT_PATH" "$@"
|
||||
else
|
||||
echo "[Error] Hash corrompu après téléchargement."
|
||||
rm -f "$TMP_FILE"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# Lancer la vérification
|
||||
update_script "$@"
|
||||
|
||||
# --- Reste du script ---
|
||||
echo "Exécution du script principal..."
|
||||
|
||||
|
||||
|
||||
# 1. CHECK DISQUE & INODES
|
||||
DISK_USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
|
||||
INODE_USAGE=$(df -i / | awk 'NR==2 {print $5}' | sed 's/%//')
|
||||
|
||||
if [ "$DISK_USAGE" -gt "$THRESHOLD" ]; then
|
||||
add_to_report "⚠️ DISQUE : $DISK_USAGE% utilisé\n"
|
||||
ALERT=true
|
||||
fi
|
||||
if [ "$INODE_USAGE" -gt "$THRESHOLD" ]; then
|
||||
add_to_report "⚠️ INODES : $INODE_USAGE% utilisé\n"
|
||||
ALERT=true
|
||||
# Optionnel : Envoyer une dernière alerte via l'ancien système pour dire que c'est fait
|
||||
# (Utilise vos anciennes variables NTFY si elles sont encore en mémoire)
|
||||
echo "Transition réussie vers /opt/monitoring"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# --- CHECK RAM & SWAP ---
|
||||
RAM_USAGE=$(free | grep Mem | awk '{print int($3/$2 * 100)}')
|
||||
|
||||
# On ajoute '|| echo 0' pour s'assurer que la variable n'est jamais vide
|
||||
SWAP_TOTAL=$(free | grep Swap | awk '{print $2}' | grep -E '^[0-9]+$' || echo 0)
|
||||
|
||||
if [ "$RAM_USAGE" -gt "$THRESHOLD" ]; then
|
||||
add_to_report "⚠️ RAM : $RAM_USAGE% utilisé\n"
|
||||
ALERT=true
|
||||
# 2. Si déjà installé, on s'assure qu'il reste à jour
|
||||
if [ -f "$BASE_DIR/bin/monitoring-update.sh" ]; then
|
||||
echo "[Transition] Mise à jour des scripts..."
|
||||
"$BASE_DIR/bin/monitoring-update.sh"
|
||||
fi
|
||||
|
||||
# On vérifie si SWAP_TOTAL est supérieur à 0 et n'est pas vide
|
||||
if [ -n "$SWAP_TOTAL" ] && [ "$SWAP_TOTAL" -gt 0 ]; then
|
||||
# Calcul du SWAP_USAGE avec une sécurité pour éviter la division par zéro
|
||||
SWAP_USAGE=$(free | grep Swap | awk '{print ($2>0) ? int($3/$2 * 100) : 0}')
|
||||
if [ "$SWAP_USAGE" -gt 50 ]; then
|
||||
add_to_report "⚠️ SWAP : $SWAP_USAGE% utilisé (Saturation RAM imminente)\n"
|
||||
ALERT=true
|
||||
fi
|
||||
# 3. Lancement des sondes migrées
|
||||
# On appelle les nouveaux scripts pour que le monitoring continue de tourner
|
||||
if [ -f "$BASE_DIR/bin/check_disk.sh" ]; then
|
||||
"$BASE_DIR/bin/check_disk.sh"
|
||||
fi
|
||||
|
||||
# 3. CHECK CHARGE CPU
|
||||
CPU_LOAD=$(uptime | awk -F'load average:' '{ print $2 }' | cut -d',' -f1 | tr -d ' ' | tr ',' '.')
|
||||
if (( $(echo "$CPU_LOAD > $LOAD_THRESHOLD" | bc -l) )); then
|
||||
add_to_report "🔥 CPU LOAD : $CPU_LOAD (Surcharge)\n"
|
||||
ALERT=true
|
||||
# Lancer le moteur d'alerte pour traiter les éventuels logs
|
||||
if [ -f "$BASE_DIR/bin/alert-engine.sh" ]; then
|
||||
"$BASE_DIR/bin/alert-engine.sh"
|
||||
fi
|
||||
|
||||
# 4. CHECK SERVICES (SSH et Fail2Ban sont vitaux)
|
||||
for SVC in "ssh" "fail2ban"; do
|
||||
if ! systemctl is-active --quiet "$SVC"; then
|
||||
add_to_report "❌ SERVICE : $SVC est ARRÊTÉ\n"
|
||||
ALERT=true
|
||||
fi
|
||||
done
|
||||
|
||||
# ------------------------------------------------
|
||||
# 5. NOMBRE DE PROCESSUS
|
||||
# ------------------------------------------------
|
||||
PROC_COUNT=$(ps -e --no-headers | wc -l)
|
||||
|
||||
if [ "$PROC_COUNT" -gt "$PROC_THRESHOLD" ]; then
|
||||
add_to_report "PROCESSUS : $PROC_COUNT processus actifs\n"
|
||||
ALERT=true
|
||||
fi
|
||||
|
||||
# ------------------------------------------------
|
||||
# 6. ESPACE /tmp
|
||||
# ------------------------------------------------
|
||||
TMP_USAGE=$(df /tmp | awk 'NR==2 {print $5}' | sed 's/%//')
|
||||
|
||||
if [ "$TMP_USAGE" -gt "$TMP_THRESHOLD" ]; then
|
||||
add_to_report "/tmp : $TMP_USAGE% utilisé\n"
|
||||
ALERT=true
|
||||
fi
|
||||
|
||||
# ------------------------------------------------
|
||||
# 7. PROCESSUS ZOMBIES
|
||||
# ------------------------------------------------
|
||||
ZOMBIES=$(ps aux | awk '{ if ($8=="Z") print $0 }' | wc -l)
|
||||
|
||||
if [ "$ZOMBIES" -gt 0 ]; then
|
||||
add_to_report "ZOMBIES : $ZOMBIES processus zombies\n"
|
||||
ALERT=true
|
||||
fi
|
||||
|
||||
# ------------------------------------------------
|
||||
# 8. FICHIERS SUPPRIMÉS MAIS OUVERTS (Filtré)
|
||||
# ------------------------------------------------
|
||||
# On récupère les données, puis on exclut les processus du script lui-même
|
||||
# On exclut aussi souvent 'systemd-j' (journal) car il gère ses propres rotations
|
||||
DELETED_DATA=$(sudo lsof +L1 2>/dev/null | tail -n +2 | grep -Ev "grep|lsof|tail|cron|sh|systemd-j|sys_check")
|
||||
|
||||
# On compte proprement les lignes
|
||||
DELETED_COUNT=$(echo "$DELETED_DATA" | grep -v '^$' | wc -l)
|
||||
|
||||
if (( DELETED_COUNT > 0 )); then
|
||||
# On extrait les noms des commandes uniques pour le rapport
|
||||
PROCESS_NAMES=$(echo "$DELETED_DATA" | awk '{print $1}' | sort -u | xargs)
|
||||
|
||||
add_to_report "📂 FICHIERS SUPPRIMÉS MAIS OUVERTS : $DELETED_COUNT (Processus : $PROCESS_NAMES)"
|
||||
ALERT=true
|
||||
fi
|
||||
|
||||
|
||||
|
||||
# ------------------------------------------------
|
||||
# 9. CONNEXIONS RÉSEAU
|
||||
# ------------------------------------------------
|
||||
CONN_COUNT=$(ss -tun | tail -n +2 | wc -l)
|
||||
|
||||
if [ "$CONN_COUNT" -gt "$CONN_THRESHOLD" ]; then
|
||||
add_to_report "CONNEXIONS RÉSEAU : $CONN_COUNT\n"
|
||||
ALERT=true
|
||||
fi
|
||||
|
||||
|
||||
# ------------------------------------------------
|
||||
# 10. ERREURS CRITIQUES (Dernière heure)
|
||||
# ------------------------------------------------
|
||||
# On filtre par priorité 3 (Error) ou moins, depuis 1 heure
|
||||
LOG_CONTENT=$(journalctl -p 3 --since "1 hour ago" --no-pager --quiet)
|
||||
|
||||
# On compte le nombre de lignes réelles
|
||||
LOG_COUNT=$(echo "$LOG_CONTENT" | grep -v '^--' | grep -v '^$' | wc -l)
|
||||
|
||||
if (( LOG_COUNT > 0 )); then
|
||||
add_to_report "📑 ERREURS CRITIQUES (Dernière heure : $LOG_COUNT) :"
|
||||
add_to_report "$(echo "$LOG_CONTENT" | tail -n 15 | sed 's/^/ /')"
|
||||
ALERT=true
|
||||
fi
|
||||
|
||||
|
||||
# ------------------------------------------------
|
||||
# ENVOI MAIL
|
||||
# ------------------------------------------------
|
||||
if [ "$ALERT" = true ]; then
|
||||
SUBJECT="🔴 ALERTE SERVEUR [$HOST] - $(date +'%H:%M')"
|
||||
|
||||
# Construction du corps du mail avec un header propre
|
||||
MAIL_BODY="Bonjour,\n\nUne ou plusieurs anomalies ont été détectées sur le serveur : $HOST\n"
|
||||
MAIL_BODY="$MAIL_BODY\n------------------------------------------------\n"
|
||||
MAIL_BODY="$MAIL_BODY$REPORT"
|
||||
MAIL_BODY="$MAIL_BODY\n------------------------------------------------\n"
|
||||
MAIL_BODY="$MAIL_BODY\nDate du rapport : $(date)"
|
||||
|
||||
echo -e "$MAIL_BODY" | mail -s "$SUBJECT" "$DEST"
|
||||
fi
|
||||
echo "[Transition] Fin du cycle automatique."
|
||||
1
servers/linux/sys_check.sh.sha256
Normal file
1
servers/linux/sys_check.sh.sha256
Normal file
@@ -0,0 +1 @@
|
||||
ed2cd7671fd7e22314856972bdb86412e2fbac575051f182640260efa299cd9c sys_check.sh
|
||||
Reference in New Issue
Block a user