vcs-backup.sh
author František Kučera <franta-hg@frantovo.cz>
Sun, 21 Apr 2019 21:57:46 +0200
branchv_0
changeset 14 1e1ba6753d92
parent 13 a0b7d78460c2
child 15 e7279b13a071
permissions -rwxr-xr-x
reports: use printRecfileKeyValue also for headers
     1 #!/bin/bash
     2 
     3 # VCS Backup
     4 # Copyright © 2019 František Kučera (Frantovo.cz, GlobalCode.info)
     5 #
     6 # This program is free software: you can redistribute it and/or modify
     7 # it under the terms of the GNU General Public License as published by
     8 # the Free Software Foundation, either version 3 of the License, or
     9 # (at your option) any later version.
    10 #
    11 # This program is distributed in the hope that it will be useful,
    12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
    13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    14 # GNU General Public License for more details.
    15 #
    16 # You should have received a copy of the GNU General Public License
    17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
    18 
    19 
    20 # VCS Backup is a configuration for setting up a version control system mirrors.
    21 # Currently Mercurial (Hg) and Git are supported.
    22 # Features:
    23 #  - mirrors remote repositories
    24 #  - creates Btrfs subvolume for each repository
    25 #  - does periodic pull to keep mirrors up to date
    26 #  - does periodic Btrfs snapshot to keep history (git push --force done on the remote repository will lead to modifications or deletions in our current mirror, but previous versions will be kept in the snapshots)
    27 #  - provides web interface for remote clonning of our mirrors (see systemd and etc folders)
    28 #  - can be controlled over SSH by a sane person / owner of the system
    29 #  - provides reports in the recfile format (to be processed using GNU Recutils or Relational pipes):
    30 #     - list of repositories/mirrors
    31 #     - results of pull operations
    32 
    33 
    34 # This is an asynchronous message-driven shell script that runs distributed across two machines and four user accounts. You have been warned :-)
    35 
    36 
    37 # Server-side configuration:
    38 VCS_BACKUP_DATA_DIR="/mnt/data";
    39 VCS_BACKUP_CURRENT_DIR="$VCS_BACKUP_DATA_DIR/current";
    40 VCS_BACKUP_PUBLIC_DIR="$VCS_BACKUP_DATA_DIR/public";
    41 VCS_BACKUP_CONFIG_DIR="$VCS_BACKUP_DATA_DIR/config";
    42 VCS_BACKUP_SNAPSHOT_DIR="$VCS_BACKUP_DATA_DIR/snapshot";
    43 VCS_BACKUP_SUBVOLUME_SOCKET="/run/vcs-backup-subvolume";
    44 VCS_BACKUP_CLONE_SOCKET="/run/vcs-backup-clone/socket"; # the directory will be writable by ${VCS_BACKUP_USER}
    45 VCS_BACKUP_CLONE_CALLBACK_SOCKET="clone-callback";
    46 VCS_BACKUP_USER="vcs-backup";
    47 VCS_BACKUP_MANAGER="vcs-backup-manager";
    48 
    49 # Installation – check and do it by hand:
    50 # There should be already mounted Btrfs at $VCS_BACKUP_DATA_DIR
    51 installInstructions() {
    52 cp vcs-backup.sh /usr/local/bin/
    53 adduser --disabled-password "$VCS_BACKUP"
    54 adduser --disabled-password "$VCS_BACKUP_MANAGER"
    55 
    56 mkdir "$VCS_BACKUP_CURRENT_DIR";
    57 mkdir "$VCS_BACKUP_CONFIG_DIR";
    58 mkdir "$VCS_BACKUP_SNAPSHOT_DIR";
    59 mkdir "$(dirname VCS_BACKUP_CLONE_SOCKET)"
    60 
    61 chown "${VCS_BACKUP_USER}:${VCS_BACKUP_USER}" "$(dirname VCS_BACKUP_CLONE_SOCKET)"
    62 chown "${VCS_BACKUP_MANAGER}:${VCS_BACKUP_MANAGER}" "$VCS_BACKUP_CONFIG_DIR"
    63 }
    64 
    65 
    66 # --- Private functions: ---------------------------------------------------------------------------
    67 
    68 # Environment: all
    69 # $1 = VCS type: hg, git
    70 # $2 = URL
    71 isValidTypeAndURL() { ([[ "$1" == "hg" || "$1" == "git" ]]) && [[ $(echo "$2" | wc -l) == 1 ]] && [[ $(echo "$2" | grep -E '^(http|https|ssh)://([a-zA-Z0-9_-][a-zA-Z0-9_-.]*/?)+$' | wc -l) == 1 ]]; }
    72 
    73 # Environment: all
    74 # $1 = path to the config file
    75 loadConfigFile() { if [ -f "$1" ]; then . "$1"; fi }
    76 
    77 # Environment: server
    78 # $1 = URL
    79 urlToRelativeDirectoryPath() {
    80 	echo "$1" | sed -E 's@^[^:]+://@@g';
    81 }
    82 
    83 # Environment: all
    84 # $1 = optional value (if missing, reads STDIN)
    85 escapeRecfileValue() { if [[ $# = 0 ]]; then awk '{ if (NR > 1) { printf "+ " } print $_ }'; else echo "${@}" | ${FUNCNAME[0]}; fi }
    86 
    87 # Environment: all
    88 # $1 = key
    89 # $2 = value
    90 printRecfileKeyValue() { echo -n "$1: "; escapeRecfileValue "$2"; }
    91 
    92 # --- Public interface functions: ------------------------------------------------------------------
    93 
    94 # Environment: client
    95 # $1 = VCS type: hg, git
    96 # $2 = URL
    97 # $3 = "public" or "private" (default), whether the repository should be available through the public web interface
    98 # $4 = "clone" (optional), if present, will also clone the backup locally
    99 vcs_backup_public_clientSubmitBackupRequest() {
   100 	if isValidTypeAndURL "$1" "$2"; then
   101 		loadConfigFile ~/.config/vcs-backup/client.cfg
   102 		${VCS_BACKUP_SSH_COMMAND[@]} vcs-backup.sh serverSubmitBackupRequest "$1" "$2" "$3" "$4"
   103 		if [[ "$4" == "clone" ]]; then
   104 			if   [[ "$1" == "hg"  ]]; then  hg clone "ssh://${VCS_BACKUP_SERVER}/$VCS_BACKUP_CURRENT_DIR/$1/$(urlToRelativeDirectoryPath $2)";
   105 			elif [[ "$1" == "git" ]]; then git clone "ssh://${VCS_BACKUP_SERVER}/$VCS_BACKUP_CURRENT_DIR/$1/$(urlToRelativeDirectoryPath $2)";
   106 			fi
   107 		fi
   108 	else
   109 		echo "Unsupported VCS type: '$1' or URL: '$2'" >&2;
   110 	fi
   111 }
   112 
   113 # Environment: server
   114 # User: $VCS_BACKUP_MANAGER
   115 # has same parameters as clientSubmitBackupRequest (see above)
   116 vcs_backup_public_serverSubmitBackupRequest() {
   117 	if isValidTypeAndURL "$1" "$2"; then
   118 		loadConfigFile "/etc/vcs-backup/server.cfg";
   119 		relativePath=$1/$(urlToRelativeDirectoryPath "$2");
   120 		absolutePath="$VCS_BACKUP_CONFIG_DIR/$relativePath";
   121 		mkdir -p "$absolutePath";
   122 		echo "$2" > "$absolutePath/url.txt"
   123 		echo "submited" > "$absolutePath/state.txt"
   124 		setfacl -m u:${VCS_BACKUP_USER}:r  "$absolutePath/url.txt"
   125 		setfacl -m u:${VCS_BACKUP_USER}:rw "$absolutePath/state.txt"
   126 
   127 		if [[ "$3" == "public" ]]; then
   128 			cd "$VCS_BACKUP_PUBLIC_DIR";
   129 			mkdir -p "$(dirname $relativePath)";
   130 			ln -rs "../current/$relativePath" "$(dirname $relativePath)";
   131 		fi
   132 
   133 		if [[ "$4" == "clone" ]]; then
   134 			callBackSocket=$absolutePath/${VCS_BACKUP_CLONE_CALLBACK_SOCKET}
   135 			socat -u "unix-recvfrom:$callBackSocket,mode=777" - | while read m; do # TODO: ,group=${VCS_BACKUP_USER} and no 777 ?
   136 				echo "Message from the service: $m";
   137 			done &
   138 			callBackPID=$!;
   139 		fi
   140 
   141 		echo "$relativePath" | socat -u - unix-send:${VCS_BACKUP_SUBVOLUME_SOCKET};
   142 
   143 		if [[ "$4" == "clone" ]]; then
   144 			echo "Waiting for a message from the service on $callBackSocket (PID $callBackPID)";
   145 			wait -n $callBackPID;
   146 		fi
   147 	else
   148 		echo "Unsupported VCS type: '$1' or URL: '$2'" >&2;
   149 	fi
   150 }
   151 
   152 # Environment: server
   153 # User: root
   154 # Should be started as a systemd/init service.
   155 # - reads messages from from the subvolume socket – message contains the relative directory path
   156 # - creates a subvolume for given repository + necesary parent directories
   157 # - sends a message to the clone service → start cloning into the created subvolume
   158 vcs_backup_public_serverStartSubvolumeService() {
   159 	socat -u "unix-recv:${VCS_BACKUP_SUBVOLUME_SOCKET},group=${VCS_BACKUP_MANAGER},mode=770" - | while read d; do
   160 		mkdir -p $(dirname "$VCS_BACKUP_CURRENT_DIR/$d");
   161 		if [[ -e "$VCS_BACKUP_CURRENT_DIR/$d" ]]; then
   162 			callBackSocket="$VCS_BACKUP_CONFIG_DIR/$d/$VCS_BACKUP_CLONE_CALLBACK_SOCKET";
   163 			if [[ -e "$callBackSocket" ]]; then
   164 				echo "alreadyDone" | socat -u - unix-send:"$callBackSocket";
   165 			fi
   166 		else
   167 			btrfs subvolume create "$VCS_BACKUP_CURRENT_DIR/$d" && \
   168 			echo "subvolumeCreated" > "$VCS_BACKUP_CONFIG_DIR/$d/state.txt" && \
   169 			chown "${VCS_BACKUP_USER}:${VCS_BACKUP_USER}" "$VCS_BACKUP_CURRENT_DIR/$d" && \
   170 			echo "$d" | socat -u - unix-send:${VCS_BACKUP_CLONE_SOCKET};
   171 		fi
   172 	done
   173 }
   174 
   175 # Environment: server
   176 # User: $VCS_BACKUP_USER
   177 # should be started as a systemd/init service
   178 vcs_backup_public_serverStartCloneService() {
   179 	socat -u "unix-recv:${VCS_BACKUP_CLONE_SOCKET},mode=700" - | while read d; do
   180 		vcsType=$(echo "$d" | sed 's@/.*@@g');
   181 		url=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/url.txt");
   182 
   183 		if isValidTypeAndURL "$vcsType" "$url"; then
   184 			if   [[ "$vcsType" == "hg"  ]]; then  hg clone -U       "$url" "$VCS_BACKUP_CURRENT_DIR/$d";
   185 			elif [[ "$vcsType" == "git" ]]; then git clone --mirror "$url" "$VCS_BACKUP_CURRENT_DIR/$d";
   186 			fi && echo "cloned" > "$VCS_BACKUP_CONFIG_DIR/$d/state.txt";
   187 		else
   188 			echo "Unsupported VCS type: '$vcsType' or URL: '$url'" >&2;
   189 		fi
   190 
   191 		callBackSocket="$VCS_BACKUP_CONFIG_DIR/$d/$VCS_BACKUP_CLONE_CALLBACK_SOCKET";
   192 		if [[ -e "$callBackSocket" ]]; then
   193 			echo "done" | socat -u - unix-send:"$callBackSocket";
   194 		fi
   195 	done
   196 }
   197 
   198 # Environment: client
   199 # prints list of repositories in recfile format
   200 # usage example: vcs-backup.sh clientListRepositories | relpipe-in-recfile | relpipe-out-tabular
   201 vcs_backup_public_clientListRepositories() {
   202 	loadConfigFile ~/.config/vcs-backup/client.cfg;
   203 	${VCS_BACKUP_SSH_COMMAND[@]} vcs-backup.sh serverListRepositories;
   204 }
   205 
   206 # Environment: server
   207 # User: $VCS_BACKUP_MANAGER
   208 vcs_backup_public_serverListRepositories() {
   209 	printRecfileKeyValue "%rec"  "repositories";
   210 	printRecfileKeyValue "%type" "bytes int";
   211 	printRecfileKeyValue "%type" "public bool";
   212 	echo;
   213 
   214 	find "$VCS_BACKUP_CONFIG_DIR" -name url.txt -printf '%P\n' | sort | xargs dirname | while read d; do
   215 		url=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/url.txt");
   216 		state=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/state.txt");
   217 		vcsType=$(echo "$d" | sed 's@/.*@@g');
   218 		sizeBytes=$(du -sb "$VCS_BACKUP_CURRENT_DIR/$d" | cut -f1);
   219 		[[ -e "$VCS_BACKUP_PUBLIC_DIR/$d" ]] && public="true" || public="false";
   220 		
   221 		if [[ "$vcsType" == "hg"  ]]; then lastCommit=$(hg log --limit 1 --template '{date|isodatesec}' -R "$VCS_BACKUP_CURRENT_DIR/$d" 2>/dev/null);
   222 		elif [[ "$vcsType" == "git" ]]; then lastCommit=$(git -C "$VCS_BACKUP_CURRENT_DIR/$d" log --max-count=1 --pretty="%ai"); 
   223 		else lastCommit=""; fi
   224 		
   225 		printRecfileKeyValue "type"            "$vcsType";
   226 		printRecfileKeyValue "url"             "$url";
   227 		printRecfileKeyValue "state"           "$state";
   228 		printRecfileKeyValue "public"          "$public";
   229 		printRecfileKeyValue "serverPath"      "$VCS_BACKUP_CURRENT_DIR/$d";
   230 		printRecfileKeyValue "size"            "$sizeBytes";
   231 		printRecfileKeyValue "lastCommit"      "$lastCommit";
   232 		echo;
   233 	done
   234 }
   235 
   236 # Environment: server
   237 # User: $VCS_BACKUP_USER
   238 # should be called from cron (usually every day)
   239 vcs_backup_public_serverPullCronTask() {
   240 	printRecfileKeyValue "%rec"  "pull";
   241 	printRecfileKeyValue "%type" "started date";
   242 	printRecfileKeyValue "%type" "finished date";
   243 	printRecfileKeyValue "%type" "duration int";
   244 	printRecfileKeyValue "%type" "resultCode int";
   245 
   246 	find "$VCS_BACKUP_CONFIG_DIR" -name url.txt -printf '%P\n' | sort | xargs dirname | while read d; do
   247 		state=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/state.txt");
   248 		vcsType=$(echo "$d" | sed 's@/.*@@g');
   249 		absolutePath="$VCS_BACKUP_CURRENT_DIR/$d";
   250 
   251 
   252 		pullStarted=$(date --iso-8601=s);
   253 		pullStartedMiliseconds=$(($(date +%s%N)/1000000));
   254 		pullFinished="";
   255 		pullDuration="";
   256 		pullResult="";
   257 		pullResultCode="";
   258 		if [[ "$state" == "cloned" ]]; then
   259 			if   [[ "$vcsType" == "hg" ]];  then pullResult=$(hg pull --force --repository "$absolutePath" 2>&1); pullResultCode=$?;
   260 			elif [[ "$vcsType" == "git" ]]; then pullResult=$(git -C "$absolutePath" fetch 2>&1); pullResultCode=$?;
   261 			fi
   262 			pullFinished=$(date --iso-8601=s);
   263 			pullFinishedMiliseconds=$(($(date +%s%N)/1000000));
   264 			pullDuration=$(( $pullFinishedMiliseconds - $pullStartedMiliseconds ));
   265 		fi
   266 
   267 		printRecfileKeyValue "serverPath"      "$absolutePath";
   268 		printRecfileKeyValue "type"            "$vcsType";
   269 		printRecfileKeyValue "state"           "$state";
   270 		printRecfileKeyValue "started"         "$pullStarted";
   271 		printRecfileKeyValue "finished"        "$pullFinished";
   272 		printRecfileKeyValue "duration"        "$pullDuration";
   273 		printRecfileKeyValue "resultCode"      "$pullResultCode";
   274 		printRecfileKeyValue "message"         "$pullResult";
   275 		echo;
   276 	done
   277 }
   278 
   279 # Environment: server
   280 # User: root
   281 # should be called from cron (usually every day) after Pull (see above)
   282 vcs_backup_public_serverSnapshotCronTask() {
   283 	return;
   284 }
   285 
   286 # --- Single entry-point: --------------------------------------------------------------------------
   287 
   288 PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
   289 PUBLIC_FUNCTION_PREFIX="vcs_backup_public_";
   290 if type -t "$PUBLIC_FUNCTION_PREFIX$1" > /dev/null; then
   291 	"$PUBLIC_FUNCTION_PREFIX${@:1}";
   292 elif [[ $(basename $0) == "vcs-backup-clone-private-hg"  ]]; then "${PUBLIC_FUNCTION_PREFIX}clientSubmitBackupRequest" hg  "$1" private clone;
   293 elif [[ $(basename $0) == "vcs-backup-clone-private-git" ]]; then "${PUBLIC_FUNCTION_PREFIX}clientSubmitBackupRequest" git "$1" private clone;
   294 elif [[ $(basename $0) == "vcs-backup-clone-public-hg"   ]]; then "${PUBLIC_FUNCTION_PREFIX}clientSubmitBackupRequest" hg  "$1" public  clone;
   295 elif [[ $(basename $0) == "vcs-backup-clone-public-git"  ]]; then "${PUBLIC_FUNCTION_PREFIX}clientSubmitBackupRequest" git "$1" public  clone;
   296 else
   297 	echo "Unsupported sub-command: $1" >&2
   298 	echo "Available sub-commands:" >&2
   299 	declare -F | grep "$PUBLIC_FUNCTION_PREFIX" | sed "s/.*$PUBLIC_FUNCTION_PREFIX/  /g" >&2
   300 	exit 1;
   301 fi