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