forked from kvaps/fake-systemd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
systemctl
executable file
·546 lines (451 loc) · 14.9 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#!/bin/bash
#
# @file systemctl-fake
# @license MIT
# @author kvaps <kvaps at github.com> (c) Copyright 2017
# @author gmt4 <gmt4 at github.com> (c) Copyright 2022
# @git: https://github.com/gmt4/fake-systemd/
#
# upper vars: like UNIT* are in exec_action context
# lower vars: in local function
# camelcase vars: systemd params var
#
PROGNAME=${0##*/}
PROGVERSION=v1.0
PROGAUTHOR=gmt4
PROGURL="https://github.com/gmt4/fake-systemd"
# set -euf
startstopdaemon="$(command -v start-stop-daemon)"
get_unit_file(){
# Check for Alias=unit.service
Alias=$(grep -hr "^Alias=${UNIT}" "${UNIT_PATHS[@]}" 2>/dev/null | sed -n 's/^Alias=//p')
if [ -n "$Alias" ]; then
UNIT="$Alias"
fi
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
}
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
}
read_multioption(){
local option="$1"
(
sed ':a;N;$!ba;s/\\[[:space:]]*\n//g' "$UNIT_FILE" |
grep '^'$option'[= ]' | cut -d '=' -f2- |
sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
) |
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
# TODO: Add more options from:
# https://www.freedesktop.org/software/systemd/man/systemd.unit.html#Specifiers
}
get_unit_wants() {
(
# 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
) | sort -u
}
action_eval(){
echo "${@}" |
while IFS=$'\n' read -r -a i; do
# ignore errors
$(eval echo "$i") || echo
done
}
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 Environement
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)
action_eval "${ExecStartPre[@]}"
action_eval "${ExecStart[@]}"
action_eval "${ExecStartPost[@]}"
elif [ -z "$Type" ] || [[ "${Type,,}" == *"simple"* ]] || [[ "${Type,,}" == *"notify"* ]] || [[ "${Type,,}" == *"forking"* ]] ; then
makepid=""
if [ -z "$PIDFile" ]; then
PIDdir="/run/${UNIT_NAME}"
mkdir -p $PIDdir
[ -n "$User" ] && chown $User $PIDdir
PIDFile="${PIDdir}/${UNIT_NAME}.pid"
makepid="--make-pidfile"
fi
[ -f "$EnvironmentFile" ] && source "$EnvironmentFile"
cmd=("$startstopdaemon --background --start --pidfile $PIDFile $makepid")
[ -f "$WorkingDirectory" ] && cmd+=("--chdir $WorkingDirectory")
[ -n "$User" ] && cmd+=("--chuid $User")
cmd+=(--exec "${ExecStart[0]}" -- "${ExecStart[@]:1}")
action_eval "${ExecStartPre[@]}"
eval "$(echo "${cmd[@]}")"
action_eval "${ExecStartPost[@]}"
else
>&2 echo "Unknown service type $Type"
fi
}
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="/run/${UNIT_NAME}/${UNIT_NAME}.pid"
[ -f "$EnvironmentFile" ] && source "$EnvironmentFile"
# export Environement
for envvar in $Environment; do
eval $(echo "export $envvar")
done
# Stop service
if [ -z "$ExecStop" ] ; then
cmd="$startstopdaemon --stop --pidfile $PIDFile"
[ -n "$User" ] && cmd+=("--chuid $User")
else
cmd="$ExecStop"
[ -n "$User" ] && cmd="runuser -m -u $User -- $cmd"
fi
action_eval "${ExecStopPre[@]}"
eval "$(echo "${cmd[@]}")"
action_eval "${ExecStopPost[@]}"
}
action_restart(){
action_stop
sleep 1
action_start
}
action_show(){
cat $UNIT_FILE
echo MainPID=$(_get_pid)
}
action_reload(){
local User=$(read_option User)
local ExecReload=$(read_multioption ExecReload)
local EnvironmentFile=$(read_option EnvironmentFile | sed 's/^-//')
local Environment=$(read_multioption Environment)
# export Environement
for envvar in $Environment; do
eval $(echo "export $envvar")
done
[ -f "$EnvironmentFile" ] && source "$EnvironmentFile"
cmd="${ExecReload[@]}"
[ -n "$User" ] && cmd="runuser -m -u $User -- $cmd"
eval "$(echo "${cmd[@]}")"
}
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
}
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
}
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
}
action_isactive(){
pid=$(_get_pid)
# set default pifile
[ "$pid" == "-1" ] && echo "unknown" && exit 3
# check if the pid exists - systemctl returns 3
[ -r "/proc/$pid/status" ] || kill -0 "$pid" > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "active"
exit 0
else
echo "inactive"
exit 3
fi
}
_get_pid(){
local PIDFile=$(read_option PIDFile)
local GuessMainPID=$(read_option GuessMainPID)
local ExecStart=($(read_option ExecStart))
GuessMainPID="${GuessMainPID:-yes}"
if [ "$GuessMainPID" == "yes" ];
then
pgrep --oldest -f -- "${ExecStart}" && return
fi
# set default pifile
if [ -z "$PIDFile" ];
then
for PIDFile in "/run/${UNIT_NAME}.pid" "/run/${UNIT_NAME}/${UNIT_NAME}.pid"
do
if [ -f "$PIDFile" ]; then break; fi
done
fi
# now check if the pidfile exists
if [ ! -f "$PIDFile" ]; then
echo "-1"
else
cat "$PIDFile"
fi
}
action_status(){
local Description="$(read_option Description)"
local Documentation="$(read_option Documentation)"
local color_red="\033[1;31m"
local color_green="\033[1;32m"
local color_reset="\033[0m"
local color_curr="$color_reset"
pid=$(_get_pid)
isenabled=$(action_isenabled)
isactive=$(action_isactive)
status="inactive (dead)"
if [ "$isactive" == "failed" ]; then
color_curr=$color_red
status="${color_curr}$isactive${color_reset} (Result: NI)"
elif [ "$isactive" == "active" ]; then
color_curr=$color_green
psdate=$(ps -p "$pid" -o lstart=)
pscmd=($(ps -p "$pid" -o cmd=))
psmem=$(ps -p "$pid" -o %mem= | tr -d ' ')
status="${color_curr}$isactive (running)${color_reset} since $psdate"
fi
echo -e "${color_curr}●${color_reset} $UNIT - $Description"
echo -e " Loaded: loaded ($UNIT_FILE; $isenabled; vendor preset: NI)"
echo -e " Active: $status"
if [ -n "$Documentation" ]; then
echo " Docs: $Documentation"
fi
if [ "$isactive" == "active" ]; then
local ExecStartPre="$(read_multioption ExecStartPre)"
if [ -n "$ExecStartPre" ]; then
echo " Process: $pid ExecStartPre=$ExecStartPre"
fi
echo " Main PID: $pid ($(basename ${pscmd[0]}))"
echo " Memory: $psmem%"
echo " CGroup: /system.slice/$UNIT"
echo " └─$pid ${pscmd[@]}"
fi
echo
}
action_list_units(){
local Description="$(read_option Description)"
local isenabled=$(action_isenabled)
local isactive=$(action_isactive)
printf "$UNIT\t$isenabled $isactive $Description\n"
}
helper_list_units(){
for dir in ${UNIT_PATHS[@]} ;
do
[ -d "$dir" ] && ls -1 $dir
done
}
exec_action(){
local ACTION=$1
local UNIT=$2
[[ "$UNIT" =~ '.' ]] || UNIT="$UNIT.service"
local UNIT_NAME="${UNIT%%.*}"
if [[ $UNIT =~ '@' ]] ; then
local UNIT_INSTANCE="${UNIT##*@}"
local UNIT="${UNIT%%$UNIT_INSTANCE}"
fi
local UNIT_FILE="$(get_unit_file "$UNIT")"
if [ -z "$UNIT_FILE" ] || [ ! -f "$UNIT_FILE" ]
then
>&2 echo "Unit $UNIT could not be found."
return
fi
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)
case "$ACTION" in
status ) action_status ;;
start ) action_start ;;
stop ) action_stop ;;
restart ) action_restart ;;
reload ) action_reload ;;
try-restart) action_isactive && action_restart ;;
reload-or-restart) action_reload || action_restart ;;
enable ) action_enable ;;
disable ) action_disable ;;
is-active ) action_isactive ;;
is-enabled ) action_isenabled ;;
show) action_show ;;
list-units) action_list_units;;
help ) >&2 echo "This command expects one or more unit names. Did you mean --help?" ; return ;;
-h ) usage; return 0 ;;
--help ) usage; return 0 ;;
# exit 0 if unknown operation to avoid errors
# like mask, unmask etc
*) action_unknown "$@" ; exit 1 ;;
esac
}
action_daemonreload()
{
action_nop "$@"
sleep 0.5
}
action_unknown(){
>&2 echo "$PROGNAME: Warning unknown op $*"
}
action_nop(){
>&2 echo "$PROGNAME: Warning nop $*"
}
usage(){
local USAGE="$PROGNAME [OPTIONS...] {COMMAND} ...
$(version)
Query or send control commands to the systemd manager.
Options:
-h --help Show this help
-v --version Show this version.
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
list-units [UNITS...] List 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
"
echo -e "$USAGE"
}
version(){
echo "$PROGNAME (fake) # @version $PROGVERSION (c) $PROGAUTHOR $PROGURL (forks kvaps/fake-systemd)"
}
main(){
local ACTION="$1"
local UNITS="${@:2}"
local UNIT_PATHS=(
/lib/systemd/system/
/etc/systemd/system/
/usr/lib/systemd/system/
)
if [ -z "$UNITS" ];
then
case "$ACTION" in
status|start|stop|restart|reload) ;;
enable|disable|is-active|is-enabled) ;;
daemon-reload) action_daemonreload; return ;;
show) ;;
ls-units) helper_list_units;;
list-units) UNITS=$(helper_list_units);;
'') usage; exit 0 ;;
-h) usage; exit 0 ;;
help) usage; exit 0 ;;
--help) usage; exit 0 ;;
--version) version; exit 0 ;;
*) action_unknown "$@" ; exit 1 ;;
esac
else
case "$ACTION" in
--system) shift; ACTION="$1"; UNITS="${@:2}" ;;
set-environment|unset-environment) action_unknown "$@"; return ;;
esac
fi
if [ -z "$startstopdaemon" ];
then
>&2 echo "$PROGNAME: Error start-stop-daemon not found"
fi
for UNIT in ${UNITS[@]};
do
exec_action $ACTION $UNIT
done
}
main "$@"