More madness cleanup

This commit is contained in:
Alexandre Aubin 2020-12-06 03:23:27 +01:00
parent 9009a49a15
commit a15015c905
14 changed files with 1493 additions and 2529 deletions

33
config.defaults Normal file
View file

@ -0,0 +1,33 @@
#####################
# LXC Configuration #
#####################
# Network stuff
MAIN_NETWORK_INTERFACE=$(sudo ip route | grep default | awk '{print $5;}')
LXC_BRIDGE="lxc-pchecker"
LXC_NETWORK="10.1.4"
DNS_RESOLVER="80.67.169.12"
# Container configuration
DISTRIB="buster"
LXC_NAME="pchecker_lxc"
LXC_ROOTFS="/var/lib/lxc/$LXC_NAME/rootfs"
LXC_SNAPSHOTS="/var/lib/lxcsnaps/$LXC_NAME"
###########################
# Yunohost configuration #
###########################
# By default we'll install Yunohost with the default branch
YNH_INSTALL_SCRIPT_BRANCH=""
# Admin password
YUNO_PWD="admin"
# Domaines de test
DOMAIN="domain.tld"
SUBDOMAIN="sub.$DOMAIN"
# User de test
TEST_USER="package_checker"

View file

@ -1,28 +0,0 @@
# Interface réseau principale de l'hôte
iface=
# Adresse du dns
dns=
# Forçage du dns
dnsforce=
# Plage IP du conteneur
PLAGE_IP=
# Domaine de test
DOMAIN=
# Mot de passe
YUNO_PWD=
# Nom du conteneur
LXC_NAME=
# Nom du bridge
LXC_BRIDGE=
# Distribution debian
DISTRIB=
# Branche à utiliser pour le script d'install de cette distribution (si non standard)
BRANCH=

File diff suppressed because it is too large Load diff

View file

@ -1,27 +0,0 @@
#!/bin/bash
# Ce script n'a vocation qu'a être dans un cron. De préférence une fois par jour ou par semaine.
# Récupère le dossier du script
if [ "${0:0:1}" == "/" ]; then script_dir="$(dirname "$0")"; else script_dir="$(echo $PWD/$(dirname "$0" | cut -d '.' -f2) | sed 's@/$@@')"; fi
echo ""
date
# Vérifie que Package check n'est pas déjà utilisé.
timeout=7200 # Durée d'attente maximale
inittime=$(date +%s) # Enregistre l'heure de début d'attente
while test -e "$script_dir/../pcheck.lock"; do # Vérifie la présence du lock de Package check
sleep 60 # Attend la fin de l'exécution de Package check.
echo -n "."
if [ $(( $(date +%s) - $inittime )) -ge $timeout ] # Vérifie la durée d'attente
then # Si la durée dépasse le timeout fixé, force l'arrêt.
inittime=0 # Indique l'arrêt forcé du script
echo "Temps d'attente maximal dépassé, la mise à jour est annulée."
break
fi
done
echo ""
if [ "$inittime" -ne 0 ]; then # Continue seulement si le timeout n'est pas dépassé.
"$script_dir/lxc_upgrade.sh" # Exécute le script d'upgrade de Package check
fi

View file

@ -1,5 +1,40 @@
#!/bin/bash #!/bin/bash
[[ -e "./config.defaults" ]] && source "./config.defaults"
[[ -e "./config" ]] && source "./config"
readonly lock_file="./pcheck.lock"
#=================================================
# LXC helpers
#=================================================
RUN_INSIDE_LXC() {
sudo lxc-attach -n $LXC_NAME -- "$@"
}
RUN_THROUGH_SSH() {
ssh -tt -q $LXC_NAME "sudo $@"
}
assert_we_are_the_setup_user() {
[ -e "./.setup_user" ] || return
local setup_user=$(cat "./.setup_user")
[ "$(whoami)" == $setup_user ] \
|| log_critical "Ce script doit être exécuté avec l'utilisateur $setup_user !\nL'utilisateur actuel est $(whoami)."
}
assert_we_are_connected_to_the_internets() {
ping -q -c 2 yunohost.org > /dev/null 2>&1 \
|| ping -q -c 2 framasoft.org > /dev/null 2>&1 \
|| log_critical "Unable to connect to internet."
}
#=================================================
# Logging helpers
#=================================================
readonly NORMAL=$(printf '\033[0m') readonly NORMAL=$(printf '\033[0m')
readonly BOLD=$(printf '\033[1m') readonly BOLD=$(printf '\033[1m')
readonly faint=$(printf '\033[2m') readonly faint=$(printf '\033[2m')
@ -12,9 +47,9 @@ readonly BLUE=$(printf '\033[34m')
readonly YELLOW=$(printf '\033[93m') readonly YELLOW=$(printf '\033[93m')
readonly WHITE=$(printf '\033[39m') readonly WHITE=$(printf '\033[39m')
function title() function log_title()
{ {
cat << EOF | tee -a "$complete_log" cat << EOF
${BOLD} ${BOLD}
=================================== ===================================
$1 $1
@ -23,51 +58,187 @@ ${NORMAL}
EOF EOF
} }
function small_title() function log_small_title()
{ {
echo -e "\n${BOLD} > ${1}${NORMAL}\n" | tee -a "$complete_log" echo -e "\n${BOLD} > ${1}${NORMAL}\n"
} }
function debug() function log_debug()
{ {
echo "$1" >> "$complete_log" echo "$1"
} }
function info() function log_info()
{ {
echo "${1}" | tee -a "$complete_log" echo "${1}"
} }
function success() function log_success()
{ {
echo "${BOLD}${GREEN}Success: ${1}${NORMAL}" | tee -a "$complete_log" echo "${BOLD}${GREEN}Success: ${1}${NORMAL}"
} }
function warning() function log_warning()
{ {
echo "${BOLD}${ORANGE}Warning: ${1}${NORMAL}" | tee -a "$complete_log" 2>&1 echo "${BOLD}${ORANGE}Warning: ${1}${NORMAL}"
} }
function error() function log_error()
{ {
echo "${BOLD}${RED}Error: ${1}${NORMAL}" | tee -a "$complete_log" 2>&1 echo "${BOLD}${RED}Error: ${1}${NORMAL}"
} }
function critical() function log_critical()
{ {
echo "${BOLD}${RED}Critical: ${1}${NORMAL}" | tee -a "$complete_log" 2>&1 echo "${BOLD}${RED}Critical: ${1}${NORMAL}"
clean_exit 1 clean_exit 1
} }
function report_test_success () { function log_report_test_success () {
echo -e "\n${BOLD}${GREEN}--- SUCCESS ---${NORMAL}\n" | tee -a "$complete_log" 2>&1 echo -e "\n${BOLD}${GREEN}--- SUCCESS ---${NORMAL}\n"
} }
function report_test_warning () { function log_report_test_warning () {
echo -e "\n${BOLD}${ORANGE}--- WARNING ---${NORMAL}\n" | tee -a "$complete_log" 2>&1 echo -e "\n${BOLD}${ORANGE}--- WARNING ---${NORMAL}\n"
} }
function report_test_failed () { function log_report_test_failed () {
echo -e "\n${BOLD}${RED}--- FAIL ---${NORMAL}\n" | tee -a "$complete_log" 2>&1 echo -e "\n${BOLD}${RED}--- FAIL ---${NORMAL}\n"
} }
#=================================================
# Timing helpers
#=================================================
start_timer () {
# Set the beginning of the timer
starttime=$(date +%s)
}
stop_timer () {
# Ending the timer
# $1 = Type of querying
local finishtime=$(date +%s)
# Calculate the gap between the starting and the ending of the timer
local elapsedtime=$(echo $(( $finishtime - $starttime )))
# Extract the number of hour
local hours=$(echo $(( $elapsedtime / 3600 )))
local elapsedtime=$(echo $(( $elapsedtime - ( 3600 * $hours) )))
# Minutes
local minutes=$(echo $(( $elapsedtime / 60 )))
# And seconds
local seconds=$(echo $(( $elapsedtime - ( 60 * $minutes) )))
local phours=""
local pminutes=""
local pseconds=""
# Avoid null values
[ $hours -eq 0 ] || phours="$hours hour"
[ $minutes -eq 0 ] || pminutes="$minutes minute"
[ $seconds -eq 0 ] || pseconds="$seconds second"
# Add a 's' for plural values
[ $hours -eq 1 ] && phours="${phours}, " || test -z "$phours" || phours="${phours}s, "
[ $minutes -eq 1 ] && pminutes="${pminutes}, " || test -z "$pminutes" || pminutes="${pminutes}s, "
[ $seconds -gt 1 ] && pseconds="${pseconds}s"
time="${phours}${pminutes}${pseconds} ($(date '+%T'))"
if [ $1 -eq 2 ]; then
log_info "Working time for this test: $time"
elif [ $1 -eq 3 ]; then
log_info "Global working time for all tests: $time"
else
log_debug "Working time: $time"
fi
}
#=================================================
# Upgrade Package check
#=================================================
function self_upgrade()
{
local git_repository=https://github.com/YunoHost/package_check
local version_file="./.pcheck_version"
local check_version="$(git ls-remote $git_repository | cut -f 1 | head -n1)"
# If the version file exist, check for an upgrade
if [ -e "$version_file" ]
then
# Check if the last commit on the repository match with the current version
if [ "$check_version" != "$(cat "$version_file")" ]
then
# If the versions don't matches. Do an upgrade
log_info "Upgrading Package check"
# Build the upgrade script
cat > "./upgrade_script.sh" << EOF
#!/bin/bash
# Clone in another directory
git clone --quiet $git_repository "./upgrade"
cp -a "./upgrade/." "./."
sudo rm -r "./upgrade"
# Update the version file
echo "$check_version" > "$version_file"
rm "./pcheck.lock"
# Execute package check by replacement of this process
exec "./package_check.sh" "${arguments[@]}"
EOF
# Give the execution right
chmod +x "./upgrade_script.sh"
# Start the upgrade script by replacement of this process
exec "./upgrade_script.sh"
fi
fi
# Update the version file
echo "$check_version" > "$version_file"
}
#=================================================
# Upgrade Package linter
#=================================================
function fetch_or_upgrade_package_linter()
{
local git_repository=https://github.com/YunoHost/package_linter
local version_file="./.plinter_version"
local check_version="$(git ls-remote $git_repository | cut -f 1 | head -n1)"
# If the version file exist, check for an upgrade
if [ -e "$version_file" ]
then
# Check if the last commit on the repository match with the current version
if [ "$check_version" != "$(cat "$version_file")" ]
then
# If the versions don't matches. Do an upgrade
log_info "Upgrading Package linter"
# Clone in another directory
git clone --quiet $git_repository "./package_linter_tmp"
pip3 install pyparsing six
# And replace
cp -a "./package_linter_tmp/." "./package_linter/."
sudo rm -r "./package_linter_tmp"
fi
else
log_info "Installing Package linter"
git clone --quiet $git_repository "./package_linter"
pip3 install pyparsing six
fi
# Update the version file
echo "$check_version" > "$version_file"
}

View file

@ -1,69 +1,18 @@
# #!/bin/bash # #!/bin/bash
echo -e "Loads functions from launcher.sh"
#================================================= #=================================================
# Globals variables # Globals variables
#================================================= #=================================================
# -q aims to disable the display of 'Debian GNU/Linux' each time a command is ran # -q aims to disable the display of 'Debian GNU/Linux' each time a command is ran
arg_ssh="-tt -q" arg_ssh="-tt -q"
snapshot_path="/var/lib/lxcsnaps/$lxc_name"
current_snapshot=snap0 current_snapshot=snap0
#=================================================
# TIMER
#=================================================
start_timer () {
# Set the beginning of the timer
starttime=$(date +%s)
}
stop_timer () {
# Ending the timer
# $1 = Type of querying
local finishtime=$(date +%s)
# Calculate the gap between the starting and the ending of the timer
local elapsedtime=$(echo $(( $finishtime - $starttime )))
# Extract the number of hour
local hours=$(echo $(( $elapsedtime / 3600 )))
local elapsedtime=$(echo $(( $elapsedtime - ( 3600 * $hours) )))
# Minutes
local minutes=$(echo $(( $elapsedtime / 60 )))
# And seconds
local seconds=$(echo $(( $elapsedtime - ( 60 * $minutes) )))
local phours=""
local pminutes=""
local pseconds=""
# Avoid null values
[ $hours -eq 0 ] || phours="$hours hour"
[ $minutes -eq 0 ] || pminutes="$minutes minute"
[ $seconds -eq 0 ] || pseconds="$seconds second"
# Add a 's' for plural values
[ $hours -eq 1 ] && phours="${phours}, " || test -z "$phours" || phours="${phours}s, "
[ $minutes -eq 1 ] && pminutes="${pminutes}, " || test -z "$pminutes" || pminutes="${pminutes}s, "
[ $seconds -gt 1 ] && pseconds="${pseconds}s"
time="${phours}${pminutes}${pseconds} ($(date '+%T'))"
if [ $1 -eq 2 ]; then
info "Working time for this test: $time"
elif [ $1 -eq 3 ]; then
info "Global working time for all tests: $time"
else
info "Working time: $time" >/dev/null
fi
}
#================================================= #=================================================
# RUNNING SNAPSHOT # RUNNING SNAPSHOT
#================================================= #=================================================
create_temp_backup () { CREATE_LXC_SNAPSHOT () {
# Create a temporary snapshot # Create a temporary snapshot
# snap1 for subpath or snap2 for root install # snap1 for subpath or snap2 for root install
@ -74,10 +23,10 @@ create_temp_backup () {
check_witness_files >&2 check_witness_files >&2
# Stop the container, before its snapshot # Stop the container, before its snapshot
sudo lxc-stop --name $lxc_name >&2 sudo lxc-stop --name $LXC_NAME >&2
# Remove swap files to avoid killing the CI with huge snapshots. # Remove swap files to avoid killing the CI with huge snapshots.
local swap_file="/var/lib/lxc/$lxc_name/rootfs/swap_$ynh_app_id" local swap_file="$LXC_ROOTFS/swap_$app_id"
if sudo test -e "$swap_file" if sudo test -e "$swap_file"
then then
sudo swapoff "$swap_file" sudo swapoff "$swap_file"
@ -85,23 +34,23 @@ create_temp_backup () {
fi fi
# Check if the snapshot already exist # Check if the snapshot already exist
if [ ! -e "$snapshot_path/snap$snap_number" ] if [ ! -e "$LXC_SNAPSHOTS/snap$snap_number" ]
then then
echo "snap$snap_number doesn't exist, its first creation can takes a little while." >&2 log_debug "snap$snap_number doesn't exist, its first creation can takes a little while." >&2
# Create the snapshot. # Create the snapshot.
sudo lxc-snapshot --name $lxc_name >> "$complete_log" 2>&1 sudo lxc-snapshot --name $LXC_NAME >> "$complete_log" 2>&1
# lxc always creates the first snapshot it can creates. # lxc always creates the first snapshot it can creates.
# So if snap1 doesn't exist and you try to create snap2, it will be named snap1. # So if snap1 doesn't exist and you try to create snap2, it will be named snap1.
if [ "$snap_number" == "2" ] && [ ! -e "$snapshot_path/snap2" ] if [ "$snap_number" == "2" ] && [ ! -e "$LXC_SNAPSHOTS/snap2" ]
then then
# Rename snap1 to snap2 # Rename snap1 to snap2
sudo mv "$snapshot_path/snap1" "$snapshot_path/snap2" sudo mv "$LXC_SNAPSHOTS/snap1" "$LXC_SNAPSHOTS/snap2"
fi fi
fi fi
# Update the snapshot with rsync to clone the current lxc state # Update the snapshot with rsync to clone the current lxc state
sudo rsync --acls --archive --delete --executability --itemize-changes --xattrs "/var/lib/lxc/$lxc_name/rootfs/" "$snapshot_path/snap$snap_number/rootfs/" > /dev/null 2>> "$complete_log" sudo rsync --acls --archive --delete --executability --itemize-changes --xattrs "$LXC_ROOTFS/" "$LXC_SNAPSHOTS/snap$snap_number/rootfs/" > /dev/null 2>> "$complete_log"
# Set this snapshot as the current snapshot # Set this snapshot as the current snapshot
current_snapshot=snap$snap_number current_snapshot=snap$snap_number
@ -112,23 +61,20 @@ create_temp_backup () {
LXC_START "true" >&2 LXC_START "true" >&2
} }
use_temp_snapshot () { LOAD_LXC_SNAPSHOT () {
# Use a temporary snapshot, if it already exists # Use a temporary snapshot, if it already exists
# $1 = Name of the snapshot to use # $1 = Name of the snapshot to use
current_snapshot=$1 current_snapshot=$1
start_timer start_timer
# Fix the missing hostname in the hosts file... # Fix the missing hostname in the hosts file...
echo "127.0.0.1 $lxc_name" | sudo tee --append "$snapshot_path/$current_snapshot/rootfs/etc/hosts" > /dev/null echo "127.0.0.1 $LXC_NAME" | sudo tee --append "$LXC_SNAPSHOTS/$current_snapshot/rootfs/etc/hosts" > /dev/null
# Restore this snapshot. # Restore this snapshot.
sudo rsync --acls --archive --delete --executability --itemize-changes --xattrs "$snapshot_path/$current_snapshot/rootfs/" "/var/lib/lxc/$lxc_name/rootfs/" > /dev/null 2>> "$complete_log" sudo rsync --acls --archive --delete --executability --itemize-changes --xattrs "$LXC_SNAPSHOTS/$current_snapshot/rootfs/" "$LXC_ROOTFS/" > /dev/null 2>> "$complete_log"
stop_timer 1 stop_timer 1
# Retrieve the app id in the log. To manage the app after
ynh_app_id=$(sudo tac "$yunohost_log" | grep --only-matching --max-count=1 "YNH_APP_INSTANCE_NAME=[^ ]*" | cut --delimiter='=' --fields=2)
# Fake the yunohost_result return code of the installation # Fake the yunohost_result return code of the installation
yunohost_result=0 yunohost_result=0
} }
@ -136,31 +82,31 @@ use_temp_snapshot () {
#================================================= #=================================================
is_lxc_running () { is_lxc_running () {
sudo lxc-info --name=$lxc_name | grep --quiet "RUNNING" sudo lxc-info --name=$LXC_NAME | grep --quiet "RUNNING"
} }
LXC_INIT () { LXC_INIT () {
# Clean previous remaining swap files # Clean previous remaining swap files
sudo swapoff /var/lib/lxc/$lxc_name/rootfs/swap_* 2>/dev/null sudo swapoff $LXC_ROOTFS/swap_* 2>/dev/null
sudo rm --force /var/lib/lxc/$lxc_name/rootfs/swap_* sudo rm --force $LXC_ROOTFS/swap_*
sudo swapoff /var/lib/lxcsnaps/$lxc_name/snap0/rootfs/swap_* 2>/dev/null sudo swapoff $LXC_SNAPSHOTS/snap0/rootfs/swap_* 2>/dev/null
sudo rm --force /var/lib/lxcsnaps/$lxc_name/snap0/rootfs/swap_* sudo rm --force $LXC_SNAPSHOTS/snap0/rootfs/swap_*
sudo swapoff /var/lib/lxcsnaps/$lxc_name/snap1/rootfs/swap_* 2>/dev/null sudo swapoff $LXC_SNAPSHOTS/snap1/rootfs/swap_* 2>/dev/null
sudo rm --force /var/lib/lxcsnaps/$lxc_name/snap1/rootfs/swap_* sudo rm --force $LXC_SNAPSHOTS/snap1/rootfs/swap_*
sudo swapoff /var/lib/lxcsnaps/$lxc_name/snap2/rootfs/swap_* 2>/dev/null sudo swapoff $LXC_SNAPSHOTS/snap2/rootfs/swap_* 2>/dev/null
sudo rm --force /var/lib/lxcsnaps/$lxc_name/snap2/rootfs/swap_* sudo rm --force $LXC_SNAPSHOTS/snap2/rootfs/swap_*
# Initialize LXC network # Initialize LXC network
# Activate the bridge # Activate the bridge
echo "Initialize network for LXC." echo "Initialize network for LXC."
sudo ifup $lxc_bridge --interfaces=/etc/network/interfaces.d/$lxc_bridge | tee --append "$complete_log" 2>&1 sudo ifup $LXC_BRIDGE --interfaces=/etc/network/interfaces.d/$LXC_BRIDGE | tee --append "$complete_log" 2>&1
# Activate iptables rules # Activate iptables rules
echo "Activate iptables rules." echo "Activate iptables rules."
sudo iptables --append FORWARD --in-interface $lxc_bridge --out-interface $main_iface --jump ACCEPT | tee --append "$complete_log" 2>&1 sudo iptables --append FORWARD --in-interface $LXC_BRIDGE --out-interface $MAIN_NETWORK_INTERFACE --jump ACCEPT | tee --append "$complete_log" 2>&1
sudo iptables --append FORWARD --in-interface $main_iface --out-interface $lxc_bridge --jump ACCEPT | tee --append "$complete_log" 2>&1 sudo iptables --append FORWARD --in-interface $MAIN_NETWORK_INTERFACE --out-interface $LXC_BRIDGE --jump ACCEPT | tee --append "$complete_log" 2>&1
sudo iptables --table nat --append POSTROUTING --source $ip_range.0/24 --jump MASQUERADE | tee --append "$complete_log" 2>&1 sudo iptables --table nat --append POSTROUTING --source $LXC_NETWORK.0/24 --jump MASQUERADE | tee --append "$complete_log" 2>&1
} }
LXC_START () { LXC_START () {
@ -174,14 +120,14 @@ LXC_START () {
while [ $i -lt $max_try ] while [ $i -lt $max_try ]
do do
i=$(( $i +1 )) i=$(( $i +1 ))
# Start the container and log the booting process in $script_dir/lxc_boot.log # Start the container and log the booting process in ./lxc_boot.log
# Try to start only if the container is not already started # Try to start only if the container is not already started
if ! is_lxc_running; then if ! is_lxc_running; then
debug "Start the LXC container" >> "$complete_log" log_debug "Start the LXC container" >> "$complete_log"
sudo lxc-start --name=$lxc_name --daemon --logfile "$script_dir/lxc_boot.log" | tee --append "$complete_log" 2>&1 sudo lxc-start --name=$LXC_NAME --daemon --logfile "./lxc_boot.log" | tee --append "$complete_log" 2>&1
local avoid_witness=0 local avoid_witness=0
else else
debug "A LXC container is already running" log_debug "A LXC container is already running"
local avoid_witness=1 local avoid_witness=1
fi fi
@ -189,9 +135,9 @@ LXC_START () {
local j=0 local j=0
for j in `seq 1 5` for j in `seq 1 5`
do do
debug "." >> "$complete_log" log_debug "." >> "$complete_log"
# Try to connect with ssh to check if the container is ready to work. # Try to connect with ssh to check if the container is ready to work.
if ssh $arg_ssh -o ConnectTimeout=10 $lxc_name "exit 0" > /dev/null 2>&1; then if ssh $arg_ssh -o ConnectTimeout=10 $LXC_NAME "exit 0" > /dev/null 2>&1; then
# Break the for loop if the container is ready. # Break the for loop if the container is ready.
break break
fi fi
@ -206,19 +152,19 @@ LXC_START () {
local failstart=0 local failstart=0
# Check if the container is running # Check if the container is running
if ! is_lxc_running; then if ! is_lxc_running; then
critical "The LXC container didn't start..." log_critical "The LXC container didn't start..."
failstart=1 failstart=1
if [ $i -ne $max_try ]; then if [ $i -ne $max_try ]; then
info "Rebooting the container..." log_info "Rebooting the container..."
fi fi
LXC_STOP LXC_STOP
# Try to ping security.debian.org to check the connectivity from the container # Try to ping security.debian.org to check the connectivity from the container
elif ! ssh $arg_ssh -o ConnectTimeout=60 $lxc_name "sudo ping -q -c 2 security.debian.org > /dev/null 2>&1; exit \$?" >> "$complete_log" 2>&1 elif ! ssh $arg_ssh -o ConnectTimeout=60 $LXC_NAME "sudo ping -q -c 2 security.debian.org > /dev/null 2>&1; exit \$?" >> "$complete_log" 2>&1
then then
critical "The container failed to connect to internet..." log_critical "The container failed to connect to internet..."
failstart=1 failstart=1
if [ $i -ne $max_try ]; then if [ $i -ne $max_try ]; then
info "Rebooting the container..." log_info "Rebooting the container..."
fi fi
LXC_STOP LXC_STOP
# Create files to check if the remove script does not remove them accidentally # Create files to check if the remove script does not remove them accidentally
@ -236,55 +182,55 @@ LXC_START () {
# Send an email only if it's a CI environment # Send an email only if it's a CI environment
if [ $type_exec_env -ne 0 ] if [ $type_exec_env -ne 0 ]
then then
ci_path=$(grep "CI_URL=" "$script_dir/../config" | cut -d= -f2) ci_path=$(grep "CI_URL=" "./../config" | cut -d= -f2)
local subject="[YunoHost] Container in trouble on $ci_path." local subject="[YunoHost] Container in trouble on $ci_path."
local message="The container failed to start $max_try times on $ci_path. local message="The container failed to start $max_try times on $ci_path.
$lxc_check_result $lxc_check_result
Please have a look to the log of lxc_check: Please have a look to the log of lxc_check:
$(cat "$script_dir/lxc_check.log")" $(cat "./lxc_check.log")"
if [ $lxc_check -eq 2 ]; then if [ $lxc_check -eq 2 ]; then
# Add the log of lxc_build # Add the log of lxc_build
message="$message message="$message
Here the log of lxc_build: Here the log of lxc_build:
$(cat "$script_dir/sub_scripts/Build_lxc.log")" $(cat "./sub_scripts/Build_lxc.log")"
fi fi
dest=$(grep 'dest=' "$script_dir/../config" | cut -d= -f2) dest=$(grep 'dest=' "./../config" | cut -d= -f2)
mail -s "$subject" "$dest" <<< "$message" mail -s "$subject" "$dest" <<< "$message"
fi fi
} }
critical "The container failed to start $max_try times..." log_critical "The container failed to start $max_try times..."
info "Boot log:\n" log_info "Boot log:\n"
cat "$script_dir/lxc_boot.log" | tee --append "$complete_log" cat "./lxc_boot.log" | tee --append "$complete_log"
info "lxc_check will try to fix the container..." log_info "lxc_check will try to fix the container..."
$script_dir/sub_scripts/lxc_check.sh --no-lock | tee "$script_dir/lxc_check.log" ./sub_scripts/lxc_check.sh --no-lock | tee "./lxc_check.log"
# PIPESTATUS is an array with the exit code of each command followed by a pipe # PIPESTATUS is an array with the exit code of each command followed by a pipe
local lxc_check=${PIPESTATUS[0]} local lxc_check=${PIPESTATUS[0]}
LXC_INIT LXC_INIT
if [ $lxc_check -eq 0 ]; then if [ $lxc_check -eq 0 ]; then
local lxc_check_result="The container seems to be ok, according to lxc_check." local lxc_check_result="The container seems to be ok, according to lxc_check."
success "$lxc_check_result" log_success "$lxc_check_result"
send_email send_email
i=0 i=0
elif [ $lxc_check -eq 1 ]; then elif [ $lxc_check -eq 1 ]; then
local lxc_check_result="An error has happened with the host. Please check the configuration." local lxc_check_result="An error has happened with the host. Please check the configuration."
critical "$lxc_check_result" log_critical "$lxc_check_result"
send_email send_email
stop_timer 1 stop_timer 1
return 1 return 1
elif [ $lxc_check -eq 2 ]; then elif [ $lxc_check -eq 2 ]; then
local lxc_check_result="The container is broken, it will be rebuilt." local lxc_check_result="The container is broken, it will be rebuilt."
critical "$lxc_check_result" log_critical "$lxc_check_result"
$script_dir/sub_scripts/lxc_build.sh ./sub_scripts/lxc_build.sh
LXC_INIT LXC_INIT
send_email send_email
i=0 i=0
elif [ $lxc_check -eq 3 ]; then elif [ $lxc_check -eq 3 ]; then
local lxc_check_result="The container has been fixed by lxc_check." local lxc_check_result="The container has been fixed by lxc_check."
success "$lxc_check_result" log_success "$lxc_check_result"
send_email send_email
i=0 i=0
fi fi
@ -294,10 +240,10 @@ LXC_START () {
start_timer start_timer
# Copy the package into the container. # Copy the package into the container.
rsync -rq --delete "$package_path" "$lxc_name": >> "$complete_log" 2>&1 rsync -rq --delete "$package_path" "$LXC_NAME": >> "$complete_log" 2>&1
# Execute the command given in argument in the container and log its results. # Execute the command given in argument in the container and log its results.
ssh $arg_ssh $lxc_name "$1; exit $?" | tee -a "$complete_log" ssh $arg_ssh $LXC_NAME "$1; exit $?" | tee -a "$complete_log"
# Store the return code of the command # Store the return code of the command
local returncode=${PIPESTATUS[0]} local returncode=${PIPESTATUS[0]}
@ -313,68 +259,54 @@ LXC_STOP () {
start_timer start_timer
# Stop the LXC container # Stop the LXC container
if is_lxc_running; then if is_lxc_running; then
debug "Stop the LXC container" log_debug "Stop the LXC container"
sudo lxc-stop --name=$lxc_name | tee --append "$complete_log" 2>&1 sudo lxc-stop --name=$LXC_NAME | tee --append "$complete_log" 2>&1
fi fi
# Fix the missing hostname in the hosts file # Fix the missing hostname in the hosts file
# If the hostname is missing in /etc/hosts inside the snapshot # If the hostname is missing in /etc/hosts inside the snapshot
if ! sudo grep --quiet "$lxc_name" "$snapshot_path/$current_snapshot/rootfs/etc/hosts" if ! sudo grep --quiet "$LXC_NAME" "$LXC_SNAPSHOTS/$current_snapshot/rootfs/etc/hosts"
then then
# If the hostname was replaced by name of the snapshot, fix it # If the hostname was replaced by name of the snapshot, fix it
if sudo grep --quiet "$current_snapshot" "$snapshot_path/$current_snapshot/rootfs/etc/hosts" if sudo grep --quiet "$current_snapshot" "$LXC_SNAPSHOTS/$current_snapshot/rootfs/etc/hosts"
then then
# Replace snapX by the real hostname # Replace snapX by the real hostname
sudo sed --in-place "s/$current_snapshot/$lxc_name/" "$snapshot_path/$current_snapshot/rootfs/etc/hosts" sudo sed --in-place "s/$current_snapshot/$LXC_NAME/" "$LXC_SNAPSHOTS/$current_snapshot/rootfs/etc/hosts"
else else
# Otherwise, simply add the hostname # Otherwise, simply add the hostname
echo "127.0.0.1 $lxc_name" | sudo tee --append "$snapshot_path/$current_snapshot/rootfs/etc/hosts" > /dev/null echo "127.0.0.1 $LXC_NAME" | sudo tee --append "$LXC_SNAPSHOTS/$current_snapshot/rootfs/etc/hosts" > /dev/null
fi fi
fi fi
# Restore the snapshot. # Restore the snapshot.
debug "Restore the previous snapshot." log_debug "Restore the previous snapshot."
sudo rsync --acls --archive --delete --executability --itemize-changes --xattrs "$snapshot_path/$current_snapshot/rootfs/" "/var/lib/lxc/$lxc_name/rootfs/" > /dev/null 2>> "$complete_log" sudo rsync --acls --archive --delete --executability --itemize-changes --xattrs "$LXC_SNAPSHOTS/$current_snapshot/rootfs/" "$LXC_ROOTFS/" > /dev/null 2>> "$complete_log"
stop_timer 1 stop_timer 1
} }
LXC_TURNOFF () { LXC_TURNOFF () {
# Disable LXC network # Disable LXC network
echo "Disable iptables rules." log_debug "Disable iptables rules."
if sudo iptables --check FORWARD --in-interface $lxc_bridge --out-interface $main_iface --jump ACCEPT 2> /dev/null if sudo iptables --check FORWARD --in-interface $LXC_BRIDGE --out-interface $MAIN_NETWORK_INTERFACE --jump ACCEPT 2> /dev/null
then then
sudo iptables --delete FORWARD --in-interface $lxc_bridge --out-interface $main_iface --jump ACCEPT >> "$complete_log" 2>&1 sudo iptables --delete FORWARD --in-interface $LXC_BRIDGE --out-interface $MAIN_NETWORK_INTERFACE --jump ACCEPT >> "$complete_log" 2>&1
fi fi
if sudo iptables --check FORWARD --in-interface $main_iface --out-interface $lxc_bridge --jump ACCEPT 2> /dev/null if sudo iptables --check FORWARD --in-interface $MAIN_NETWORK_INTERFACE --out-interface $LXC_BRIDGE --jump ACCEPT 2> /dev/null
then then
sudo iptables --delete FORWARD --in-interface $main_iface --out-interface $lxc_bridge --jump ACCEPT | tee --append "$complete_log" 2>&1 sudo iptables --delete FORWARD --in-interface $MAIN_NETWORK_INTERFACE --out-interface $LXC_BRIDGE --jump ACCEPT | tee --append "$complete_log" 2>&1
fi fi
if sudo iptables --table nat --check POSTROUTING --source $ip_range.0/24 --jump MASQUERADE 2> /dev/null if sudo iptables --table nat --check POSTROUTING --source $LXC_NETWORK.0/24 --jump MASQUERADE 2> /dev/null
then then
sudo iptables --table nat --delete POSTROUTING --source $ip_range.0/24 --jump MASQUERADE | tee --append "$complete_log" 2>&1 sudo iptables --table nat --delete POSTROUTING --source $LXC_NETWORK.0/24 --jump MASQUERADE | tee --append "$complete_log" 2>&1
fi fi
echo "Disable the network bridge." log_debug "Disable the network bridge."
if sudo ifquery $lxc_bridge --state > /dev/null if sudo ifquery $LXC_BRIDGE --state > /dev/null
then then
sudo ifdown --force $lxc_bridge | tee --append "$complete_log" 2>&1 sudo ifdown --force $LXC_BRIDGE | tee --append "$complete_log" 2>&1
fi fi
# Set snap0 as the current snapshot # Set snap0 as the current snapshot
current_snapshot=snap0 current_snapshot=snap0
} }
LXC_CONNECT_INFO () {
# Print access information
echo "> To access the container:"
echo "To execute one command:"
echo -e "\e[1msudo lxc-attach -n $lxc_name -- command\e[0m"
echo "To establish a ssh connection:"
if [ $(cat "$script_dir/sub_scripts/setup_user") = "root" ]; then
echo -ne "\e[1msudo "
fi
echo -e "\e[1mssh $arg_ssh $lxc_name\e[0m"
}

View file

@ -8,182 +8,119 @@ then
exit 1 exit 1
fi fi
# Récupère le dossier du script # Load configuration
if [ "${0:0:1}" == "/" ]; then script_dir="$(dirname "$0")"; else script_dir="$(echo $PWD/$(dirname "$0" | cut -d '.' -f2) | sed 's@/$@@')"; fi dnsforce=1
pcheck_config="$script_dir/../config" cd $(dirname $(realpath $0) | sed 's@/sub_scripts$@@g')
# Tente de lire les informations depuis le fichier de config si il existe source "./sub_scripts/common.sh"
if [ -e "$pcheck_config" ]
then
PLAGE_IP=$(cat "$pcheck_config" | grep PLAGE_IP= | cut -d '=' -f2)
DOMAIN=$(cat "$pcheck_config" | grep DOMAIN= | cut -d '=' -f2)
YUNO_PWD=$(cat "$pcheck_config" | grep YUNO_PWD= | cut -d '=' -f2)
LXC_NAME=$(cat "$pcheck_config" | grep LXC_NAME= | cut -d '=' -f2)
LXC_BRIDGE=$(cat "$pcheck_config" | grep LXC_BRIDGE= | cut -d '=' -f2)
dns=$(cat "$pcheck_config" | grep dns= | cut -d '=' -f2)
dnsforce=$(cat "$pcheck_config" | grep dnsforce= | cut -d '=' -f2)
main_iface=$(cat "$pcheck_config" | grep iface= | cut -d '=' -f2)
DISTRIB=$(cat "$pcheck_config" | grep DISTRIB= | cut -d '=' -f2)
branch=$(cat "$pcheck_config" | grep BRANCH= | cut -d '=' -f2)
fi
LOG_BUILD_LXC="$script_dir/Build_lxc.log" LXC_BUILD()
# Utilise des valeurs par défaut si les variables sont vides. {
test -n "$PLAGE_IP" || PLAGE_IP=10.1.4 # Met en place le lock de Package check, le temps de l'installation
test -n "$DOMAIN" || DOMAIN=domain.tld touch "$lock_file"
test -n "$YUNO_PWD" || YUNO_PWD=admin echo $(whoami) > "./.setup_user"
test -n "$LXC_NAME" || LXC_NAME=pchecker_lxc
test -n "$LXC_BRIDGE" || LXC_BRIDGE=lxc-pchecker
test -n "$dnsforce" || dnsforce=1
test -n "$DISTRIB" || DISTRIB=buster
test -n "$branch" || branch=""
ARG_SSH="-t"
# Tente de définir l'interface réseau principale log_title "Installing dependencies..."
if [ -z $main_iface ] # Si main_iface est vide, tente de le trouver.
then
# main_iface=$(sudo route | grep default.*0.0.0.0 -m1 | awk '{print $8;}') # Prend l'interface réseau défini par default
main_iface=$(sudo ip route | grep default | awk '{print $5;}') # Prend l'interface réseau défini par default
if [ -z $main_iface ]; then
echo -e "\e[91mImpossible de déterminer le nom de l'interface réseau de l'hôte.\e[0m"
exit 1
fi
fi
if [ -z $dns ] # Si l'adresse du dns est vide, tente de le déterminer à partir de la passerelle par défaut. DEPENDENCIES="lxc lxctl git curl lynx jq python3-pip debootstrap rsync bridge-utils"
then sudo apt-get update
# dns=$(sudo route -n | grep ^0.0.0.0.*$main_iface | awk '{print $2;}') sudo apt-get install -y $DEPENDENCIES
dns=$(sudo ip route | grep default | awk '{print $3;}')
if [ -z $dns ]; then
echo -e "\e[91mImpossible de déterminer l'adresse de la passerelle.\e[0m"
exit 1
fi
fi
touch "$script_dir/../pcheck.lock" # Met en place le lock de Package check, le temps de l'installation # Créer le dossier lxcsnaps, pour s'assurer que lxc utilisera ce dossier, même avec lxc 2.
sudo mkdir -p /var/lib/lxcsnaps
# Check user
echo $(whoami) > "$script_dir/setup_user"
# Enregistre le nom de l'interface réseau de l'hôte dans un fichier de config
echo -e "# Interface réseau principale de l'hôte\niface=$main_iface\n" > "$pcheck_config"
echo -e "# Adresse du dns\ndns=$dns\n" >> "$pcheck_config"
echo -e "# Forçage du dns\ndnsforce=$dnsforce\n" >> "$pcheck_config"
# Enregistre les infos dans le fichier de config.
echo -e "# Plage IP du conteneur\nPLAGE_IP=$PLAGE_IP\n" >> "$pcheck_config"
echo -e "# Domaine de test\nDOMAIN=$DOMAIN\n" >> "$pcheck_config"
echo -e "# Mot de passe\nYUNO_PWD=$YUNO_PWD\n" >> "$pcheck_config"
echo -e "# Nom du conteneur\nLXC_NAME=$LXC_NAME\n" >> "$pcheck_config"
echo -e "# Nom du bridge\nLXC_BRIDGE=$LXC_BRIDGE\n" >> "$pcheck_config"
echo -e "# Distribution debian\nDISTRIB=$DISTRIB" >> "$pcheck_config"
echo -e "# Branche à utiliser pour le script d'install de cette distribution (si non standard)\nBRANCH=$branch\n" >> "$pcheck_config"
echo -e "\e[1m> Update et install lxc lxctl\e[0m" | tee -a "$LOG_BUILD_LXC"
sudo apt-get update >> "$LOG_BUILD_LXC" 2>&1
sudo apt-get install -y lxc lxctl >> "$LOG_BUILD_LXC" 2>&1
echo -e "\e[1m> Install git, curl and lynx\e[0m" | tee -a "$LOG_BUILD_LXC"
sudo apt-get install -y git curl lynx jq python3-pip boxes >> "$LOG_BUILD_LXC" 2>&1
# For those who have disabled APT::Install-Recommends we need to manually install the following packages.
sudo apt-get install -y debootstrap rsync bridge-utils >> "$LOG_BUILD_LXC" 2>&1
sudo mkdir -p /var/lib/lxcsnaps # Créer le dossier lxcsnaps, pour s'assurer que lxc utilisera ce dossier, même avec lxc 2.
# Si le conteneur existe déjà
if sudo lxc-info -n $LXC_NAME > /dev/null 2>&1 if sudo lxc-info -n $LXC_NAME > /dev/null 2>&1
then # Si le conteneur existe déjà then
echo -e "\e[1m> Suppression du conteneur existant.\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Suppression du conteneur existant."
"$script_dir/lxc_remove.sh" quiet | tee -a "$LOG_BUILD_LXC" ./sub_scripts/lxc_remove.sh
fi fi
echo -e "\e[1m> Création d'une machine debian $DISTRIB minimaliste.\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Création d'une machine debian $DISTRIB minimaliste."
sudo lxc-create -n $LXC_NAME -t download -- -d debian -r $DISTRIB -a $(dpkg --print-architecture) >> "$LOG_BUILD_LXC" 2>&1 sudo lxc-create -n $LXC_NAME -t download -- -d debian -r $DISTRIB -a $(dpkg --print-architecture)
echo -e "\e[1m> Autoriser l'ip forwarding, pour router vers la machine virtuelle.\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Autoriser l'ip forwarding, pour router vers la machine virtuelle."
echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/lxc_pchecker.conf >> "$LOG_BUILD_LXC" 2>&1 echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/lxc_pchecker.conf
sudo sysctl -p /etc/sysctl.d/lxc_pchecker.conf >> "$LOG_BUILD_LXC" 2>&1 sudo sysctl -p /etc/sysctl.d/lxc_pchecker.conf
echo -e "\e[1m> Ajoute un brige réseau pour la machine virtualisée\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Ajoute un brige réseau pour la machine virtualisée"
echo | sudo tee /etc/network/interfaces.d/$LXC_BRIDGE <<EOF >> "$LOG_BUILD_LXC" 2>&1 echo | sudo tee /etc/network/interfaces.d/$LXC_BRIDGE <<EOF
auto $LXC_BRIDGE auto $LXC_BRIDGE
iface $LXC_BRIDGE inet static iface $LXC_BRIDGE inet static
address $PLAGE_IP.1/24 address $LXC_NETWORK.1/24
bridge_ports none bridge_ports none
bridge_fd 0 bridge_fd 0
bridge_maxwait 0 bridge_maxwait 0
EOF EOF
echo -e "\e[1m> Active le bridge réseau\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Active le bridge réseau"
sudo ifup $LXC_BRIDGE --interfaces=/etc/network/interfaces.d/$LXC_BRIDGE >> "$LOG_BUILD_LXC" 2>&1 sudo ifup $LXC_BRIDGE --interfaces=/etc/network/interfaces.d/$LXC_BRIDGE
echo -e "\e[1m> Configuration réseau du conteneur\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Configuration réseau du conteneur"
if [ $(lsb_release -sc) != buster ] if [ $(lsb_release -sc) != buster ]
then then
sudo sed -i "s/^lxc.network.type = empty$/lxc.network.type = veth\nlxc.network.flags = up\nlxc.network.link = $LXC_BRIDGE\nlxc.network.name = eth0\nlxc.network.hwaddr = 00:FF:AA:00:00:01/" /var/lib/lxc/$LXC_NAME/config >> "$LOG_BUILD_LXC" 2>&1 sudo sed -i "s/^lxc.network.type = empty$/lxc.network.type = veth\nlxc.network.flags = up\nlxc.network.link = $LXC_BRIDGE\nlxc.network.name = eth0\nlxc.network.hwaddr = 00:FF:AA:00:00:01/" /var/lib/lxc/$LXC_NAME/config
else else
echo -e "lxc.net.0.type = veth\nlxc.net.0.flags = up\nlxc.net.0.link = $LXC_BRIDGE\nlxc.net.0.name = eth0\nlxc.net.0.hwaddr = 00:FF:AA:00:00:01" | sudo tee -a /var/lib/lxc/$LXC_NAME/config >> "$LOG_BUILD_LXC" 2>&1 echo -e "lxc.net.0.type = veth\nlxc.net.0.flags = up\nlxc.net.0.link = $LXC_BRIDGE\nlxc.net.0.name = eth0\nlxc.net.0.hwaddr = 00:FF:AA:00:00:01" | sudo tee -a /var/lib/lxc/$LXC_NAME/config
fi fi
echo -e "\e[1m> Configuration réseau de la machine virtualisée\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Configuration réseau de la machine virtualisée"
sudo sed -i "s@iface eth0 inet dhcp@iface eth0 inet static\n\taddress $PLAGE_IP.2/24\n\tgateway $PLAGE_IP.1@" /var/lib/lxc/$LXC_NAME/rootfs/etc/network/interfaces >> "$LOG_BUILD_LXC" 2>&1 sudo sed -i "s@iface eth0 inet dhcp@iface eth0 inet static\n\taddress $LXC_NETWORK.2/24\n\tgateway $LXC_NETWORK.1@" $LXC_ROOTFS/etc/network/interfaces
echo -e "\e[1m> Configure le parefeu\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Configure le parefeu"
sudo iptables -A FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT >> "$LOG_BUILD_LXC" 2>&1 sudo iptables -A FORWARD -i $LXC_BRIDGE -o $MAIN_NETWORK_INTERFACE -j ACCEPT
sudo iptables -A FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT >> "$LOG_BUILD_LXC" 2>&1 sudo iptables -A FORWARD -i $MAIN_NETWORK_INTERFACE -o $LXC_BRIDGE -j ACCEPT
sudo iptables -t nat -A POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE >> "$LOG_BUILD_LXC" 2>&1 sudo iptables -t nat -A POSTROUTING -s $LXC_NETWORK.0/24 -j MASQUERADE
echo -e "\e[1m> Vérification du contenu du resolv.conf\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Vérification du contenu du resolv.conf"
sudo cp -a /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf.origin sudo cp -a $LXC_ROOTFS/etc/resolv.conf $LXC_ROOTFS/etc/resolv.conf.origin
if ! sudo cat /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf | grep -q nameserver; then if ! sudo cat $LXC_ROOTFS/etc/resolv.conf | grep -q nameserver; then
dnsforce=1 # Le resolv.conf est vide, on force l'ajout d'un dns. dnsforce=1 # Le resolv.conf est vide, on force l'ajout d'un dns.
sed -i "s/dnsforce=.*/dnsforce=$dnsforce/" "$pcheck_config"
fi fi
if [ $dnsforce -eq 1 ]; then # Force la réécriture du resolv.conf if [ $dnsforce -eq 1 ]; then # Force la réécriture du resolv.conf
echo "nameserver $dns" | sudo tee /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf echo "nameserver $DNS_RESOLVER" | sudo tee $LXC_ROOTFS/etc/resolv.conf
fi fi
# Fix an issue with apparmor when the container start. # Fix an issue with apparmor when the container start.
if [ $(lsb_release -sc) != buster ] if [ $(lsb_release -sc) != buster ]
then then
echo -e "\n# Fix apparmor issues\nlxc.aa_profile = unconfined" | sudo tee -a /var/lib/lxc/$LXC_NAME/config >> "$LOG_BUILD_LXC" 2>&1 echo -e "\n# Fix apparmor issues\nlxc.aa_profile = unconfined" | sudo tee -a /var/lib/lxc/$LXC_NAME/config
else else
echo -e "\n# Fix apparmor issues\nlxc.apparmor.profile = unconfined" | sudo tee -a /var/lib/lxc/$LXC_NAME/config >> "$LOG_BUILD_LXC" 2>&1 echo -e "\n# Fix apparmor issues\nlxc.apparmor.profile = unconfined" | sudo tee -a /var/lib/lxc/$LXC_NAME/config
fi fi
echo -e "\e[1m> Démarrage de la machine\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Démarrage de la machine"
sudo lxc-start -n $LXC_NAME -d --logfile "$script_dir/lxc_boot.log" >> "$LOG_BUILD_LXC" 2>&1 sudo lxc-start -n $LXC_NAME -d --logfile "./lxc_boot.log"
sleep 3 sleep 3
sudo lxc-ls -f >> "$LOG_BUILD_LXC" 2>&1 sudo lxc-ls -f
echo -e "\e[1m> Test la configuration dns\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Test la configuration dns"
broken_dns=0 broken_dns=0
while ! sudo lxc-attach -n $LXC_NAME -- getent hosts debian.org > /dev/null 2>&1 while ! RUN_INSIDE_LXC getent hosts debian.org
do do
echo -e "\e[1m>>> The dns isn't working (Current dns = $(sudo cat /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf | grep nameserver | awk '{print $2}'))" log_info "The dns isn't working (Current dns = $(sudo cat $LXC_ROOTFS/etc/resolv.conf | grep nameserver | awk '{print $2}'))"
if [ $broken_dns -eq 2 ] if [ $broken_dns -eq 2 ]
then then
echo -e "\e[1m>>>The dns is still broken, use FDN dns\e[0m" | tee -a "$LOG_BUILD_LXC" log_info "The dns is still broken, use FDN dns"
echo "nameserver 80.67.169.12" | sudo tee /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf echo "nameserver 80.67.169.12" | sudo tee $LXC_ROOTFS/etc/resolv.conf
dnsforce=0 dnsforce=0
((broken_dns++)) ((broken_dns++))
elif [ $dnsforce -eq 0 ] elif [ $dnsforce -eq 0 ]
then then
echo -e "\e[1m>>>Force to use the dns from the config file\e[0m" | tee -a "$LOG_BUILD_LXC" log_info "Force to use the dns from the config file"
echo "nameserver $dns" | sudo tee /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf echo "nameserver $DNS_RESOLVER" | sudo tee $LXC_ROOTFS/etc/resolv.conf
new_dns="$dns" new_dns="$DNS_RESOLVER"
dnsforce=1 dnsforce=1
((broken_dns++)) ((broken_dns++))
else else
echo -e "\e[1m>>>Force to use the default dns\e[0m" | tee -a "$LOG_BUILD_LXC" log_info "Force to use the default dns"
sudo cp -a /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf.origin /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf sudo cp -a $LXC_ROOTFS/etc/resolv.conf.origin $LXC_ROOTFS/etc/resolv.conf
new_dns="$(sudo cat /var/lib/lxc/$LXC_NAME/rootfs/etc/resolv.conf | grep nameserver | awk '{print $2}')" new_dns="$(sudo cat $LXC_ROOTFS/etc/resolv.conf | grep nameserver | awk '{print $2}')"
dnsforce=0 dnsforce=0
((broken_dns++)) ((broken_dns++))
fi fi
echo -e "\e[1m>>> Try to use the dns address $new_dns\e[0m" | tee -a "$LOG_BUILD_LXC" log_info "Try to use the dns address $new_dns"
# Change the value of dnsforce into the config file
sed -i "s/dnsforce=.*/dnsforce=$dnsforce/" "$pcheck_config"
if [ $broken_dns -eq 3 ]; then if [ $broken_dns -eq 3 ]; then
# Break the loop if all the possibilities have been tried. # Break the loop if all the possibilities have been tried.
@ -191,103 +128,92 @@ do
fi fi
done done
echo -e "\e[1m> Update et install aptitude sudo git\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Update et install aptitude sudo git"
sudo lxc-attach -n $LXC_NAME -- apt-get update RUN_INSIDE_LXC apt-get update
sudo lxc-attach -n $LXC_NAME -- apt-get install -y aptitude sudo git ssh openssh-server RUN_INSIDE_LXC apt-get install -y sudo git ssh openssh-server
echo -e "\e[1m> Installation des paquets standard et ssh-server\e[0m" | tee -a "$LOG_BUILD_LXC"
sudo lxc-attach -n $LXC_NAME -- aptitude install -y ~pstandard ~prequired ~pimportant
echo -e "\e[1m> Renseigne /etc/hosts sur l'invité\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Renseigne /etc/hosts sur l'invité"
echo "127.0.0.1 $LXC_NAME" | sudo tee -a /var/lib/lxc/$LXC_NAME/rootfs/etc/hosts >> "$LOG_BUILD_LXC" 2>&1 echo "127.0.0.1 $LXC_NAME" | sudo tee -a $LXC_ROOTFS/etc/hosts
echo -e "\e[1m> Ajoute l'user pchecker\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Ajoute l'user pchecker"
sudo lxc-attach -n $LXC_NAME -- useradd -m -p pchecker pchecker >> "$LOG_BUILD_LXC" 2>&1 RUN_INSIDE_LXC useradd -m -p pchecker pchecker
echo -e "\e[1m> Autorise pchecker à utiliser sudo sans mot de passe\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Autorise pchecker à utiliser sudo sans mot de passe"
echo "pchecker ALL=(ALL:ALL) NOPASSWD: ALL" | sudo tee -a /var/lib/lxc/$LXC_NAME/rootfs/etc/sudoers >> "$LOG_BUILD_LXC" 2>&1 echo "pchecker ALL=(ALL:ALL) NOPASSWD: ALL" | sudo tee -a $LXC_ROOTFS/etc/sudoers
echo -e "\e[1m> Mise en place de la connexion ssh vers l'invité.\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Mise en place de la connexion ssh vers l'invité."
if [ -e $HOME/.ssh/$LXC_NAME ]; then if [ -e $HOME/.ssh/$LXC_NAME ]; then
rm -f $HOME/.ssh/$LXC_NAME $HOME/.ssh/$LXC_NAME.pub rm -f $HOME/.ssh/$LXC_NAME $HOME/.ssh/$LXC_NAME.pub
ssh-keygen -f $HOME/.ssh/known_hosts -R $PLAGE_IP.2 ssh-keygen -f $HOME/.ssh/known_hosts -R $LXC_NETWORK.2
fi fi
ssh-keygen -t rsa -f $HOME/.ssh/$LXC_NAME -P '' >> "$LOG_BUILD_LXC" 2>&1 ssh-keygen -t rsa -f $HOME/.ssh/$LXC_NAME -P ''
sudo mkdir /var/lib/lxc/$LXC_NAME/rootfs/home/pchecker/.ssh >> "$LOG_BUILD_LXC" 2>&1 sudo mkdir $LXC_ROOTFS/home/pchecker/.ssh
sudo cp $HOME/.ssh/$LXC_NAME.pub /var/lib/lxc/$LXC_NAME/rootfs/home/pchecker/.ssh/authorized_keys >> "$LOG_BUILD_LXC" 2>&1 sudo cp $HOME/.ssh/$LXC_NAME.pub $LXC_ROOTFS/home/pchecker/.ssh/authorized_keys
sudo lxc-attach -n $LXC_NAME -- chown pchecker: -R /home/pchecker/.ssh >> "$LOG_BUILD_LXC" 2>&1 RUN_INSIDE_LXC chown pchecker: -R /home/pchecker/.ssh
echo | tee -a $HOME/.ssh/config <<EOF >> "$LOG_BUILD_LXC" 2>&1 echo | tee -a $HOME/.ssh/config <<EOF
# ssh $LXC_NAME # ssh $LXC_NAME
Host $LXC_NAME Host $LXC_NAME
Hostname $PLAGE_IP.2 Hostname $LXC_NETWORK.2
User pchecker User pchecker
IdentityFile $HOME/.ssh/$LXC_NAME IdentityFile $HOME/.ssh/$LXC_NAME
EOF EOF
ssh-keyscan -H $PLAGE_IP.2 >> ~/.ssh/known_hosts ssh-keyscan -H $LXC_NETWORK.2 >> ~/.ssh/known_hosts
ssh $ARG_SSH $LXC_NAME "exit 0" # Initie une premier connexion SSH pour valider la clé. # Initie une premier connexion SSH pour valider la clé.
if [ "$?" -ne 0 ]; then # Si l'utilisateur tarde trop, la connexion sera refusée... ??? RUN_THROUGH_SSH "exit 0"
ssh $ARG_SSH $LXC_NAME "exit 0" # Initie une premier connexion SSH pour valider la clé. # Si l'utilisateur tarde trop, la connexion sera refusée... ???
fi [ "$?" -ne 0 ] && RUN_THROUGH_SSH "exit 0"
# Fix ssh common issues with stretch "No supported key exchange algorithms" [ -n "$YNH_INSTALL_SCRIPT_BRANCH" ] && YNH_INSTALL_SCRIPT_BRANCH="--branch $YNH_INSTALL_SCRIPT_BRANCH"
sudo lxc-attach -n $LXC_NAME -- dpkg-reconfigure openssh-server >> "$LOG_BUILD_LXC" 2>&1
# Fix locales issue RUN_THROUGH_SSH git clone https://github.com/YunoHost/install_script $YNH_INSTALL_SCRIPT_BRANCH /tmp/install_script
sudo lxc-attach -n $LXC_NAME -- locale-gen en_US.UTF-8 >> "$LOG_BUILD_LXC" 2>&1 log_title "Installation de Yunohost..."
sudo lxc-attach -n $LXC_NAME -- localedef -i en_US -f UTF-8 en_US.UTF-8 >> "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH bash /tmp/install_script/install_yunohost -a
log_title "Disable apt-daily to prevent it from messing with apt/dpkg lock"
if [ -n "$branch" ]; then RUN_THROUGH_SSH systemctl -q stop apt-daily.timer
branch="--branch $branch" RUN_THROUGH_SSH systemctl -q stop apt-daily-upgrade.timer
fi RUN_THROUGH_SSH systemctl -q stop apt-daily.service
RUN_THROUGH_SSH systemctl -q stop apt-daily-upgrade.service
ssh $ARG_SSH $LXC_NAME "git clone https://github.com/YunoHost/install_script $branch /tmp/install_script" >> "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH systemctl -q disable apt-daily.timer
echo -e "\e[1m> Installation de Yunohost...\e[0m" | tee -a "$LOG_BUILD_LXC" RUN_THROUGH_SSH systemctl -q disable apt-daily-upgrade.timer
ssh $ARG_SSH $LXC_NAME "cd /tmp/install_script; sudo ./install_yunohost -a" | tee -a "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH systemctl -q disable apt-daily.service
echo -e "\e[1m> Disable apt-daily to prevent it from messing with apt/dpkg lock\e[0m" | tee -a "$LOG_BUILD_LXC" RUN_THROUGH_SSH systemctl -q disable apt-daily-upgrade.service
ssh $ARG_SSH $LXC_NAME "systemctl -q stop apt-daily.timer" | tee -a "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH rm -f /etc/cron.daily/apt-compat
ssh $ARG_SSH $LXC_NAME "systemctl -q stop apt-daily-upgrade.timer" | tee -a "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH cp /bin/true /usr/lib/apt/apt.systemd.daily
ssh $ARG_SSH $LXC_NAME "systemctl -q stop apt-daily.service" | tee -a "$LOG_BUILD_LXC" 2>&1
ssh $ARG_SSH $LXC_NAME "systemctl -q stop apt-daily-upgrade.service" | tee -a "$LOG_BUILD_LXC" 2>&1
ssh $ARG_SSH $LXC_NAME "systemctl -q disable apt-daily.timer" | tee -a "$LOG_BUILD_LXC" 2>&1
ssh $ARG_SSH $LXC_NAME "systemctl -q disable apt-daily-upgrade.timer" | tee -a "$LOG_BUILD_LXC" 2>&1
ssh $ARG_SSH $LXC_NAME "systemctl -q disable apt-daily.service" | tee -a "$LOG_BUILD_LXC" 2>&1
ssh $ARG_SSH $LXC_NAME "systemctl -q disable apt-daily-upgrade.service" | tee -a "$LOG_BUILD_LXC" 2>&1
ssh $ARG_SSH $LXC_NAME "rm -f /etc/cron.daily/apt-compat" | tee -a "$LOG_BUILD_LXC" 2>&1
ssh $ARG_SSH $LXC_NAME "cp /bin/true /usr/lib/apt/apt.systemd.daily" | tee -a "$LOG_BUILD_LXC" 2>&1
echo -e "\e[1m> Post install Yunohost\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Post install Yunohost"
ssh $ARG_SSH $LXC_NAME "sudo yunohost tools postinstall --domain $DOMAIN --password $YUNO_PWD --force-password" | tee -a "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH yunohost tools postinstall --domain $DOMAIN --password $YUNO_PWD --force-password
# Disable password strength check # Disable password strength check
ssh $ARG_SSH $LXC_NAME "sudo yunohost settings set security.password.admin.strength -v -1" | tee -a "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH yunohost settings set security.password.admin.strength -v -1
ssh $ARG_SSH $LXC_NAME "sudo yunohost settings set security.password.user.strength -v -1" | tee -a "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH yunohost settings set security.password.user.strength -v -1
USER_TEST=$(cat "$(dirname "$script_dir")/package_check.sh" | grep test_user= | cut -d '=' -f2)
SOUS_DOMAIN="sous.$DOMAIN"
# echo "Le mot de passe Yunohost est \'$YUNO_PWD\'" # echo "Le mot de passe Yunohost est \'$YUNO_PWD\'"
echo -e "\e[1m> Ajout du sous domaine de test\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Ajout du sous domaine de test"
ssh $ARG_SSH $LXC_NAME "sudo yunohost domain add \"$SOUS_DOMAIN\"" RUN_THROUGH_SSH yunohost domain add $SUBDOMAIN
USER_TEST_CLEAN=${USER_TEST//"_"/""} TEST_USER_DISPLAY=${TEST_USER//"_"/""}
echo -e "\e[1m> Ajout de l'utilisateur de test\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Ajout de l'utilisateur de test"
ssh $ARG_SSH $LXC_NAME "sudo yunohost user create --firstname \"$USER_TEST_CLEAN\" --mail \"$USER_TEST_CLEAN@$DOMAIN\" --lastname \"$USER_TEST_CLEAN\" --password \"$YUNO_PWD\" \"$USER_TEST\"" RUN_THROUGH_SSH yunohost user create $TEST_USER --firstname $TEST_USER_DISPLAY --mail $TEST_USER@$DOMAIN --lastname $TEST_USER_DISPLAY --password \"$YUNO_PWD\"
echo -e -e "\e[1m\n> Vérification de l'état de Yunohost\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Vérification de l'état de Yunohost"
ssh $ARG_SSH $LXC_NAME "sudo yunohost -v" | tee -a "$LOG_BUILD_LXC" 2>&1 RUN_THROUGH_SSH yunohost --version
log_title "Arrêt de la machine virtualisée"
sudo lxc-stop -n $LXC_NAME
echo -e "\e[1m> Arrêt de la machine virtualisée\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Suppression des règles de parefeu"
sudo lxc-stop -n $LXC_NAME >> "$LOG_BUILD_LXC" 2>&1 sudo iptables -D FORWARD -i $LXC_BRIDGE -o $MAIN_NETWORK_INTERFACE -j ACCEPT
sudo iptables -D FORWARD -i $MAIN_NETWORK_INTERFACE -o $LXC_BRIDGE -j ACCEPT
sudo iptables -t nat -D POSTROUTING -s $LXC_NETWORK.0/24 -j MASQUERADE
sudo ifdown --force $LXC_BRIDGE
echo -e "\e[1m> Suppression des règles de parefeu\e[0m" | tee -a "$LOG_BUILD_LXC" log_title "Création d'un snapshot"
sudo iptables -D FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT >> "$LOG_BUILD_LXC" 2>&1 sudo lxc-snapshot -n $LXC_NAME
sudo iptables -D FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT >> "$LOG_BUILD_LXC" 2>&1
sudo iptables -t nat -D POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE >> "$LOG_BUILD_LXC" 2>&1
sudo ifdown --force $LXC_BRIDGE >> "$LOG_BUILD_LXC" 2>&1
echo -e "\e[1m> Création d'un snapshot\e[0m" | tee -a "$LOG_BUILD_LXC"
sudo lxc-snapshot -n $LXC_NAME >> "$LOG_BUILD_LXC" 2>&1
# Il sera nommé snap0 et stocké dans /var/lib/lxcsnaps/$LXC_NAME/snap0/ # Il sera nommé snap0 et stocké dans /var/lib/lxcsnaps/$LXC_NAME/snap0/
sudo rm "$script_dir/../pcheck.lock" # Retire le lock rm "$lock_file"
}
LXC_BUILD 2>&1 | tee -a "./Build_lxc.log"

View file

@ -1,41 +1,18 @@
#!/bin/bash #!/bin/bash
# Test différents aspect du conteneur pour chercher d'éventuelles erreurs. # Test différents aspect du conteneur pour chercher d'éventuelles erreurs.
# Et tente de réparer si possible... # Et tente de réparer si possible...
# Récupère le dossier du script cd $(dirname $(realpath $0) | sed 's@/sub_scripts$@@g')
if [ "${0:0:1}" == "/" ]; then script_dir="$(dirname "$0")"; else script_dir="$(echo $PWD/$(dirname "$0" | cut -d '.' -f2) | sed 's@/$@@')"; fi source "./sub_scripts/common.sh"
no_lock=0 no_lock=0
if [ "$1" == "--no-lock" ]; then if [ "$1" == "--no-lock" ]; then
no_lock=1 no_lock=1
fi fi
ARG_SSH="-t"
# Récupère les informations depuis le fichier de conf (Ou le complète le cas échéant)
pcheck_config="$script_dir/../config"
# Tente de lire les informations depuis le fichier de config si il existe
if [ -e "$pcheck_config" ]
then
PLAGE_IP=$(cat "$pcheck_config" | grep PLAGE_IP= | cut -d '=' -f2)
DOMAIN=$(cat "$pcheck_config" | grep DOMAIN= | cut -d '=' -f2)
YUNO_PWD=$(cat "$pcheck_config" | grep YUNO_PWD= | cut -d '=' -f2)
LXC_NAME=$(cat "$pcheck_config" | grep LXC_NAME= | cut -d '=' -f2)
LXC_BRIDGE=$(cat "$pcheck_config" | grep LXC_BRIDGE= | cut -d '=' -f2)
main_iface=$(cat "$pcheck_config" | grep iface= | cut -d '=' -f2)
fi
# Exit with the correct exit code # Exit with the correct exit code
remove_lock () { remove_lock () {
if [ $no_lock -eq 1 ] rm -f "$lock_file"
then
sudo rm -f "$script_dir/../pcheck.lock"
fi
}
exit_failure () {
remove_lock
exit 1
} }
exit_rebuild () { exit_rebuild () {
@ -53,51 +30,6 @@ exit_sane () {
exit 0 exit 0
} }
# Use the default value and set it in the config file
replace_default_value () {
CONFIG_KEY=$1
local value=$(grep "|| $CONFIG_KEY=" "$build_script" | cut -d '=' -f2)
if grep -q $CONFIG_KEY= "$pcheck_config"
then
sed -i "s/$CONFIG_KEY=.*/$CONFIG_KEY=$value/" "$pcheck_config"
else
echo -e "$CONFIG_KEY=$value\n" >> "$pcheck_config"
fi
echo $value
}
# Utilise des valeurs par défaut si les variables sont vides, et génère le fichier de config
if [ -z "$PLAGE_IP" ]; then
PLAGE_IP=$(replace_default_value PLAGE_IP)
fi
if [ -z "$DOMAIN" ]; then
DOMAIN=$(replace_default_value DOMAIN)
fi
if [ -z "$YUNO_PWD" ]; then
YUNO_PWD=$(replace_default_value YUNO_PWD)
fi
if [ -z "$LXC_NAME" ]; then
LXC_NAME=$(replace_default_value LXC_NAME)
fi
if [ -z "$LXC_BRIDGE" ]; then
LXC_BRIDGE=$(replace_default_value LXC_BRIDGE)
fi
if [ -z "$main_iface" ]; then
# Tente de définir l'interface réseau principale
main_iface=$(sudo ip route | grep default | awk '{print $5;}') # Prend l'interface réseau défini par default
if [ -z $main_iface ]; then
echo -e "\e[91mImpossible de déterminer le nom de l'interface réseau de l'hôte.\e[0m"
exit_failure
fi
# Store the main iface in the config file
if grep -q iface= "$pcheck_config"
then
sed -i "s/iface=.*/iface=$main_iface/"
else
echo -e "# Main host iface\niface=$main_iface\n" >> "$pcheck_config"
fi
fi
STOP_CONTAINER () { STOP_CONTAINER () {
echo "Arrêt du conteneur $LXC_NAME" echo "Arrêt du conteneur $LXC_NAME"
sudo lxc-stop -n $LXC_NAME sudo lxc-stop -n $LXC_NAME
@ -107,16 +39,16 @@ START_NETWORK () {
echo "Initialisation du réseau pour le conteneur." echo "Initialisation du réseau pour le conteneur."
sudo ifup $LXC_BRIDGE --interfaces=/etc/network/interfaces.d/$LXC_BRIDGE sudo ifup $LXC_BRIDGE --interfaces=/etc/network/interfaces.d/$LXC_BRIDGE
# Activation des règles iptables # Activation des règles iptables
sudo iptables -A FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT sudo iptables -A FORWARD -i $LXC_BRIDGE -o $MAIN_NETWORK_INTERFACE -j ACCEPT
sudo iptables -A FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT sudo iptables -A FORWARD -i $MAIN_NETWORK_INTERFACE -o $LXC_BRIDGE -j ACCEPT
sudo iptables -t nat -A POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE sudo iptables -t nat -A POSTROUTING -s $LXC_NETWORK.0/24 -j MASQUERADE
} }
STOP_NETWORK () { STOP_NETWORK () {
echo "Arrêt du réseau pour le conteneur." echo "Arrêt du réseau pour le conteneur."
sudo iptables -D FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT > /dev/null 2>&1 sudo iptables -D FORWARD -i $LXC_BRIDGE -o $MAIN_NETWORK_INTERFACE -j ACCEPT > /dev/null 2>&1
sudo iptables -D FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT > /dev/null 2>&1 sudo iptables -D FORWARD -i $MAIN_NETWORK_INTERFACE -o $LXC_BRIDGE -j ACCEPT > /dev/null 2>&1
sudo iptables -t nat -D POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE > /dev/null 2>&1 sudo iptables -t nat -D POSTROUTING -s $LXC_NETWORK.0/24 -j MASQUERADE > /dev/null 2>&1
sudo ifdown --force $LXC_BRIDGE > /dev/null 2>&1 sudo ifdown --force $LXC_BRIDGE > /dev/null 2>&1
} }
@ -278,9 +210,7 @@ LXC_NETWORK_CONFIG () {
fi fi
} }
if [ $no_lock -eq 0 ]; then [ $no_lock -eq 0 ] && touch "$lock_file"
touch "$script_dir/../pcheck.lock" # Met en place le lock de Package check
fi
STOP_CONTAINER STOP_CONTAINER
STOP_NETWORK STOP_NETWORK
@ -292,7 +222,7 @@ CREATE_BRIDGE () {
echo | sudo tee /etc/network/interfaces.d/$LXC_BRIDGE <<EOF echo | sudo tee /etc/network/interfaces.d/$LXC_BRIDGE <<EOF
auto $LXC_BRIDGE auto $LXC_BRIDGE
iface $LXC_BRIDGE inet static iface $LXC_BRIDGE inet static
address $PLAGE_IP.1/24 address $LXC_NETWORK.1/24
bridge_ports none bridge_ports none
bridge_fd 0 bridge_fd 0
bridge_maxwait 0 bridge_maxwait 0
@ -318,7 +248,7 @@ do
then then
echo -e "\e[92mLe bridge démarre correctement.\e[0m" echo -e "\e[92mLe bridge démarre correctement.\e[0m"
# Vérifie que le bridge obtient une adresse IP # Vérifie que le bridge obtient une adresse IP
if LC_ALL=C sudo ip address | grep -A 10 $LXC_BRIDGE | grep "inet " | grep -q -F "$PLAGE_IP.1" if LC_ALL=C sudo ip address | grep -A 10 $LXC_BRIDGE | grep "inet " | grep -q -F "$LXC_NETWORK.1"
then then
echo -e "\e[92mLe bridge obtient correctement son adresse IP.\e[0m" echo -e "\e[92mLe bridge obtient correctement son adresse IP.\e[0m"
else else
@ -353,16 +283,15 @@ do
done done
# Test l'application des règles iptables # Test l'application des règles iptables
sudo iptables -A FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT sudo iptables -A FORWARD -i $LXC_BRIDGE -o $MAIN_NETWORK_INTERFACE -j ACCEPT
sudo iptables -A FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT sudo iptables -A FORWARD -i $MAIN_NETWORK_INTERFACE -o $LXC_BRIDGE -j ACCEPT
sudo iptables -t nat -A POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE sudo iptables -t nat -A POSTROUTING -s $LXC_NETWORK.0/24 -j MASQUERADE
if sudo iptables -C FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT && sudo iptables -C FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT && sudo iptables -t nat -C POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE if sudo iptables -C FORWARD -i $LXC_BRIDGE -o $MAIN_NETWORK_INTERFACE -j ACCEPT && sudo iptables -C FORWARD -i $MAIN_NETWORK_INTERFACE -o $LXC_BRIDGE -j ACCEPT && sudo iptables -t nat -C POSTROUTING -s $LXC_NETWORK.0/24 -j MASQUERADE
then then
echo -e "\e[92mLes règles iptables sont appliquées correctement.\e[0m" echo -e "\e[92mLes règles iptables sont appliquées correctement.\e[0m"
else else
echo -e "\e[91mLes règles iptables ne sont pas appliquées correctement, vérifier la configuration du système...\e[0m" critical "Les règles iptables ne sont pas appliquées correctement, vérifier la configuration du système..."
exit_failure
fi fi
# Arrête le réseau du conteneur # Arrête le réseau du conteneur
@ -388,8 +317,7 @@ ping -q -c 2 yunohost.org > /dev/null 2>&1
if [ "$?" -ne 0 ]; then # En cas d'échec de connexion, tente de pinger un autre domaine pour être sûr if [ "$?" -ne 0 ]; then # En cas d'échec de connexion, tente de pinger un autre domaine pour être sûr
ping -q -c 2 framasoft.org > /dev/null 2>&1 ping -q -c 2 framasoft.org > /dev/null 2>&1
if [ "$?" -ne 0 ]; then # En cas de nouvel échec de connexion. On considère que la connexion est down... if [ "$?" -ne 0 ]; then # En cas de nouvel échec de connexion. On considère que la connexion est down...
echo -e "\e[91mL'hôte semble ne pas avoir accès à internet. La connexion internet est indispensable.\e[0m" critical "L'hôte semble ne pas avoir accès à internet. La connexion internet est indispensable."
exit_failure
fi fi
fi fi
echo -e "\e[92mL'hôte dispose d'un accès à internet.\e[0m" echo -e "\e[92mL'hôte dispose d'un accès à internet.\e[0m"
@ -397,13 +325,10 @@ echo -e "\e[92mL'hôte dispose d'un accès à internet.\e[0m"
### Test le réseau du conteneur ### Test le réseau du conteneur
echo -e "\e[1m\n> Test de l'accès internet depuis le conteneur:\e[0m" echo -e "\e[1m\n> Test de l'accès internet depuis le conteneur:\e[0m"
CHECK_LXC_NET () { CHECK_LXC_NET () {
sudo lxc-attach -n $LXC_NAME -- ping -q -c 2 yunohost.org > /dev/null 2>&1 RUN_INSIDE_LXC ping -q -c 2 yunohost.org > /dev/null 2>&1 \
if [ "$?" -ne 0 ]; then # En cas d'échec de connexion, tente de pinger un autre domaine pour être sûr || RUN_INSIDE_LXC ping -q -c 2 framasoft.org > /dev/null 2>&1 \
sudo lxc-attach -n $LXC_NAME -- ping -q -c 2 framasoft.org > /dev/null 2>&1 || return 1
if [ "$?" -ne 0 ]; then # En cas de nouvel échec de connexion. On considère que la connexion est down...
return 1
fi
fi
return 0 return 0
} }
@ -473,7 +398,7 @@ do
else else
echo -e "\e[92mLe fichier network/interfaces du conteneur est présent.\nMais il va être réécrit par précaution.\e[0m" echo -e "\e[92mLe fichier network/interfaces du conteneur est présent.\nMais il va être réécrit par précaution.\e[0m"
fi fi
echo -e "auto lo\niface lo inet loopback\nauto eth0\niface eth0 inet static\n\taddress $PLAGE_IP.2/24\n\tgateway $PLAGE_IP.1" | sudo tee /var/lib/lxc/$LXC_NAME/rootfs/etc/network/interfaces echo -e "auto lo\niface lo inet loopback\nauto eth0\niface eth0 inet static\n\taddress $LXC_NETWORK.2/24\n\tgateway $LXC_NETWORK.1" | sudo tee /var/lib/lxc/$LXC_NAME/rootfs/etc/network/interfaces
fi fi
else else
echo -e "\e[92mLe conteneur dispose d'un accès à internet.\e[0m" echo -e "\e[92mLe conteneur dispose d'un accès à internet.\e[0m"
@ -483,21 +408,17 @@ done
### Test l'accès ssh sur le conteneur ### Test l'accès ssh sur le conteneur
echo -e "\e[1m\n> Test de l'accès ssh:\e[0m" echo -e "\e[1m\n> Test de l'accès ssh:\e[0m"
# Check user assert_we_are_the_setup_user
if [ "$(whoami)" != "$(cat "$script_dir/setup_user")" ] && test -e "$script_dir/setup_user"; then
echo -e "\e[91mPour tester l'accès ssh, le script doit être exécuté avec l'utilisateur $(cat "$script_dir/setup_user") !\nL'utilisateur actuel est $(whoami).\e[0m"
exit_failure
fi
sudo lxc-ls -f sudo lxc-ls -f
sleep 3 sleep 3
ssh $ARG_SSH $LXC_NAME "exit 0" # Test une connexion ssh ssh -t $LXC_NAME "exit 0" # Test une connexion ssh
if [ "$?" -eq 0 ]; then if [ "$?" -eq 0 ]; then
echo -e "\e[92mLa connexion ssh est fonctionnelle.\e[0m" echo -e "\e[92mLa connexion ssh est fonctionnelle.\e[0m"
else else
echo -e "\e[91mÉchec de la connexion ssh. Reconfiguration de l'accès ssh.\e[0m" echo -e "\e[91mÉchec de la connexion ssh. Reconfiguration de l'accès ssh.\e[0m"
check_repair=1 check_repair=1
ssh $ARG_SSH $LXC_NAME -v "exit 0" # Répète la connexion ssh pour afficher l'erreur. ssh -t $LXC_NAME -v "exit 0" # Répète la connexion ssh pour afficher l'erreur.
echo "Suppression de la config ssh actuelle pour le conteneur." echo "Suppression de la config ssh actuelle pour le conteneur."
rm -f $HOME/.ssh/$LXC_NAME $HOME/.ssh/$LXC_NAME.pub rm -f $HOME/.ssh/$LXC_NAME $HOME/.ssh/$LXC_NAME.pub
@ -505,23 +426,23 @@ else
BEGIN_LINE=$(cat $HOME/.ssh/config | grep -n "# ssh $LXC_NAME" | cut -d':' -f 1) BEGIN_LINE=$(cat $HOME/.ssh/config | grep -n "# ssh $LXC_NAME" | cut -d':' -f 1)
sed -i "$BEGIN_LINE,/^IdentityFile/d" $HOME/.ssh/config sed -i "$BEGIN_LINE,/^IdentityFile/d" $HOME/.ssh/config
ssh-keygen -f "$HOME/.ssh/known_hosts" -R $PLAGE_IP.2 ssh-keygen -f "$HOME/.ssh/known_hosts" -R $LXC_NETWORK.2
echo "Création de la clé ssh." echo "Création de la clé ssh."
ssh-keygen -t dsa -f $HOME/.ssh/$LXC_NAME -P '' ssh-keygen -t dsa -f $HOME/.ssh/$LXC_NAME -P ''
sudo cp $HOME/.ssh/$LXC_NAME.pub /var/lib/lxc/$LXC_NAME/rootfs/home/pchecker/.ssh/authorized_keys sudo cp $HOME/.ssh/$LXC_NAME.pub /var/lib/lxc/$LXC_NAME/rootfs/home/pchecker/.ssh/authorized_keys
sudo lxc-attach -n $LXC_NAME -- chown pchecker: -R /home/pchecker/.ssh RUN_INSIDE_LXC chown pchecker: -R /home/pchecker/.ssh
echo "Ajout de la config ssh." echo "Ajout de la config ssh."
echo | tee -a $HOME/.ssh/config <<EOF echo | tee -a $HOME/.ssh/config <<EOF
# ssh $LXC_NAME # ssh $LXC_NAME
Host $LXC_NAME Host $LXC_NAME
Hostname $PLAGE_IP.2 Hostname $LXC_NETWORK.2
User pchecker User pchecker
IdentityFile $HOME/.ssh/$LXC_NAME IdentityFile $HOME/.ssh/$LXC_NAME
EOF EOF
ssh-keyscan -H 10.1.4.2 >> ~/.ssh/known_hosts # Récupère la clé publique pour l'ajouter au known_hosts ssh-keyscan -H 10.1.4.2 >> ~/.ssh/known_hosts # Récupère la clé publique pour l'ajouter au known_hosts
ssh $ARG_SSH $LXC_NAME -v "exit 0" > /dev/null # Test à nouveau la connexion ssh ssh -t $LXC_NAME -v "exit 0" > /dev/null # Test à nouveau la connexion ssh
if [ "$?" -eq 0 ]; then if [ "$?" -eq 0 ]; then
echo -e "\e[92mLa connexion ssh est retablie.\e[0m" echo -e "\e[92mLa connexion ssh est retablie.\e[0m"
else else
@ -532,7 +453,7 @@ fi
### Vérifie que Yunohost est installé ### Vérifie que Yunohost est installé
echo -e "\e[1m\n> Vérifie que Yunohost est installé dans le conteneur:\e[0m" echo -e "\e[1m\n> Vérifie que Yunohost est installé dans le conteneur:\e[0m"
sudo lxc-attach -n $LXC_NAME -- sudo yunohost -v RUN_INSIDE_LXC sudo yunohost -v
if [ "$?" -ne 0 ]; then # Si la commande échoue, il y a un problème avec Yunohost if [ "$?" -ne 0 ]; then # Si la commande échoue, il y a un problème avec Yunohost
echo -e "\e[91mYunohost semble mal installé. Il est nécessaire de détruire et de reconstruire le conteneur.\e[0m" echo -e "\e[91mYunohost semble mal installé. Il est nécessaire de détruire et de reconstruire le conteneur.\e[0m"
exit_rebuild exit_rebuild

View file

@ -1,41 +0,0 @@
#!/bin/bash
# Force le démarrage conteneur et active la config réseau dédiée.
# Récupère le dossier du script
if [ "${0:0:1}" == "/" ]; then script_dir="$(dirname "$0")"; else script_dir="$(echo $PWD/$(dirname "$0" | cut -d '.' -f2) | sed 's@/$@@')"; fi
pcheck_config="$script_dir/../config"
PLAGE_IP=$(cat "$pcheck_config" | grep PLAGE_IP= | cut -d '=' -f2)
LXC_NAME=$(cat "$pcheck_config" | grep LXC_NAME= | cut -d '=' -f2)
LXC_BRIDGE=$(cat "$pcheck_config" | grep LXC_BRIDGE= | cut -d '=' -f2)
main_iface=$(cat "$pcheck_config" | grep iface= | cut -d '=' -f2)
"$script_dir/lxc_force_stop.sh" > /dev/null 2>&1
echo "Initialisation du réseau pour le conteneur."
sudo ifup $LXC_BRIDGE --interfaces=/etc/network/interfaces.d/$LXC_BRIDGE
# Activation des règles iptables
echo "> Configure le parefeu"
sudo iptables -A FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT
sudo iptables -A FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT
sudo iptables -t nat -A POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE
# Démarrage de la machine
echo "> Démarrage de la machine"
sudo lxc-start -n $LXC_NAME -d --logfile "$script_dir/lxc_boot.log"
sleep 3
# Vérifie que la machine a démarré
sudo lxc-ls -f
echo "> Connexion au conteneur:"
echo "Pour exécuter une seule commande:"
echo -e "\e[1msudo lxc-attach -n $LXC_NAME -- commande\e[0m"
echo "Pour établir une connexion ssh:"
if [ $(cat "$script_dir/setup_user") = "root" ]; then
echo -ne "\e[1msudo "
fi
echo -e "\e[1mssh -t $LXC_NAME 'bash -i'\e[0m"

View file

@ -1,49 +0,0 @@
#!/bin/bash
# Force l'arrêt du conteneur et désactive la config réseau dédiée.
# Récupère le dossier du script
if [ "${0:0:1}" == "/" ]; then script_dir="$(dirname "$0")"; else script_dir="$(echo $PWD/$(dirname "$0" | cut -d '.' -f2) | sed 's@/$@@')"; fi
pcheck_config="$script_dir/../config"
PLAGE_IP=$(cat "$pcheck_config" | grep PLAGE_IP= | cut -d '=' -f2)
LXC_NAME=$(cat "$pcheck_config" | grep LXC_NAME= | cut -d '=' -f2)
LXC_BRIDGE=$(cat "$pcheck_config" | grep LXC_BRIDGE= | cut -d '=' -f2)
main_iface=$(cat "$pcheck_config" | grep iface= | cut -d '=' -f2)
echo "> Arrêt de package_check"
# Kill package_check
# Retrieve the pid of Package check
package_check_pid="$(cat "$script_dir/../pcheck.lock" | cut -d: -f3)"
sudo kill --signal 15 $package_check_pid
echo "> Arrêt du conteneur"
if [ $(sudo lxc-info --name $LXC_NAME | grep -c "STOPPED") -eq 0 ]; then
echo "Arrêt du conteneur $LXC_NAME"
sudo lxc-stop -n $LXC_NAME
fi
echo "> Suppression des règles de parefeu"
if sudo iptables -C FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT 2> /dev/null
then
sudo iptables -D FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT
fi
if sudo iptables -C FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT 2> /dev/null
then
sudo iptables -D FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT
fi
if sudo iptables -t nat -C POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE 2> /dev/null
then
sudo iptables -t nat -D POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE
fi
echo "Arrêt de l'interface réseau pour le conteneur."
# Et arrêt du bridge
if sudo ifquery $LXC_BRIDGE --state > /dev/null
then
sudo ifdown --force $LXC_BRIDGE
fi
sudo lxc-ls -f
sudo rm "$script_dir/../pcheck.lock"

View file

@ -1,58 +1,30 @@
#!/bin/bash #!/bin/bash
# Récupère le dossier du script cd $(dirname $(realpath $0) | sed 's@/sub_scripts$@@g')
if [ "${0:0:1}" == "/" ]; then script_dir="$(dirname "$0")"; else script_dir="$(echo $PWD/$(dirname "$0" | cut -d '.' -f2) | sed 's@/$@@')"; fi source "./sub_scripts/common.sh"
pcheck_config="$script_dir/../config"
LXC_NAME=$(cat "$pcheck_config" | grep LXC_NAME= | cut -d '=' -f2)
LXC_BRIDGE=$(cat "$pcheck_config" | grep LXC_BRIDGE= | cut -d '=' -f2)
# Check user # Check user
if [ "$(whoami)" != "$(cat "$script_dir/setup_user")" ] && test -e "$script_dir/setup_user"; then assert_we_are_the_setup_user
echo -e "\e[91mCe script doit être exécuté avec l'utilisateur $(cat "$script_dir/setup_user") !\nL'utilisateur actuel est $(whoami)."
echo -en "\e[0m"
exit 0
fi
echo_bold () { touch "$lock_file"
if [ $quiet_remove -eq 0 ]
then
echo -e "\e[1m> $1\e[0m"
fi
}
quiet_remove=0 log_title "Retire l'ip forwarding."
# Check argument "quiet" sudo rm -f /etc/sysctl.d/lxc_pchecker.conf
if [ "$1" = "quiet" ]
then
quiet_remove=1
fi
touch "$script_dir/../pcheck.lock" # Met en place le lock de Package check
echo_bold "Retire l'ip forwarding."
sudo rm /etc/sysctl.d/lxc_pchecker.conf
sudo sysctl -p sudo sysctl -p
echo_bold "Désactive le bridge réseau" log_title "Désactive le bridge réseau"
sudo ifdown --force $LXC_BRIDGE sudo ifdown --force $LXC_BRIDGE
echo_bold "Supprime le brige réseau" log_title "Supprime le brige réseau"
sudo rm /etc/network/interfaces.d/$LXC_BRIDGE sudo rm -f /etc/network/interfaces.d/$LXC_BRIDGE
echo_bold "Suppression de la machine et de son snapshots" log_title "Suppression de la machine et de son snapshots"
sudo lxc-snapshot -n $LXC_NAME -d snap0 sudo lxc-snapshot -n $LXC_NAME -d snap0
sudo lxc-snapshot -n $LXC_NAME -d snap1 sudo lxc-snapshot -n $LXC_NAME -d snap1
sudo lxc-snapshot -n $LXC_NAME -d snap2 sudo lxc-snapshot -n $LXC_NAME -d snap2
sudo rm -f /var/lib/lxcsnaps/$LXC_NAME/snap0.tar.gz sudo rm -f /var/lib/lxcsnaps/$LXC_NAME/snap0.tar.gz
sudo lxc-destroy -n $LXC_NAME -f sudo lxc-destroy -n $LXC_NAME -f
if [ $quiet_remove -eq 0 ] log_title "Suppression des lignes de pchecker_lxc dans $HOME/.ssh/config"
then
echo_bold "Remove lxc lxctl"
sudo apt-get remove lxc lxctl
fi
echo_bold "Suppression des lignes de pchecker_lxc dans $HOME/.ssh/config"
BEGIN_LINE=$(cat $HOME/.ssh/config | grep -n "^# ssh pchecker_lxc$" | cut -d':' -f 1 | tail -n1) BEGIN_LINE=$(cat $HOME/.ssh/config | grep -n "^# ssh pchecker_lxc$" | cut -d':' -f 1 | tail -n1)
sed -i "$BEGIN_LINE,/^IdentityFile/d" $HOME/.ssh/config sed -i "$BEGIN_LINE,/^IdentityFile/d" $HOME/.ssh/config

View file

@ -1,123 +0,0 @@
#!/bin/bash
# Récupère le dossier du script
if [ "${0:0:1}" == "/" ]; then script_dir="$(dirname "$0")"; else script_dir="$(echo $PWD/$(dirname "$0" | cut -d '.' -f2) | sed 's@/$@@')"; fi
if test -e "$script_dir/../pcheck.lock"
then # L'upgrade est annulé
echo "Le fichier $script_dir/../pcheck.lock est présent. Package check est déjà utilisé. Exécution annulée..."
exit 0
fi
touch "$script_dir/../pcheck.lock" # Met en place le lock de Package check
pcheck_config="$script_dir/../config"
PLAGE_IP=$(cat "$pcheck_config" | grep PLAGE_IP= | cut -d '=' -f2)
LXC_NAME=$(cat "$pcheck_config" | grep LXC_NAME= | cut -d '=' -f2)
LXC_BRIDGE=$(cat "$pcheck_config" | grep LXC_BRIDGE= | cut -d '=' -f2)
main_iface=$(cat "$pcheck_config" | grep iface= | cut -d '=' -f2)
if [ -z "$main_iface" ]; then
# Tente de définir l'interface réseau principale
main_iface=$(sudo route | grep default | awk '{print $8;}') # Prend l'interface réseau défini par default
if [ -z $main_iface ]; then
echo -e "\e[91mImpossible de déterminer le nom de l'interface réseau de l'hôte.\e[0m"
exit 1
fi
# Enregistre le nom de l'interface réseau de l'hôte dans un fichier de config
echo -e "# Interface réseau principale de l'hôte\niface=$main_iface\n" >> "$pcheck_config"
fi
# Check user
if [ "$(whoami)" != "$(cat "$script_dir/setup_user")" ] && test -e "$script_dir/setup_user"; then
echo -e "\e[91mCe script doit être exécuté avec l'utilisateur $(cat "$script_dir/setup_user") !\nL'utilisateur actuel est $(whoami)."
echo -en "\e[0m"
rm "$script_dir/../pcheck.lock" # Retire le lock
exit 0
fi
echo -e "\e[1m> Active le bridge réseau\e[0m"
if ! sudo ifquery $LXC_BRIDGE --state > /dev/null
then
sudo ifup $LXC_BRIDGE --interfaces=/etc/network/interfaces.d/$LXC_BRIDGE
fi
echo -e "\e[1m> Configure le parefeu\e[0m"
if ! sudo iptables -D FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT 2> /dev/null
then
sudo iptables -A FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT
fi
if ! sudo iptables -C FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT 2> /dev/null
then
sudo iptables -A FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT
fi
if ! sudo iptables -t nat -C POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE 2> /dev/null
then
sudo iptables -t nat -A POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE
fi
echo -e "\e[1m> Démarrage de la machine\e[0m"
if [ $(sudo lxc-info --name $LXC_NAME | grep -c "STOPPED") -eq 0 ]; then
# Si la machine n'est pas à l'arrêt.
sudo lxc-stop -n $LXC_NAME # Arrête la machine LXC
fi
# Restaure le snapshot
sudo rsync -aEAX --delete -i /var/lib/lxcsnaps/$LXC_NAME/snap0/rootfs/ /var/lib/lxc/$LXC_NAME/rootfs/ > /dev/null # Pour être sûr!
sudo lxc-start -n $LXC_NAME -d
sleep 3
sudo lxc-ls -f
echo -e "\e[1m> Update\e[0m"
update_apt=0
sudo lxc-attach -n $LXC_NAME -- apt-get update
# Wait for apt to be available before the upgrade.
for try in `seq 1 17`
do
# Check if /var/lib/dpkg/lock is used by another process
if sudo lxc-attach -n $LXC_NAME -- lsof /var/lib/dpkg/lock > /dev/null
then
echo "apt is already in use..."
# Sleep an exponential time at each round
sleep $(( try * try ))
fi
done
sudo lxc-attach -n $LXC_NAME -- apt-get dist-upgrade --dry-run | grep -q "^Inst " # Vérifie si il y aura des mises à jour.
if [ "$?" -eq 0 ]; then
update_apt=1
fi
echo -e "\e[1m> Upgrade\e[0m"
sudo lxc-attach -n $LXC_NAME -- apt-get dist-upgrade --option Dpkg::Options::=--force-confold -yy
echo -e "\e[1m> Clean\e[0m"
sudo lxc-attach -n $LXC_NAME -- apt-get autoremove -y
sudo lxc-attach -n $LXC_NAME -- apt-get autoclean
if [ "$update_apt" -eq 1 ]
then # Print les numéros de version de Yunohost, si il y a eu un upgrade
(sudo lxc-attach -n $LXC_NAME -- yunohost -v) | sudo tee "$script_dir/ynh_version"
fi
# Disable password strength check
ssh $ARG_SSH $LXC_NAME "sudo yunohost settings set security.password.admin.strength -v -1" | tee -a "$LOG_BUILD_LXC" 2>&1
ssh $ARG_SSH $LXC_NAME "sudo yunohost settings set security.password.user.strength -v -1" | tee -a "$LOG_BUILD_LXC" 2>&1
echo -e "\e[1m> Arrêt de la machine virtualisée\e[0m"
sudo lxc-stop -n $LXC_NAME
echo -e "\e[1m> Suppression des règles de parefeu\e[0m"
sudo iptables -D FORWARD -i $LXC_BRIDGE -o $main_iface -j ACCEPT
sudo iptables -D FORWARD -i $main_iface -o $LXC_BRIDGE -j ACCEPT
sudo iptables -t nat -D POSTROUTING -s $PLAGE_IP.0/24 -j MASQUERADE
sudo ifdown --force $LXC_BRIDGE
if [ "$update_apt" -eq 1 ]
then
echo -e "\e[1m> Archivage du snapshot\e[0m"
sudo tar -cz --acls --xattrs -f /var/lib/lxcsnaps/$LXC_NAME/snap0.tar.gz /var/lib/lxcsnaps/$LXC_NAME/snap0
echo -e "\e[1m> Remplacement du snapshot\e[0m"
sudo lxc-snapshot -n $LXC_NAME -d snap0
sudo lxc-snapshot -n $LXC_NAME
fi
sudo rm "$script_dir/../pcheck.lock" # Retire le lock

196
sub_scripts/notifications.sh Executable file
View file

@ -0,0 +1,196 @@
#!/bin/bash
#=================================================
# Determine if it's a CI environment
#=================================================
# By default, it's a standalone execution.
type_exec_env=0
# CI environment
[ -e "./../config" ] && type_exec_env=1
# Official CI environment
[ -e "./../auto_build/auto.conf" ] && type_exec_env=2
# Try to find a optionnal email address to notify the maintainer
# In this case, this email will be used instead of the email from the manifest.
notification_email="$(grep -m1 "^Email=" $TEST_CONTEXT/check_process.options | cut -d '=' -f2)"
# Try to find a optionnal option for the grade of notification
notification_mode="$(grep -m1 "^Notification=" $TEST_CONTEXT/check_process.options | cut -d '=' -f2)"
#=================================================
# Notification grade
#=================================================
notif_grade () {
# Check the level of notification from the check_process.
# Echo 1 if the grade is reached
compare_grade ()
{
if echo "$notification_mode" | grep -q "$1"; then
echo 1
else
echo 0
fi
}
case "$1" in
all)
# If 'all' is needed, only a grade of notification at 'all' can match
compare_grade "^all$"
;;
change)
# If 'change' is needed, notification at 'all' or 'change' can match
compare_grade "^all$\|^change$"
;;
down)
# If 'down' is needed, notification at 'all', 'change' or 'down' match
compare_grade "^all$\|^change$\|^down$"
;;
*)
echo 0
;;
esac
}
#=================================================
# Inform of the results by XMPP and/or by mail
#=================================================
send_mail=0
# If package check it's in the official CI environment
# Check the level variation
if [ $type_exec_env -eq 2 ]
then
# Get the job name, stored in the work_list
job=$(head -n1 "./../work_list" | cut -d ';' -f 3)
# Identify the type of test, stable (0), testing (1) or unstable (2)
# Default stable
test_type=0
message=""
if echo "$job" | grep -q "(testing)"
then
message="(TESTING) "
test_type=1
elif echo "$job" | grep -q "(unstable)"
then
message="(UNSTABLE) "
test_type=2
fi
# Build the log path (and replace all space by %20 in the job name)
if [ -n "$job" ]; then
if systemctl list-units | grep --quiet jenkins
then
job_log="/job/${job// /%20}/lastBuild/console"
elif systemctl list-units | grep --quiet yunorunner
then
# Get the directory of YunoRunner
ci_dir="$(grep WorkingDirectory= /etc/systemd/system/yunorunner.service | cut -d= -f2)"
# List the jobs from YunoRunner and grep the job (without Community or Official).
job_id="$(cd "$ci_dir"; ve3/bin/python ciclic list | grep ${job%% *} | head -n1)"
# Keep only the id of the job, by removing everything after -
job_id="${job_id%% -*}"
# And remove any space before the id.
job_id="${job_id##* }"
job_log="/job/$job_id"
fi
fi
# If it's a test on testing or unstable
if [ $test_type -gt 0 ]
then
# Remove unstable or testing of the job name to find its stable version in the level list
job="${job% (*)}"
fi
# Get the previous level, found in the file list_level_stable
previous_level=$(grep "^$job:" "./../auto_build/list_level_stable" | cut -d: -f2)
# Print the variation of the level. If this level is different than 0
if [ $global_level -gt 0 ]
then
message="${message}Application $app_id"
# If non previous level was found
if [ -z "$previous_level" ]; then
message="$message just reach the level $global_level"
send_mail=$(notif_grade all)
# If the level stays the same
elif [ $global_level -eq $previous_level ]; then
message="$message stays at level $global_level"
# Need notification at 'all' to notify by email
send_mail=$(notif_grade all)
# If the level go up
elif [ $global_level -gt $previous_level ]; then
message="$message rise from level $previous_level to level $global_level"
# Need notification at 'change' to notify by email
send_mail=$(notif_grade change)
# If the level go down
elif [ $global_level -lt $previous_level ]; then
message="$message go down from level $previous_level to level $global_level"
# Need notification at 'down' to notify by email
send_mail=$(notif_grade down)
fi
fi
fi
# If the app completely failed and obtained 0
if [ $global_level -eq 0 ]
then
message="${message}Application $app_id has completely failed the continuous integration tests"
# Always send an email if the app failed
send_mail=1
fi
subject="[YunoHost] $message"
# If the test was perform in the official CI environment
# Add the log address
# And inform with xmpp
if [ $type_exec_env -eq 2 ]
then
# Build the address of the server from auto.conf
ci_path=$(grep "DOMAIN=" "./../auto_build/auto.conf" | cut -d= -f2)/$(grep "CI_PATH=" "./../auto_build/auto.conf" | cut -d= -f2)
# Add the log adress to the message
message="$message on https://$ci_path$job_log"
# Send a xmpp notification on the chat room "apps"
# Only for a test with the stable version of YunoHost
if [ $test_type -eq 0 ]
then
"./../auto_build/xmpp_bot/xmpp_post.sh" "$message" > /dev/null 2>&1
fi
fi
# Send a mail to main maintainer according to notification option in the check_process.
# Only if package check is in a CI environment (Official or not)
if [ $type_exec_env -ge 1 ] && [ $send_mail -eq 1 ]
then
# Add a 'from' header for the official CI only.
# Apparently, this trick is not needed anymore !?
# if [ $type_exec_env -eq 2 ]; then
# from_yuno="-a \"From: yunohost@yunohost.org\""
# fi
# Get the maintainer email from the manifest. If it doesn't found if the check_process
if [ -z "$notification_email" ]; then
notification_email=$(grep '\"email\": ' "$package_path/manifest.json" | cut -d '"' -f 4)
fi
# Send the message by mail, if a address has been find
if [ -n "$notification_email" ]; then
mail $from_yuno -s "$subject" "$notification_email" <<< "$message"
fi
fi

1036
sub_scripts/testing_process.sh Normal file → Executable file

File diff suppressed because it is too large Load diff