#!/usr/bin/python3

# 2025 marc.o.sandlus@hostsharing.net


#################################################
# Konfiguration

DEBUG = False

LOG_DIR = '/var/log/hostsharing/hs-log-pac-memory2'

MEMORY_BOOKING_UNIT = 128 * 1024 ** 2

#################################################

import os, time, subprocess, datetime, sys, tempfile, shutil, re, math


def hostname():
    return open('/etc/hostname', 'r').read().strip()


def vmXXXX():
    res = hostname()
    if res.startswith('h') and len(res) == 3:
        res = 'vm10' + res[1:]
    return res


def is_hs_shared_hive():
    # TODO Infos aus hsdb holen
    return hostname() in {'h01', 'h02', 'h03', 'h04', 'h05', 'h06', 'h07', 'h08', 'h20', 'h93', 'h94'}


def hsdb_pacs_by_name_hive():
    """Return a sorted list of all Hostsharing Packets on this hive.
    """
    res = []
    hive = hostname()
    cmd = ['/usr/local/sbin/hsdb', '--cmd=pacs_by_name', f'--hive={hive}', "--arg=*"]
    if DEBUG:
        print(cmd)
    out = subprocess.run(cmd, capture_output=True, text=True)
    if DEBUG:
        print(out)

    if out and out.stdout:
        for l in out.stdout.splitlines():
            l = l.rstrip()

            if len(l) == 5:  # != 'vmXXXX'
                res.append(l)

    return sorted(res)


def prettytable2str(table, vsep=' ', colalign='l'):
    s = []
    columns = len(table[0])

    if len(colalign) == 1:
        colalign = colalign * columns

    max_widths = [0] * columns
    for row in table:
        for c, col in enumerate(row):
            max_widths[c] = max(max_widths[c], len(str(col)))

    for row in table:
        l = []
        for c, col in enumerate(row):
            if colalign[c] == 'l':
                l.append(str(col) + ' ' * (max_widths[c] - len(str(col))))

            elif colalign[c] == 'r':
                l.append(' ' * (max_widths[c] - len(str(col))) + str(col))

        s.append(vsep.join(l))

    return '\n'.join(s)


def memory_format(mem, unit=1024 ** 2):
    if mem is None:
        res = '---'
    elif mem == 'max':
        res = mem
    else:
        res = '{}'.format(math.ceil(mem / unit))

    return res


def get_cgroup(pid):
    """Return cgroup of process with given pid.
    """
    cgroup = None

    if os.path.exists(f'/proc/{pid}/cgroup'):
        try:
            cgroup = open(f'/proc/{pid}/cgroup').read()
        except ProcessLookupError:
            pass

    return cgroup


def is_cgroup_in_pacs_slice(cgroup, username):
    """Return True iff given cgroup is in pacs-<pac>.slice.
    """
    # 0::/pacs.slice/pacs-hsh03.slice/user@115063.service/app.slice/hsadminng.service

    pac = get_pac(username)
    return cgroup.startswith(f'0::/pacs.slice/pacs-{pac}.slice/')


def is_ram_accounting_enabled():
    res = None
    if os.path.exists('/etc/salt/grains'):
        with open('/etc/salt/grains', 'r') as f:
            for l in f:
                if l.startswith('ram_accounting_enabled:'):
                    res = l.split(':', 1)[-1].strip() == 'True'
                    break

    return res


def get_cgroup_memory(pac):
    res = {'memory.current': None, 'memory.high': None, 'memory.max': None,
           'memory.pressure': None, 'memory.pressure.some': None, 'memory.pressure.full': None,
           'memory.swap.current': None, 'memory.swap.max': None}

    for key in {'memory.current', 'memory.high', 'memory.max',
                'memory.pressure', 'memory.swap.current', 'memory.swap.max'}:
        if os.path.exists(f'/sys/fs/cgroup/pacs.slice/pacs-{pac}.slice/{key}'):
            res[key] = open(f'/sys/fs/cgroup/pacs.slice/pacs-{pac}.slice/{key}', 'r').read().rstrip()

    for key in {'memory.current', 'memory.high', 'memory.max', 'memory.swap.current',
                'memory.swap.max'}:
        try:
            res[key] = math.ceil(int(res[key]) / 1024 ** 2)
        except:
            pass

    if 'memory.pressure' in res and res['memory.pressure']:
        tmp = res['memory.pressure'].splitlines()
        assert tmp[0].startswith('some avg10=')
        assert tmp[1].startswith('full avg10=')
        res['memory.pressure.some'] = tmp[0].split('avg60=', 1)[-1].split(' ', 1)[0]
        res['memory.pressure.full'] = tmp[1].split('avg60=', 1)[-1].split(' ', 1)[0]

    return res


def get_cgroup_memory_limits(pac):
    res = {'MemoryMax': None, 'MemoryHigh': None, 'MemorySwapMax': None, 'hsadmin.pacram': None,
           'hsadmin.pacnumusers': None}

    # h93:~# cat /etc/systemd/system/pacs-mos00.slice
    # [Unit]
    # Description=Hostsharing Packet mos00 Slice
    # Before=slices.target
    #
    # [Slice]
    # MemoryMax=19232M
    # MemoryHigh=131075M
    # hsadmin.pacram=131072M
    # hsadmin.pacnumusers=3

    # [Unit]
    # Description=Hostsharing Packet mos01 Slice
    # Before=slices.target
    #
    # [Slice]
    # MemoryMax=19232M
    ##MemoryHigh=17M
    ##MemoryMax=34M
    ##hsadmin.pacram=0M
    ##hsadmin.pacnumusers=17

    if os.path.exists(f'/etc/systemd/system/pacs-{pac}.slice'):
        with open(f'/etc/systemd/system/pacs-{pac}.slice', 'r') as f:
            for l in f:
                if DEBUG:
                    print(l.rstrip())

                if (l.startswith('MemoryMax=')
                        or l.startswith('MemoryHigh=')
                        or l.startswith('MemorySwapMax=')
                        or l.startswith('#hsadmin.pacram=')
                        or l.startswith('#hsadmin.pacnumusers=')
                        or l.startswith('#hsadmin.pacnumuserslingering=')
                ):
                    key, value = l.rstrip().split('=', 1)
                    key = key.lstrip('#')

                    if value.endswith('M'):
                        value = int(value.rstrip('M')) * 1024 ** 2

                    else:
                        value = int(value)

                    res[key] = value

    # TODO es sollte meiner Meinung nach nicht für jeden User des Webpakets extra RAM reserveriert werden
    # sondern nur für diejenigen User, die "lingering" aktiviert haben
    # verwende für die Einführungsphase extra Variable hsadmin.pacnumuserslingering statt hsadmin.pacnumusers
    if 'hsadmin.pacnumuserslingering' in res:
        res['hsadmin.pacnumusers'] = res['hsadmin.pacnumuserslingering']

    if DEBUG:
        print(res)

    return res


def get_smem(pac):
    res = {'proccount': None, 'usercount': None, 'swap': None, 'uss': None, 'pss': None, 'rss': None}
    # smem -U fcz00 -t -u -n -H
    # User     Count     Swap      USS      PSS      RSS
    # 113016       2     9784       12       14     3976
    # 113622       2     9740       12       14     3960
    # 113017       2     9400     1624     2479     8480
    # ---------------------------------------------------
    #             6    28924     1648     2507    16416
    cmd = ['/usr/bin/smem', '-U', pac, '-t', '-u', '-n', '-H']
    out = subprocess.run(cmd, capture_output=True, text=True)

    if out and out.stdout:
        lastline = None
        usercount = 0
        for l in out.stdout.splitlines():
            if l.startswith('User'):
                pass

            elif l.startswith('----'):
                assert lastline is None
                lastline = True

            elif lastline is True:
                lastline = l
                values = re.findall(r'\b[0-9]+\b', lastline)
                res['proccount'], res['swap'], res['uss'], res['pss'], res['rss'] = tuple(int(v) for v in values)
                res['usercount'] = usercount

            else:
                assert lastline is None
                usercount += 1

    return res


if __name__ == '__main__':
    if not os.path.exists(LOG_DIR):
        os.mkdir(LOG_DIR)

    hour = datetime.datetime.now().hour

    pacs = hsdb_pacs_by_name_hive()
    while datetime.datetime.now().hour == hour:
        statistics = [
            ['Zeit', 'pac', 'HS-Einheiten', 'HS-pacram', 'HS-User', 'HS-MemHigh', 'HS-MemMax', 'HS-SwapMemMax',
             'MemHigh', 'MemMax', 'MemSwapMax', 'MemCurrent', 'MemDiff', 'perc',
             'MemPressSome', 'MemPressFull',
             'smemUser', 'smemProc', 'smemSwap', 'smemUSS', 'smemPSS', 'smemRSS'
             ]]

        s = datetime.datetime.now().second
        if s < 5:
            time.sleep(5 - s)

        now = datetime.datetime.now()
        for pac in pacs:
            cgroup_memory = get_cgroup_memory(pac)

            if DEBUG:
                print(f"cgroup_memory={cgroup_memory}")

            if True:
                memlimits = get_cgroup_memory_limits(pac)
                smem = get_smem(pac)

                statistics.append([now.strftime('%Y-%m-%d %H:%M:%S'),
                                   pac,
                                   int(memlimits["hsadmin.pacram"] / MEMORY_BOOKING_UNIT),  # HS-Einheiten
                                   memory_format(memlimits["hsadmin.pacram"]),  # HS-pacram
                                   memlimits["hsadmin.pacnumusers"],  # HS-User
                                   memory_format(memlimits["MemoryHigh"]),  # HS-MemHigh
                                   memory_format(memlimits["MemoryMax"]),  # HS-MemMax
                                   memory_format(memlimits["MemorySwapMax"]),  # HS-MemSwapMax
                                   memory_format(cgroup_memory["memory.high"], unit=1),  # MemHigh
                                   memory_format(cgroup_memory["memory.max"], unit=1),  # MemMax
                                   memory_format(cgroup_memory["memory.swap.max"], unit=1),  # MemSwapMax
                                   memory_format(cgroup_memory["memory.current"], unit=1),  # MemCurrent
                                   cgroup_memory["memory.high"] - cgroup_memory['memory.current'] if cgroup_memory[
                                                                                                         "memory.high"] not in [
                                                                                                         'max',
                                                                                                         None] else '---',
                                   # MemDiff
                                   f'{cgroup_memory["memory.current"] * 100 / cgroup_memory["memory.high"]:3.2f}%' if
                                   cgroup_memory["memory.high"] not in ['max', None] else '---',  # perc
                                   cgroup_memory["memory.pressure.some"],  # MemPressSome
                                   cgroup_memory["memory.pressure.full"],  # MemPressFull
                                   smem["usercount"],
                                   smem["proccount"],
                                   memory_format(smem["swap"], unit=1024),
                                   memory_format(smem["uss"], unit=1024),
                                   memory_format(smem["pss"], unit=1024),
                                   memory_format(smem["rss"], unit=1024),
                                   ])

        f = tempfile.NamedTemporaryFile(mode='w', delete=False)
        f.write(prettytable2str(statistics, vsep='; ', colalign='llrrrrrrrrrrrrrrrrrrrr'))
        f.close()

        logf = f'{LOG_DIR}/{vmXXXX()}-{now.strftime("%Y%m%d-%H%M%S")}'
        shutil.move(f.name, logf)
        os.chmod(logf, 0o660)
        shutil.chown(logf, group='adm')

        time.sleep(60 - datetime.datetime.now().second)
