]> git.plutz.net Git - cgilite/blob - storage.sh
bugfix: allow positive return of LOCK()
[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 [ -n "$include_storage" ] && return 0
21 include_storage="$0"
22
23 LOCK(){
24   lock="${1}.lock"
25   timeout="${2-20}"
26   if [ \! -w "${lock%/*}" ] || [ -e "$lock" -a \! -d "$lock" ]; then
27     printf 'Impossible to get lock: %s\n' "$lock" >&2
28     return 1
29   fi
30
31   while ! mkdir "$lock"; do
32     block="$(cat "$lock/pid" || printf 1)"
33     if ! { ps -eo pid |grep -qwF "$block"; }; then
34       printf 'Overriding stale lock: %s\n' "$lock" >&2
35       break
36     fi
37     if [ $timeout -le 0 ]; then
38       printf 'Timeout while trying to get lock: %s\n' "$lock" >&2
39       return 1
40     fi
41     timeout=$((timeout - 1))
42     sleep 1
43   done
44   printf '%i\n' $$ >"${lock}/pid"
45   return 0
46 }
47
48 RELEASE(){
49   lock="${1}.lock"
50   if [ "$(cat "$lock/pid")" = "$$" ]; then
51     rm "$lock/pid"
52     if ! rmdir "$lock"; then
53       printf 'Cannot remove tainted lock: %s\n' "$lock" >&2
54       printf '%i\n' $$ >"${lock}/pid"
55       return 1
56     fi
57     return 0
58   else
59     printf 'Refusing to release foreign lock: %s\n' "$lock" >&2
60     return 1
61   fi
62 }
63
64 STRING(){
65   printf %s "$*" |sed -r '
66     :X; $!{N;bX;}
67     s;\\;\\\\;g;
68     s;\n;\\n;g;
69     s;\t;\\t;g;
70     s;\r;\\r;g;
71   '
72 }
73
74 UNSTRING(){
75   printf %s "$*" |sed -r '
76     :X
77     s;((^|[^\\])(\\\\)*)\\n;\1\n;g;
78     s;((^|[^\\])(\\\\)*)\\t;\1\t;g;
79     s;((^|[^\\])(\\\\)*)\\r;\1\r;g;
80     tX;
81     s;\\\\;\\;g;
82   '
83 }