forked from Wizcorp/libbash
-
Notifications
You must be signed in to change notification settings - Fork 1
/
memcached.sh
171 lines (133 loc) · 2.64 KB
/
memcached.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/bin/sh
if [ "$MB_SERVER" == "" ]; then
export MB_SERVER="localhost"
fi
if [ "$MB_PORT" == "" ]; then
export MB_PORT="11211"
fi
mbGet(){
keys=$(mbGetKey $@)
mbQuery "get $keys"
}
mbDel(){
key=$(mbGetKey ${1:-})
mbQuery "delete $key"
}
mbTouch(){
key=$(mbGetKey ${1:-})
OPTIND=2;
mbGetOpts $@;
mbQuery "touch $key $TTL"
}
mbIncr(){
key=$(mbGetKey ${1:-})
value=${2:-}
mbQuery "incr $key $value"
}
mbDecr(){
key=$(mbGetKey ${1:-})
value=${2:-}
mbQuery "decr $key $value"
}
mbSet(){
mbDataCommand "set" $@
}
mbAdd(){
mbDataCommand "add" $@
}
mbReplace(){
mbDataCommand "replace" $@
}
mbAppend(){
mbDataCommand "append" $@
}
mbPrepend(){
mbDataCommand "prepend" $@
}
mbDataCommand(){
# Options
command=${1:-};
key=$(mbGetKey ${2:-} | sed "s/ $//")
value="${3:-}"
dataFile="/tmp/mbCommand_$(uuidgen)";
if [ "${3:-}" == "" -o "$(echo ${3:-} | grep "^-")" != "" ]; then
OPTIND=3;
cat - > $dataFile;
else
OPTIND=4;
echo -n ${3:-} > $dataFile;
fi
mbGetOpts $@;
if [ "${3:-}" == "$(cat $dataFile)" ]; then
len=$(($(cat $dataFile | wc -c)))
elif [ "$(grep $dataFile)" == "" ]; then
len=$(($(cat $dataFile | wc -c)-1))
else
len=$(($(cat $dataFile | wc -c)))
fi
# Run
mbQuery "set $key $FLAGS $TTL $len"
# Cleanup
rm -rf $dataFile
unset dataFile;
unset value;
unset key;
mbCleanOpts
}
mbGetOpts(){
TTL=0;
FLAGS=0;
while getopts "t:f:" OPTION; do
case $OPTION in
t)
TTL="$OPTARG"
;;
f)
FLAGS="$OPTARG"
;;
esac
done
}
mbCleanOpts(){
unset TTL;
unset FLAGS;
}
mbGetKey(){
if [ "$MB_PREFIX" == "" ]; then
for key in $@; do
echo -n "$key "
done
else
for key in $@; do
echo -n "$MB_PREFIX/$key "
done
fi
}
mbQuery(){
for query in "$@"; do
mbBuildQuery "$query" | nc $MB_SERVER $MB_PORT
done
}
mbBuildQuery(){
echo -en "${1:-}\r\n";
if [ "$dataFile" != "" ]; then
if [ -f $dataFile ]; then
cat $dataFile | sed "\$s/\$//" | sed "\$s/$/\\r\\nquit\\r\\n/";
else
echo "Could not find dataFile!" >&2;
fi
else
echo -en "quit\r\n";
fi
}
mbExtract(){
cat - | sed "1 d;$ d;\$s/\r\n\$//";
}
mbExtractTest(){
dataFile="/tmp/mbCommand_$(uuidgen)";
cat - | tee $dataFile | sed "1 d;$ d;\$s/\r\n\$//";
meta=$(head -n1 < $dataFile && rm $dataFile);
mb_key=$(echo $meta | cut -d" " -f2);
mb_flag=$(echo $meta | cut -d" " -f3);
mb_size=$(echo $meta | cut -d" " -f4);
}