]> git.plutz.net Git - cgilite/blob - storage.sh
locking functions
[cgilite] / storage.sh
1 #!/bin/sh
2
3 # Copyright 2018 Paul Hänsch
4 #
5 # This is a file format helper, part of CGIlite.
6
7 # CGIlite is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # CGIlite is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with CGIlite.  If not, see <http://www.gnu.org/licenses/>. 
19
20 LOCK(){
21   lock="${1}.lock"
22   timeout="${2-20}"
23   if [ \! -w "${lock%/*}" ] || [ -e "$lock" -a \! -d "$lock" ]; then
24     printf 'Impossible to get lock: %s\n' "$lock" >&2
25     return 1
26   fi
27
28   while ! mkdir "$lock"; do
29     block="$(cat "$lock/pid" || printf 1)"
30     if ! { ps -eo pid |grep -qwF "$block"; }; then
31       printf 'Overriding stale lock: %s\n' "$lock" >&2
32       break
33     fi
34     if [ $timeout -le 0 ]; then
35       printf 'Timeout while trying to get lock: %s\n' "$lock" >&2
36       return 1
37     fi
38     timeout=$((timeout - 1))
39     sleep 1
40   done
41   printf '%i\n' $$ >"${lock}/pid"
42   return 1
43 }
44
45 RELEASE(){
46   lock="${1}.lock"
47   if [ "$(cat "$lock/pid")" = "$$" ]; then
48     rm "$lock/pid"
49     if ! rmdir "$lock"; then
50       printf 'Cannot remove tainted lock: %s\n' "$lock" >&2
51       printf '%i\n' $$ >"${lock}/pid"
52       return 1
53     fi
54   else
55     printf 'Refusing to release foreign lock: %s\n' "$lock" >&2
56     return 1
57   fi
58 }
59
60 STRING(){
61   printf %s "$*" |sed -r '
62     :X; $!{N;bX;}
63     s;\\;\\\\;g;
64     s;\n;\\n;g;
65     s;\t;\\t;g;
66     s;\r;\\r;g;
67   '
68 }
69
70 UNSTRING(){
71   printf %s "$*" |sed -r '
72     :X
73     s;((^|[^\\])(\\\\)*)\\n;\1\n;g;
74     s;((^|[^\\])(\\\\)*)\\t;\1\t;g;
75     s;((^|[^\\])(\\\\)*)\\r;\1\r;g;
76     tX;
77     s;\\\\;\\;g;
78   '
79 }