#!/bin/bash
#
# Copyright (c) 2019-2020 Oracle and/or its affiliates. All rights reserved.
# Licensed under the GNU General Public License Version 2 as shown at https://oss.oracle.com/licenses/GPL-2.

# This script locates conmon processes that don't belong to
# cri-o or podman and terminates the contained processes.

# get all pods from crictl
PODS=$(crictl pods -q; crictl ps -q)
CONMONS=$(pgrep conmon)

# make the match string for grep by creating multiple
# regexes, one for each pod.
export MATCH=''
while read POD; do
        export MATCH="$MATCH -e $POD"
done <<< "$(echo -e "$PODS")"

echo PODS
echo "$PODS"
echo MATCHES - "$MATCH"
echo "$CONMONS" | while read CONMON; do
	grep -q -e crio < /proc/$CONMON/cmdline
	if [ $? -ne 0 ]; then
		echo Skipping due to non-crio $CONMON: $(tr '\0' ' ' < /proc/$CONMON/cmdline)
		continue
	fi
        # If there's a match, leave these processes alone
        grep -q $MATCH < /proc/$CONMON/cmdline
        if [ $? -eq 0 ]; then
                echo Skipping $CONMON: $(tr '\0' ' ' < /proc/$CONMON/cmdline)
                continue
        fi

        # get children and smash them
        echo "Children of $CONMON are: $(pgrep -P $CONMON)"
        pkill -9 -P "$CONMON"
done
