#!/bin/bash
#
# This file contains helper functions for setting up device cgroup in
# the LXC. virsh calls only add the device to the root cgroup.
# New allowed entries are not automatically propagated to child cgroups
# for the "devices" cgroup controller. Add them explicitly.
#
# Copyright (c) 2023 by Cisco Systems, Inc.
# All rights reserved.
#

CG_DEV_CTRL="/sys/fs/cgroup/devices/machine.slice"

# Argument-1: Domain name
# Argument-2: Absolute device path

function setup_dev_cgroup_hierarchy {
    machine_name=lxc-$(cat /var/run/libvirt/lxc/$1.pid)-$1
    devallow_base=$CG_DEV_CTRL/machine-$(systemd-escape "$machine_name").scope

    if [ -b $2 ]; then
        type="b"
    else
        type="c"
    fi

    majornum=$(( $(stat -c 0x'%t' $2) ))
    minornum=$(( $(stat -c 0x'%T' $2) ))

    find "$devallow_base" -name devices.allow -printf "%d %p\n" | sort -n | while read -r depth path; do
        echo "$type $majornum:$minornum rwm" >"$path"
    done
}
