service-ids-check: Add check uid/gid of services
[src/qa-testdefinitions.git] / common / scripts / service-ids-check.sh
1 #!/bin/bash
2 #-----------------------------------------------------
3 # This scripts allows to check the ids (user and/or group)
4 # of running services.
5 # It doesn't check that the service runs because this is
6 # the object of other tests.
7 # If a process doesn't run it emits an unknown status for
8 # the service, but not a fail.
9 # When there are multiple instance of a service, it checks
10 # that at least one instance matches expectation.
11 # Author: jose.bollo@iot.bzh
12 #-----------------------------------------------------
13
14 # out of LAVA run
15 if ! type lava-test-case 2>/dev/null; then
16         lava-test-case() { echo "lava-test-case $*"; }
17 fi
18 if ! type lava-test-set 2>/dev/null; then
19         lava-test-set() { echo "lava-test-set $*"; }
20 fi
21
22 # extraction of numeric ids for user and group
23 get-id() {
24         local id="$1" file="$2"
25         if grep -q "^${id}:" "$file"; then
26                 grep "^${id}:" "$file" | cut -d: -f3
27         else
28                 echo -n "$id"
29         fi
30 }
31 get-uid() { get-id "$1" /etc/passwd; }
32 get-gid() { get-id "$1" /etc/group; }
33
34 # extraction of numeric effective ids of processes
35 get-p-id() {
36         local pid="$1" field="$2"
37         grep "$field" "/proc/$pid/status" | cut -f3
38 }
39 get-p-uid() { get-p-id "$1" "Uid:"; }
40 get-p-gid() { get-p-id "$1" "Gid:"; }
41
42 # check the process status
43 check-p-ids() {
44         local pid="$1" uid="$2" gid="$3"
45         local u=$(get-p-uid "$pid")
46         local g=$(get-p-gid "$pid")
47         [[ -z "$uid" || "$uid" -eq "$u" ]] && [[ -z "$gid" || "$gid" -eq "$g" ]]
48 }
49 check-user-group() {
50         local service="$1" user="$2" group="$3"
51         local name="${service}-${user}-${group}"
52         local pid uid=$(get-uid "$user") gid=$(get-gid "$group")
53
54         if ! pgrep -c "^$service\$" > /dev/null 2>&1; then
55                 lava-test-case "$name" --result unknown
56                 return 0
57         fi
58
59         for pid in $(pgrep "^$service\$"); do
60                 if check-p-ids "$pid" "$uid" "$gid"; then
61                         lava-test-case "$name" --result pass
62                         return 0
63                 fi
64         done
65         lava-test-case "$name" --result fail
66         return 1
67 }
68 check-user() { check-user-group "$1" "$2" ""; }
69 check-group() { check-user-group "$1" "" "$2"; }
70
71 # the test effective
72 lava-test-set start check-services-user-group
73
74 check-user-group        weston          display         display
75
76 lava-test-set stop check-services-user-group
77
78 exit 0