vcs-backup.sh
author František Kučera <franta-hg@frantovo.cz>
Tue, 23 Apr 2019 17:06:58 +0200
branchv_0
changeset 17 fb9b67ba1dae
parent 16 44a8a36ca380
child 18 9353b2531cda
permissions -rwxr-xr-x
common function: allRepositories()
     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: / loadServerConfigFile()
    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 # Client-side configuration: / see loadClientConfigFile()
    50 VCS_BACKUP_SERVER="$VCS_BACKUP_MANAGER@localhost";
    51 VCS_BACKUP_SSH_COMMAND=(ssh "$VCS_BACKUP_SERVER");
    52 
    53 # Installation – check and do it by hand:
    54 # There should be already mounted Btrfs at $VCS_BACKUP_DATA_DIR
    55 installInstructions() {
    56 cp vcs-backup.sh /usr/local/bin/
    57 adduser --disabled-password "$VCS_BACKUP"
    58 adduser --disabled-password "$VCS_BACKUP_MANAGER"
    59 
    60 mkdir "$VCS_BACKUP_CURRENT_DIR";
    61 mkdir "$VCS_BACKUP_CONFIG_DIR";
    62 mkdir "$VCS_BACKUP_SNAPSHOT_DIR";
    63 mkdir "$(dirname VCS_BACKUP_CLONE_SOCKET)"
    64 
    65 chown "${VCS_BACKUP_USER}:${VCS_BACKUP_USER}" "$(dirname VCS_BACKUP_CLONE_SOCKET)"
    66 chown "${VCS_BACKUP_MANAGER}:${VCS_BACKUP_MANAGER}" "$VCS_BACKUP_CONFIG_DIR"
    67 }
    68 
    69 
    70 # --- Private functions: ---------------------------------------------------------------------------
    71 
    72 # Environment: all
    73 # $1 = VCS type: hg, git
    74 # $2 = URL
    75 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 ]]; }
    76 
    77 # Environment: all
    78 # $1 = path to the config file
    79 loadConfigFile() { if [ -f "$1" ]; then . "$1"; fi }
    80 loadClientConfigFile() { loadConfigFile ~/.config/vcs-backup/client.cfg; }
    81 loadServerConfigFile() { loadConfigFile "/etc/vcs-backup/server.cfg"; }
    82 
    83 # Environment: server
    84 # $1 = URL
    85 urlToRelativeDirectoryPath() {
    86 	echo "$1" | sed -E 's@^[^:]+://@@g';
    87 }
    88 
    89 # Environment: server
    90 # Lists relative paths (starting wiht hg or git) of all configured repositories
    91 allRepositories() { find "$VCS_BACKUP_CONFIG_DIR" -name url.txt -printf '%P\n' | sort | xargs --no-run-if-empty dirname; }
    92 
    93 # Environment: all
    94 # $1 = optional value (if missing, reads STDIN)
    95 escapeRecfileValue() { if [[ $# = 0 ]]; then awk '{ if (NR > 1) { printf "+ " } print $_ }'; else echo "${@}" | ${FUNCNAME[0]}; fi }
    96 
    97 # Environment: all
    98 # $1 = key
    99 # $2 = value
   100 printRecfileKeyValue() { echo -n "$1: "; escapeRecfileValue "$2"; }
   101 
   102 # --- Public interface functions: ------------------------------------------------------------------
   103 
   104 # Environment: client
   105 # $1 = VCS type: hg, git
   106 # $2 = URL
   107 # $3 = "public" or "private" (default), whether the repository should be available through the public web interface
   108 # $4 = "clone" (optional), if present, will also clone the backup locally
   109 vcs_backup_public_clientSubmitBackupRequest() {
   110 	if isValidTypeAndURL "$1" "$2"; then
   111 		${VCS_BACKUP_SSH_COMMAND[@]} vcs-backup.sh serverSubmitBackupRequest "$1" "$2" "$3" "$4"
   112 		if [[ "$4" == "clone" ]]; then
   113 			if   [[ "$1" == "hg"  ]]; then  hg clone "ssh://${VCS_BACKUP_SERVER}/$VCS_BACKUP_CURRENT_DIR/$1/$(urlToRelativeDirectoryPath $2)";
   114 			elif [[ "$1" == "git" ]]; then git clone "ssh://${VCS_BACKUP_SERVER}/$VCS_BACKUP_CURRENT_DIR/$1/$(urlToRelativeDirectoryPath $2)";
   115 			fi
   116 		fi
   117 	else
   118 		echo "Unsupported VCS type: '$1' or URL: '$2'" >&2;
   119 	fi
   120 }
   121 
   122 # Environment: server
   123 # User: $VCS_BACKUP_MANAGER
   124 # has same parameters as clientSubmitBackupRequest (see above)
   125 vcs_backup_public_serverSubmitBackupRequest() {
   126 	if isValidTypeAndURL "$1" "$2"; then
   127 		relativePath=$1/$(urlToRelativeDirectoryPath "$2");
   128 		absolutePath="$VCS_BACKUP_CONFIG_DIR/$relativePath";
   129 		# TODO: stop if directory already exists / only add public link?
   130 		mkdir -p "$absolutePath";
   131 		echo "$2" > "$absolutePath/url.txt"
   132 		echo "submited" > "$absolutePath/state.txt"
   133 		setfacl -m u:${VCS_BACKUP_USER}:r  "$absolutePath/url.txt"
   134 		setfacl -m u:${VCS_BACKUP_USER}:rw "$absolutePath/state.txt"
   135 
   136 		if [[ "$3" == "public" ]]; then
   137 			cd "$VCS_BACKUP_PUBLIC_DIR";
   138 			mkdir -p "$(dirname $relativePath)";
   139 			ln -rs "../current/$relativePath" "$(dirname $relativePath)";
   140 		fi
   141 
   142 		if [[ "$4" == "clone" ]]; then
   143 			callBackSocket=$absolutePath/${VCS_BACKUP_CLONE_CALLBACK_SOCKET}
   144 			socat -u "unix-recvfrom:$callBackSocket,mode=777" - | while read m; do # TODO: ,group=${VCS_BACKUP_USER} and no 777 ?
   145 				echo "Message from the service: $m";
   146 			done &
   147 			callBackPID=$!;
   148 		fi
   149 
   150 		echo "$relativePath" | socat -u - unix-send:${VCS_BACKUP_SUBVOLUME_SOCKET};
   151 
   152 		if [[ "$4" == "clone" ]]; then
   153 			echo "Waiting for a message from the service on $callBackSocket (PID $callBackPID)";
   154 			wait -n $callBackPID;
   155 		fi
   156 	else
   157 		echo "Unsupported VCS type: '$1' or URL: '$2'" >&2;
   158 	fi
   159 }
   160 
   161 # Environment: server
   162 # User: root
   163 # Should be started as a systemd/init service.
   164 # - reads messages from from the subvolume socket – message contains the relative directory path
   165 # - creates a subvolume for given repository + necesary parent directories
   166 # - sends a message to the clone service → start cloning into the created subvolume
   167 vcs_backup_public_serverStartSubvolumeService() {
   168 	socat -u "unix-recv:${VCS_BACKUP_SUBVOLUME_SOCKET},group=${VCS_BACKUP_MANAGER},mode=770" - | while read d; do
   169 		mkdir -p $(dirname "$VCS_BACKUP_CURRENT_DIR/$d");
   170 		if [[ -e "$VCS_BACKUP_CURRENT_DIR/$d" ]]; then
   171 			callBackSocket="$VCS_BACKUP_CONFIG_DIR/$d/$VCS_BACKUP_CLONE_CALLBACK_SOCKET";
   172 			if [[ -e "$callBackSocket" ]]; then
   173 				echo "alreadyDone" | socat -u - unix-send:"$callBackSocket";
   174 			fi
   175 		else
   176 			btrfs subvolume create "$VCS_BACKUP_CURRENT_DIR/$d" && \
   177 			echo "subvolumeCreated" > "$VCS_BACKUP_CONFIG_DIR/$d/state.txt" && \
   178 			chown "${VCS_BACKUP_USER}:${VCS_BACKUP_USER}" "$VCS_BACKUP_CURRENT_DIR/$d" && \
   179 			echo "$d" | socat -u - unix-send:${VCS_BACKUP_CLONE_SOCKET};
   180 		fi
   181 	done
   182 }
   183 
   184 # Environment: server
   185 # User: $VCS_BACKUP_USER
   186 # should be started as a systemd/init service
   187 vcs_backup_public_serverStartCloneService() {
   188 	socat -u "unix-recv:${VCS_BACKUP_CLONE_SOCKET},mode=700" - | while read d; do
   189 		vcsType=$(echo "$d" | sed 's@/.*@@g');
   190 		url=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/url.txt");
   191 
   192 		if isValidTypeAndURL "$vcsType" "$url"; then
   193 			if   [[ "$vcsType" == "hg"  ]]; then  hg clone -U       "$url" "$VCS_BACKUP_CURRENT_DIR/$d";
   194 			elif [[ "$vcsType" == "git" ]]; then git clone --mirror "$url" "$VCS_BACKUP_CURRENT_DIR/$d";
   195 			fi && echo "cloned" > "$VCS_BACKUP_CONFIG_DIR/$d/state.txt";
   196 		else
   197 			echo "Unsupported VCS type: '$vcsType' or URL: '$url'" >&2;
   198 		fi
   199 
   200 		callBackSocket="$VCS_BACKUP_CONFIG_DIR/$d/$VCS_BACKUP_CLONE_CALLBACK_SOCKET";
   201 		if [[ -e "$callBackSocket" ]]; then
   202 			echo "done" | socat -u - unix-send:"$callBackSocket";
   203 		fi
   204 	done
   205 }
   206 
   207 # Environment: client
   208 # prints list of repositories in recfile format
   209 # usage example: vcs-backup.sh clientListRepositories | relpipe-in-recfile | relpipe-out-tabular
   210 vcs_backup_public_clientListRepositories() {
   211 	${VCS_BACKUP_SSH_COMMAND[@]} vcs-backup.sh serverListRepositories;
   212 }
   213 
   214 # Environment: server
   215 # User: $VCS_BACKUP_MANAGER
   216 vcs_backup_public_serverListRepositories() {
   217 	printRecfileKeyValue "%rec"  "repository";
   218 	printRecfileKeyValue "%type" "bytes int";
   219 	printRecfileKeyValue "%type" "public bool";
   220 	echo;
   221 
   222 	allRepositories | while read d; do
   223 		url=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/url.txt");
   224 		state=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/state.txt");
   225 		vcsType=$(echo "$d" | sed 's@/.*@@g');
   226 		sizeBytes=$(du -sb "$VCS_BACKUP_CURRENT_DIR/$d" | cut -f1);
   227 		[[ -e "$VCS_BACKUP_PUBLIC_DIR/$d" ]] && public="true" || public="false";
   228 		
   229 		if [[ "$vcsType" == "hg"  ]]; then lastCommit=$(hg log --limit 1 --template '{date|isodatesec}' -R "$VCS_BACKUP_CURRENT_DIR/$d" 2>/dev/null);
   230 		elif [[ "$vcsType" == "git" ]]; then lastCommit=$(git -C "$VCS_BACKUP_CURRENT_DIR/$d" log --max-count=1 --pretty="%ai"); 
   231 		else lastCommit=""; fi
   232 		
   233 		printRecfileKeyValue "type"            "$vcsType";
   234 		printRecfileKeyValue "url"             "$url";
   235 		printRecfileKeyValue "state"           "$state";
   236 		printRecfileKeyValue "public"          "$public";
   237 		printRecfileKeyValue "serverPath"      "$VCS_BACKUP_CURRENT_DIR/$d";
   238 		printRecfileKeyValue "size"            "$sizeBytes";
   239 		printRecfileKeyValue "lastCommit"      "$lastCommit";
   240 		echo;
   241 	done
   242 }
   243 
   244 # Environment: server
   245 # User: $VCS_BACKUP_USER
   246 # should be called from cron (usually every day)
   247 vcs_backup_public_serverPullCronTask() {
   248 	printRecfileKeyValue "%rec"  "pull";
   249 	printRecfileKeyValue "%type" "started date";
   250 	printRecfileKeyValue "%type" "finished date";
   251 	printRecfileKeyValue "%type" "duration int";
   252 	printRecfileKeyValue "%type" "resultCode int";
   253 
   254 	allRepositories | while read d; do
   255 		state=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/state.txt");
   256 		vcsType=$(echo "$d" | sed 's@/.*@@g');
   257 		absolutePath="$VCS_BACKUP_CURRENT_DIR/$d";
   258 
   259 		pullStarted=$(date --iso-8601=s);
   260 		pullStartedMiliseconds=$(($(date +%s%N)/1000000));
   261 		pullFinished="";
   262 		pullDuration="";
   263 		pullResult="";
   264 		pullResultCode="";
   265 		if [[ "$state" == "cloned" ]]; then
   266 			if   [[ "$vcsType" == "hg" ]];  then pullResult=$(hg pull --force --repository "$absolutePath" 2>&1); pullResultCode=$?;
   267 			elif [[ "$vcsType" == "git" ]]; then pullResult=$(git -C "$absolutePath" fetch 2>&1); pullResultCode=$?;
   268 			fi
   269 			pullFinished=$(date --iso-8601=s);
   270 			pullFinishedMiliseconds=$(($(date +%s%N)/1000000));
   271 			pullDuration=$(( $pullFinishedMiliseconds - $pullStartedMiliseconds ));
   272 		fi
   273 
   274 		printRecfileKeyValue "serverPath"      "$absolutePath";
   275 		printRecfileKeyValue "type"            "$vcsType";
   276 		printRecfileKeyValue "state"           "$state";
   277 		printRecfileKeyValue "started"         "$pullStarted";
   278 		printRecfileKeyValue "finished"        "$pullFinished";
   279 		printRecfileKeyValue "duration"        "$pullDuration";
   280 		printRecfileKeyValue "resultCode"      "$pullResultCode";
   281 		printRecfileKeyValue "message"         "$pullResult";
   282 		echo;
   283 	done
   284 }
   285 
   286 # Environment: server
   287 # User: root
   288 # should be called from cron (usually every day) after Pull (see above)
   289 vcs_backup_public_serverSnapshotCronTask() {
   290 	printRecfileKeyValue "%rec"  "snapshot";
   291 	printRecfileKeyValue "%type" "started date";
   292 	printRecfileKeyValue "%type" "finished date";
   293 	printRecfileKeyValue "%type" "duration int";
   294 	printRecfileKeyValue "%type" "resultCode int";
   295 	
   296 	allRepositories | while read d; do
   297 		state=$(cat "$VCS_BACKUP_CONFIG_DIR/$d/state.txt");
   298 		vcsType=$(echo "$d" | sed 's@/.*@@g');
   299 		absolutePath="$VCS_BACKUP_CURRENT_DIR/$d";
   300 
   301 		started=$(date --iso-8601=s);
   302 		startedMiliseconds=$(($(date +%s%N)/1000000));
   303 		finished="";
   304 		duration="";
   305 		result="";
   306 		resultCode="";
   307 		snapshotPath="";
   308 		if [[ "$state" == "cloned" ]]; then
   309 			snapshotPath="$VCS_BACKUP_SNAPSHOT_DIR/$d/$(date --iso-8601=date)";
   310 			mkdir -p $(dirname "$snapshotPath");
   311 			result=$(btrfs subvolume snapshot -r "$absolutePath" "$snapshotPath" 2>&1);
   312 			resultCode=$?;
   313 			finished=$(date --iso-8601=s);
   314 			finishedMiliseconds=$(($(date +%s%N)/1000000));
   315 			duration=$(( $finishedMiliseconds - $startedMiliseconds ));
   316 		fi
   317 
   318 		printRecfileKeyValue "currentPath"     "$absolutePath";
   319 		printRecfileKeyValue "snapshotPath"    "$snapshotPath";
   320 		printRecfileKeyValue "type"            "$vcsType";
   321 		printRecfileKeyValue "state"           "$state";
   322 		printRecfileKeyValue "started"         "$started";
   323 		printRecfileKeyValue "finished"        "$finished";
   324 		printRecfileKeyValue "duration"        "$duration";
   325 		printRecfileKeyValue "resultCode"      "$resultCode";
   326 		printRecfileKeyValue "message"         "$result";
   327 		echo;
   328 	done
   329 }
   330 
   331 # --- Single entry-point: --------------------------------------------------------------------------
   332 
   333 loadClientConfigFile;
   334 loadServerConfigFile;
   335 PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
   336 PUBLIC_FUNCTION_PREFIX="vcs_backup_public_";
   337 if type -t "$PUBLIC_FUNCTION_PREFIX$1" > /dev/null; then
   338 	"$PUBLIC_FUNCTION_PREFIX${@:1}";
   339 elif [[ $(basename $0) == "vcs-backup-clone-private-hg"  ]]; then "${PUBLIC_FUNCTION_PREFIX}clientSubmitBackupRequest" hg  "$1" private clone;
   340 elif [[ $(basename $0) == "vcs-backup-clone-private-git" ]]; then "${PUBLIC_FUNCTION_PREFIX}clientSubmitBackupRequest" git "$1" private clone;
   341 elif [[ $(basename $0) == "vcs-backup-clone-public-hg"   ]]; then "${PUBLIC_FUNCTION_PREFIX}clientSubmitBackupRequest" hg  "$1" public  clone;
   342 elif [[ $(basename $0) == "vcs-backup-clone-public-git"  ]]; then "${PUBLIC_FUNCTION_PREFIX}clientSubmitBackupRequest" git "$1" public  clone;
   343 else
   344 	echo "Unsupported sub-command: $1" >&2
   345 	echo "Available sub-commands:" >&2
   346 	declare -F | grep "$PUBLIC_FUNCTION_PREFIX" | sed "s/.*$PUBLIC_FUNCTION_PREFIX/  /g" >&2
   347 	exit 1;
   348 fi