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