forked from kvaps/fake-systemd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystemctl
executable file
·440 lines (367 loc) · 12.8 KB
/
systemctl
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#!/bin/bash
# upper vars: like UNIT* are in exec_action context
# lower vars: in local function
# camelcase vars: systemd params var
# Copy to fake-systemd for process starter
if [ ! -f /usr/bin/fake-systemctl ]; then
cp /usr/bin/systemctl /usr/bin/fake-systemctl
fi
# Add to startup with bashrc
if ! grep -q fake_systemctl_start ~/.bashrc; then
echo '
function fake_systemctl_start() {
echo "==== Fake Systemd Startup ===="
for service in /etc/systemd/system/multi-user.target.wants/*;
do
first=${service##*/}
if [[ $first == *service ]] &&
[[ $first != networking.service ]] &&
[[ $first != rsyslog.service ]] &&
[[ $first != inithooks.service ]] &&
[[ $first != shellinabox.service ]] &&
[[ $first != *stunnel4* ]] &&
[[ $first != rsync.service ]]; then
name=${first/.service}
echo -n "Starting $name... "
fake-systemctl start $name &>> /var/log/fake_systemd.log
if (( $? == 0 )); then
echo "OK"
else
echo "FAIL"
fi
fi
done
echo "==== Done Fake Systemd Startup ===="
}
fake_systemctl_start
' >> ~/.bashrc
fi
if [ ! -d /pids ]; then
mkdir /pids
fi
function get_unit_file(){
for dir in ${UNIT_PATHS[@]} ; do
if [ -f "${dir}${UNIT}" ] ; then
echo "${dir}${UNIT}"
break
fi
if [ -f "${dir}${UNIT}.service" ] ; then
echo "${dir}${UNIT}.service"
break
fi
done
}
function read_option(){
local option="$1"
value="$(grep '^'$option'[= ]' "$UNIT_FILE" | cut -d '=' -f2- | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
value="`
echo $value |
sed -e "s/%[i]/$UNIT_INSTANCE/g" \
-e "s/%[I]/\"$UNIT_INSTANCE\"/g" \
-e "s/%[n]/$UNIT_FULL/g" \
-e "s/%[N]/\"$UNIT_FULL\"/g"
`"
# TODO: Add more options from:
# https://www.freedesktop.org/software/systemd/man/systemd.unit.html#Specifiers
if [ -n "$value" ]; then
echo $value
return
else
for include in $(grep '^.include' "$UNIT_FILE" | sed 's/^\.include[[:space:]]*//'); do
recurse_value=$(UNIT_FILE=$include read_option $option)
if [ -n "$recurse_value" ]; then
echo $recurse_value
return
fi
done
fi
}
function read_multioption(){
local option="$1"
while IFS= read -r line; do
echo "$line" |
sed -e "s/%[i]/$UNIT_INSTANCE/g" \
-e "s/%[I]/\"$UNIT_INSTANCE\"/g" \
-e "s/%[n]/$UNIT_FULL/g" \
-e "s/%[N]/\"$UNIT_FULL\"/g"
done < <( sed ':a;N;$!ba;s/\\[[:space:]]*\n//g' "$UNIT_FILE" | grep '^'$option'[= ]' | cut -d '=' -f2- | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' )
# TODO: Add more options from:
# https://www.freedesktop.org/software/systemd/man/systemd.unit.html#Specifiers
}
function get_unit_wants() {
sort -u <<< `(
# Print wants from UNIT_PATHS
for DIR in ${UNIT_PATHS[@]} ; do
if [ -d "${DIR}${UNIT}.wants" ] ; then
ls -1 "${DIR}${UNIT}.wants/" | tr '\n' ' '
fi
done
# Print wants from unit-file
read_option Wants $UNIT_FILE
)`
}
function action_start(){
# Start depended services
for unit in ${UNIT_WANTS[@]}; do
exec_action start $unit
done
# Load options
local User=$(read_option User)
local Type=$(read_option Type)
local PIDFile=$(read_option PIDFile)
local EnvironmentFile=$(read_option EnvironmentFile | sed 's/^-//')
local WorkingDirectory=($(read_option WorkingDirectory))
local ExecStart=($(read_option ExecStart))
local ExecStartPre=$(read_multioption ExecStartPre)
local ExecStartPost=$(read_multioption ExecStartPost)
local Environment=$(read_multioption Environment)
# export Environnement
for envvar in $Environment; do
eval $(echo "export $envvar")
done
# From doc: oneshot are the only service units that may have more than one
# ExecStart= specified. They will be executed in order until either they
# are all successful or one of them fails.
# Note that systemd will consider the unit to be in the state "starting"
# until the program has terminated, so ordered dependencies will wait
# for the program to finish before starting themselves. The unit will
# revert to the "inactive" state after the execution is done, never
# reaching the "active" state. That means another request to start
# the unit will perform the action again.
if [[ "${Type,,}" == *"oneshot"* ]]; then
local ExecStart=$(read_multioption ExecStart)
while IFS=$'\n' read -a i; do
# ignore errors
$(eval echo "$i") || echo
done <<< "${ExecStartPre[@]}"
while IFS=$'\n' read -a i; do
# ignore errors
$(eval echo "$i") || echo
done <<< "${ExecStart[@]}"
while IFS=$'\n' read -a i; do
$(eval echo "$i")
done <<< "${ExecStartPost[@]}"
elif [ -z $Type ] || [[ "${Type,,}" == *"simple"* ]] || [[ "${Type,,}" == *"notify"* ]] || [[ "${Type,,}" == *"forking"* ]] ; then
makepid=""
if [ -z "$PIDFile" ]; then
PIDdir="/pids/${UNIT_NAME}"
mkdir -p $PIDdir
[ -n "$User" ] && chown $User $PIDdir
PIDFile="${PIDdir}/${UNIT_NAME}.pid"
makepid="--make-pidfile"
fi
[ -f "$EnvironmentFile" ] && source "$EnvironmentFile"
cmd=("$(which start-stop-daemon) --background --start --pidfile $PIDFile $makepid")
[ -f "$WorkingDirectory" ] && cmd+=("--chdir $WorkingDirectory")
[ -n "$User" ] && cmd+=("--chuid $User")
cmd+=(--exec "${ExecStart[0]}" -- "${ExecStart[@]:1}")
while IFS=$'\n' read -a i; do
# ignore errors
$(eval echo "$i") || echo
done <<< "${ExecStartPre[@]}"
eval "$(echo "${cmd[@]}")"
while IFS=$'\n' read -a i; do
# ignore errors
$(eval echo "$i") || echo
done <<< "${ExecStartPost[@]}"
else
>&2 echo "Unknown service type $Type"
fi
}
function action_stop(){
# Load options
local User=$(read_option User)
local Type=$(read_option Type)
local PIDFile=$(read_option PIDFile)
local EnvironmentFile=$(read_option EnvironmentFile | sed 's/^-//')
local ExecStop=$(read_option ExecStop)
local ExecStopPre=$(read_multioption ExecStopPre)
local ExecStopPost=$(read_multioption ExecStopPost)
local Environment=$(read_multioption Environment)
[ -z "$PIDFile" ] && PIDFile="/pids/${UNIT_NAME}/${UNIT_NAME}.pid"
[ -f "$EnvironmentFile" ] && source "$EnvironmentFile"
# export Environnement
for envvar in $Environment; do
eval $(echo "export $envvar")
done
# Stop service
if [ -z "$ExecStop" ] ; then
cmd="$(which start-stop-daemon) --stop --pidfile $PIDFile"
[ -n "$User" ] && cmd+=("--chuid $User")
else
cmd="$ExecStop"
[ -n "$User" ] && cmd="runuser -m -u $User -- $cmd"
fi
while IFS=$'\n' read -a i; do
# ignore errors
$(eval echo "$i") || echo
done <<< "${ExecStopPre[@]}"
eval "$(echo "${cmd[@]}")"
while IFS=$'\n' read -a i; do
# ignore errors
$(eval echo "$i") || echo
done <<< "${ExecStopPost[@]}"
}
function action_restart(){
action_stop
sleep 1
action_start
}
function action_enable(){
local WantedBy=$(read_option WantedBy)
if [ -z $WantedBy ] ; then
>&2 echo "Unit $UNIT have no WantedBy option."
exit 1
fi
local WANTEDBY_DIR="/etc/systemd/system/$WantedBy.wants"
if [ ! -f "$WANTEDBY_DIR/$UNIT_FULL" ] ; then
mkdir -p $WANTEDBY_DIR
echo Created symlink from $WANTEDBY_DIR/$UNIT_FULL to $UNIT_FILE.
ln -s $UNIT_FILE $WANTEDBY_DIR/$UNIT_FULL
fi
}
function action_disable(){
local WantedBy=$(read_option WantedBy)
if [ -z $WantedBy ] ; then
>&2 echo "Unit $UNIT have no WantedBy option."
exit 1
fi
local WANTEDBY_DIR="/etc/systemd/system/$WantedBy.wants"
if [ -f "$WANTEDBY_DIR/$UNIT_FULL" ] ; then
echo Removed $WANTEDBY_DIR/$UNIT_FULL.
rm -f $WANTEDBY_DIR/$UNIT_FULL
rmdir --ignore-fail-on-non-empty $WANTEDBY_DIR
fi
}
function action_isenabled(){
local WantedBy=$(read_option WantedBy)
if [ -z $WantedBy ] ; then
echo "unknown"
else
local WANTEDBY_DIR="/etc/systemd/system/$WantedBy.wants"
if [ -f "$WANTEDBY_DIR/$UNIT_FULL" ] ; then
echo "enabled"
exit 0
else
echo "disabled"
exit 1
fi
fi
}
function action_isactive(){
pid=$(_get_pid)
# set default pifile
[ "$pid" == "-1" ] && echo "unknown" && exit 3
# check if the pid exists - systemctl returns 3
kill -0 $pid > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "active"
exit 0
else
echo "failed"
exit 3
fi
}
function _get_pid(){
local PIDFile=$(read_option PIDFile)
# set default pifile
[ -z "$PIDFile" ] && PIDFile="/pids/${UNIT_NAME}/${UNIT_NAME}.pid"
# now check if the pidfile exists
if [ ! -f "$PIDFile" ]; then
echo "-1"
else
cat $PIDFile
fi
}
function action_status(){
local Description=$(read_option Description)
local Documentation=$(read_option Documentation)
pid=$(_get_pid)
isenabled=$(action_isenabled)
isactive=$(action_isactive)
status="inactive (dead)"
if [ $isactive == "failed" ]; then
status="failed (Result: not_implemented)"
elif [ $isactive == "active" ]; then
psdate=$(ps -p $pid -o lstart=)
pscmd=($(ps -p $pid -o cmd=))
psmem=$(ps -p $pid -o %mem= | tr -d ' ')
status="active (running) since $psdate"
fi
echo "● $UNIT - $Description"
echo " Loaded: loaded ($UNIT_FILE; $isenabled; vendor preset: not_implemented)"
echo " Active: $status"
if [ $isactive == "active" ]; then
if [ ! -z $Documentation ]; then
echo " Docs: $Documentation"
fi
echo " Main PID: $pid ($(basename ${pscmd[0]}))"
echo " Memory: $psmem%"
echo " CGroup: /system.slice/$UNIT"
echo " └─$pid ${pscmd[@]}"
fi
echo
}
function exec_action(){
local ACTION=$1
local UNIT=$2
[[ $UNIT =~ '.' ]] || UNIT="$UNIT.service"
local UNIT_NAME=$(echo $UNIT | cut -d '.' -f1)
if [[ $UNIT =~ '@' ]] ; then
local UNIT_INSTANCE=`echo $UNIT | cut -d'@' -f2- | cut -d. -f1`
local UNIT=`echo $UNIT | sed "s/$UNIT_INSTANCE//"`
fi
local UNIT_FILE=`get_unit_file $UNIT`
local UNIT_FULL=`echo $UNIT | sed "s/@/@$UNIT_INSTANCE/"`
local UNIT_WANTS=(`get_unit_wants $UNIT`)
# Systemd env variables
# https://www.freedesktop.org/software/systemd/man/systemd.service.html
local MAINPID=$(_get_pid)
if [ -z $UNIT_FILE ] ; then
>&2 echo "Failed to $ACTION $UNIT: Unit $UNIT not found."
exit 1
else
case "$ACTION" in
status ) action_status ;;
start ) action_start ;;
stop ) action_stop ;;
restart ) action_restart ;;
enable ) action_enable ;;
disable ) action_disable ;;
is-active ) action_isactive ;;
is-enabled ) action_isenabled ;;
help ) >&2 echo "This command expects one or more unit names. Did you mean --help?" ; exit 1 ;;
-h ) echo $USAGE ; exit 0 ;;
--help ) echo $USAGE ; exit 0 ;;
# exit 0 if unknown operation to avoid errors
# like mask, unmask etc
* ) >&2 echo "Unknown operation '$ACTION'" ; exit 0 ;;
esac
fi
}
function main(){
local USAGE="systemctl [OPTIONS...] {COMMAND} ...
Query or send control commands to the systemd manager.
-h --help Show this help
Unit Commands:
start NAME... Start (activate) one or more units
stop NAME... Stop (deactivate) one or more units
restart NAME... Start or restart one or more units
is-active PATTERN... Check whether units are active
status [PATTERN...|PID...] Show runtime status of one or more units
Unit File Commands:
enable NAME... Enable one or more unit files
disable NAME... Disable one or more unit files
is-enabled NAME... Check whether unit files are enabled
"
local ACTION="$1"
local UNITS="${@:2}"
local UNIT_PATHS=(
/etc/systemd/system/
/usr/lib/systemd/system/
)
for UNIT in ${UNITS[@]}; do
exec_action $ACTION $UNIT
done
}
main $@