#!/usr/bin/python3

# 2025 marc.o.sandlus@hostsharing.net

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

DEBUG = False

TIMESTAMP_DIR = '/var/lib/hostsharing/hs-check-pac-daemons'

# zu Testzwecken wird die Warn-E-Mail ggfs. an diesen Paket-Nutzer umgelenkt:
OVERRIDE_RECIPIENT_PAC = None  # 'mos00'
# OVERRIDE_RECIPIENT_PAC = 'mos00'
WARN_PERIOD_HOURS = 25

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


import psutil, os, re, time, subprocess, datetime, math, argparse, sys, pathlib, glob, pwd
import pprint


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


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


def hsdb_addr_get(member):
    """Return addr_get for given member.
    """
    res = {}
    cmd = ['/usr/local/sbin/hsdb', '--cmd=addr_get', f"--arg=hsh00-{member}"]
    if DEBUG:
        print(cmd)
    out = subprocess.run(cmd, capture_output=True, text=True)
    if DEBUG:
        print(out)

    if out.stdout:
        for l in out.stdout.splitlines():
            key, value = l.rstrip().split('=', 1)
            assert value.startswith("'") and value.endswith("'")
            res[key] = value[1:-1]

    return res


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 hs_mailto_member(pac, subject, body, nocc=False):
    # echo "Test" | mailto-member - mos00 "Test-Mail"
    # ==> Hallo Herr Sandlus,
    #
    # Test
    #
    # Alles Gute wÃ¼nschen
    #	die Hostsharing Hostmaster
    #
    # --
    # Hostsharing Service | https://www.hostsharing.net
    # Telefon: +49 40 2093313-11 | E-Mail: service@hostsharing.net
    # Hostsharing eG | Flughafenstr. 52a | 22335 Hamburg | Germany
    # Registergericht Hamburg, GnR 1007 | UID: DE218602793
    # Vorstand: Michael Hierweck, Gudio Schnepp

    if OVERRIDE_RECIPIENT_PAC:
        pac = OVERRIDE_RECIPIENT_PAC
        nocc = True

    cmd = ['/usr/local/sbin/mailto-member'] + (['--nocc'] if nocc else []) + ['-', pac, subject]
    subprocess.run(cmd, input=body, text=True, encoding='iso-8859-1')


def prettytable2str(table, vsep=' '):
    s = []
    columns = len(table[0])
    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):
            l.append(str(col) + ' ' * (max_widths[c] - len(str(col))))
        s.append(vsep.join(l))

    return '\n'.join(s)


def hs_mailto_member_warning(pac, procs, crontabs):
    # 234567890123456789012345678901234567890123456789012345678901234567890
    proctable = [['PID', 'Startzeit', 'Username', 'Befehlszeile']]

    if pac in procs:
        for procid in sorted(procs[pac].keys()):
            p = procs[pac][procid]
            if p["cgroup"] == '0::/system.slice/cron.service':
                cmdline = '(cron) '

            else:
                # cmdline = '(' + p["exe"] + ') '
                cmdline = ''

            cmdline += p["cmdline"][:50]

            proctable.append([p["pid"],
                              datetime.datetime.fromtimestamp(p["created"]).strftime('%Y-%m-%d %H:%M:%S'),
                              p["username"], cmdline])

    if pac in crontabs:
        proctable.extend(crontab2proctable(crontabs, pac))

    assert proctable

    proctable = prettytable2str(proctable)

    body = f"""seit dem 15.01.2025 unterstützt die Hostsharing eG im Managed Webspace
nur noch Serverdienste, die von systemd gestartet/verwaltet werden,
siehe Mitteilung vom 02.12.2024 auf unserer Mailingliste
"Operations Announce".

Cron, Monit, Supervisor und etwaige andere Tools werden nicht mehr 
unterstützt.

Eine automatische Stichprobe hat mindestens einen nicht mehr 
unterstützten Serverdienst in Ihrem Managed Webspace {pac} gefunden,
siehe angehängte Liste.

Bitte stellen Sie die Verwaltung aller eigenen Serverdienste
*** in den nächsten Tagen ***
auf systemd um. Im Wiki gibt es dazu zwei Anleitungen:

https://wiki.hostsharing.net/index.php?title=Umstellung_von_Daemon-Diensten_auf_systemd

https://wiki.hostsharing.net/index.php?title=Prozessmanagement_mit_systemd_im_Userspace

Bitte beachten Sie, dass durch die Umstellung auf systemd der
Arbeitsspeicher-Bedarf Ihres Webpakets steigen wird und evtl.
Arbeitsspeicher nachgebucht werden muss. Sie erhalten in diesem
Fall eine weitere E-Mail mit dem Betreff
"Warnung! Arbeitsspeicher (RAM) ist ausgeschöpft".

Wenn Sie bei der Umstellung Probleme haben, fragen Sie bitte soweit 
wie möglich in der Mailingliste "Operations Discussion" um Hilfe,
damit auch andere Mitglieder von den Antworten profitieren können.

Selbstverständlich können Sie auch den Webmaster on Demand mit der
Umstellung Ihrer Serverdienste beauftragen:

https://www.hostsharing.net/service/webmaster-on-demand/

Liste gefundener Serverdienste ohne systemd-Verwaltung:
{proctable}

(Die nächste Warn-E-Mail mit dem gleichen Anliegen erhalten Sie
frühestens in {WARN_PERIOD_HOURS} Stunden.)
"""
    subject = "Achtung! Serverdienste ohne systemd-Verwaltung gefunden"
    hs_mailto_member(pac, subject, body)


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 exists_user(username):
    try:
        res = bool(pwd.getpwnam(username))

    except KeyError:
        res = False

    return res


re_hs_username = re.compile(r'[a-z][a-z0-9]{2}[0-9]{2}(-[a-z0-9._]{1,26})?')


def is_hs_username(username):
    """Return true iff username is a Linux user controlled by HSAdmin 

    e.g. xyz00 -> True, xyz00-bla -> True, nobody -> False
    """
    m = re_hs_username.match(username)

    return bool(m) and exists_user(username)


def get_pac(username):
    """Return Packet of given username.

    e.g. xyz00 -> xyz, xyz -> xyz"""

    return username if '-' not in username else username.split('-', 1)[0]


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_illegal_cgroup( cgroup ):
#    return cgroup in ('0::/system.slice/cron.service',)

re_cgroup_ssh_login = re.compile(r'0::/user\.slice/user-[0-9]+\.slice/session-[0-9]+\.scope')


def is_process_allowed(exe, cgroup, username):
    res = False

    # 0::/user.slice/user-1006.slice/session-140603.scope

    # res = ( exe in ('/usr/lib/openssh/sftp-server', '/usr/sbin/sshd', '/usr/lib/systemd/systemd' )
    res = (exe in ('/usr/lib/openssh/sftp-server', '/usr/sbin/sshd',
                   '/usr/lib/systemd/systemd', '/usr/lib/dovecot/dovecot-lda',
                   '/sbin/proftpd', '/usr/sbin/proftpd')
           or cgroup in ('0::/system.slice/dovecot.service',
                         '0::/system.slice/apache2.service',
                         '0::/system.slice/spamd.service',
                         '0::/system.slice/system-postfix.slice/postfix@postfix-mailin.service',
                         '0::/system.slice/cron.service'
                         )
           or is_cgroup_in_pacs_slice(cgroup, username)
           or re_cgroup_ssh_login.match(cgroup)
           )

    return res


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_current(pac):
    res = None
    # /sys/fs/cgroup/pacs.slice/pacs-peh97.slice/memory.current
    if os.path.exists(f'/sys/fs/cgroup/pacs.slice/pacs-{pac}.slice/memory.current'):
        res = int(float(open(f'/sys/fs/cgroup/pacs.slice/pacs-{pac}.slice/memory.current', 'r').read()))

    return res


def get_cgroup_memory_limits(pac):
    res = {'MemoryMax': None, 'MemoryHigh': 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

    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 l.startswith('MemoryMax=') or l.startswith('MemoryHigh=') or l.startswith(
                        '#hsadmin.pacram=') or l.startswith('#hsadmin.pacnumusers='):
                    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

    return res


def update_process_table(PROCS={}, only_illegal_procs=False):
    # PROCS = {}  # { 'xyz': { '<pid>-<createdat>': { 'pid': 123, 'createdat': 123232, 'vanishedat': 123123, 'username': 'xyz00-bla', 'exe': '/usr/sbin/sshd', 'cmdline': '', 'cgroup': None } }
    now = time.time()
    procids_seen = set()
    for p in psutil.process_iter():
        try:
            # cmdline = p.cmdline()[0] if p.cmdline() else ''
            cmdline = ' '.join(p.cmdline())
            username = p.username()
            pid = p.pid
            exe = p.exe()
            create_time = p.create_time()
            rss = p.memory_info().rss

        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            continue

        if is_hs_username(username):
            cgroup = get_cgroup(pid).rstrip()
            if only_illegal_procs is False or not is_process_allowed(exe, cgroup, username):
                pac = get_pac(username)
                if pac not in PROCS:
                    PROCS[pac] = {}
                created = datetime.datetime.fromtimestamp(create_time).strftime('%Y-%m-%d %H:%M:%S')
                procid = f'{pid}@{created}'

                if procid not in PROCS[pac]:
                    if DEBUG:
                        print(f"created: {pac} {procid}")
                    PROCS[pac][procid] = {'pid': pid,
                                          'created': create_time,
                                          'vanished': None,
                                          'username': username,
                                          'exe': exe,
                                          'cmdline': cmdline,
                                          'cgroup': cgroup,
                                          'rss': rss}

                procids_seen.add(procid)

    # set vanished
    for pac in PROCS:
        for procid in PROCS[pac]:
            if procid not in procids_seen and PROCS[pac][procid]['vanished'] is None:
                if DEBUG:
                    print(f"vanished: {pac} {procid}")
                PROCS[pac][procid]['vanished'] = now

    return PROCS


re_crontab_env = re.compile(r'[A-Za-z0-9_]+=.*')


def load_crontabs(only_reboot_jobs=False):
    res = {}
    crontabs = glob.glob('/var/spool/cron/crontabs/*')

    for crontab in crontabs:
        username = crontab.rsplit('/', 1)[-1]

        if is_hs_username(username):
            with open(crontab, 'rb') as f:
                n = 0
                for l in f:
                    l = l.decode('utf8', errors='ignore').encode('latin1', errors='ignore').decode('latin1', errors='ignore')
                    l = l.strip()
                    n += 1

                    if l and not l.startswith('#') and not re_crontab_env.match(l) and (
                            not only_reboot_jobs or l.startswith('@reboot')):
                        pac = get_pac(username)

                        # Datenstruktur initialisieren
                        if pac not in res:
                            res[pac] = {}

                        if crontab not in res[pac]:
                            res[pac][crontab] = []

                        # Zeilennummer und Zeile der Crontab speichern
                        res[pac][crontab].append((n, l))

    return res


def crontab2proctable(crontabs, pac):
    # [ 'PID', 'Startzeit', 'Username', 'Befehlszeile' ]
    res = []

    if pac in crontabs:
        for crontab in crontabs[pac]:
            username = crontab.rsplit('/', 1)[-1]

            for line in crontabs[pac][crontab]:
                res.append(['---', '---', username, "(crontab Zeile {0}) {1}".format(line[0], line[1])])

    return res


def get_etc_signature():
    res = ""
    if os.path.exists('/etc/signature'):
        res = open('/etc/signature', 'r').read()

    return res


def write_process_table(PROCS):
    with open('{TIMESTAMP_DIR}/procs', 'w') as f:
        for pac in sorted(PROCS.keys()):
            for procid in sorted(PROCS[pac].keys()):
                p = PROCS[pac][procid]
                f.write(
                    f'{pac}; {p["pid"]}; {p["created"]}; {p["vanished"]}; {p["username"]}; {p["exe"]}; {p["cgroup"]}; {p["cmdline"]}\n')


def get_age_last_warning(pac):
    res = 24 * 10  # 10 Tage
    if not os.path.exists(TIMESTAMP_DIR):
        os.mkdir(TIMESTAMP_DIR, mode=0o700)

    if os.path.exists(f'{TIMESTAMP_DIR}/{pac}'):
        mtime = os.path.getmtime(f'{TIMESTAMP_DIR}/{pac}')

        res = (time.time() - mtime) / 60 / 60

    return res


def set_age_last_warning(pac):
    pathlib.Path(f'{TIMESTAMP_DIR}/{pac}').touch(mode=0o700, exist_ok=True)


if __name__ == '__main__':
    if not is_hs_shared_hive():
        sys.exit(0)

    parser = argparse.ArgumentParser(prog='hs-check-pac-daemons', description='TODO', epilog='TODO')
    parser.add_argument('--interval', action='store', help='Time in seconds between measurements.')
    parser.add_argument('--count', action='store', help='Number of measurements.')
    # parser.add_argument( '--write-procs', action='store_true', help='Write collected data to /var/lib/hostsharing/hs-check-illegal-daemons.' )
    parser.add_argument('--send-member-emails', action='store_true', help='')

    args = parser.parse_args()

    interval = int(args.interval) if args.interval else 0
    count = int(args.count) if args.count else 0

    if count:
        PROCS = {}
        while count:
            PROCS = update_process_table(PROCS, only_illegal_procs=True)
            # write_process_table( PROCS )

            count -= 1

            if count:
                time.sleep(interval)

        # if args.write_procs:
        #    write_process_table( PROCS )

        CRONTABS = load_crontabs(only_reboot_jobs=True)

        if args.send_member_emails:
            pacs = list(set(PROCS.keys()) | set(CRONTABS.keys()))
            for pac in sorted(pacs):
                if get_age_last_warning(pac) > WARN_PERIOD_HOURS:
                    # älter als WARN_PERIOD_HOURS Stunden
                    set_age_last_warning(pac)

                    hs_mailto_member_warning(pac, PROCS, CRONTABS)
