__init__.py 2.27 KB
import sys
import os
from argparse import ArgumentParser
from configparser import ConfigParser
from subprocess import (
    PIPE,
    Popen,
    )
from maintenance import (
    is_mirror,
    Reader,
    )


def get_option(argv):
    parser = ArgumentParser()
    parser.add_argument('config')
    return parser.parse_args(argv)


def mkdir(name):
    if not os.path.exists(name):
        os.mkdir(name)


def is_active(conf_file):
    r = Reader(conf_file)
    port = r['port']
    cmd_psql = f'psql -p {port} -c "SELECT pg_is_in_recovery()"'
    cmd1 = ['su', '-', 'postgres', '-c', cmd_psql]
    cmd2 = ['sed', '-n', '3p']
    p1 = Popen(cmd1, stdout=PIPE)
    p2 = Popen(cmd2, stdin=p1.stdout, stdout=PIPE)
    out, err = p2.communicate()
    if not err:
        s = out.decode('utf-8')
        return s.strip()


def main(argv=sys.argv[1:]):
    option = get_option(argv)
    conf_file = option.config
    conf = ConfigParser()
    conf.read(conf_file)
    status_dir = conf.get('mirror_status', 'status_dir')
    status_change_cmd = conf.get('mirror_status', 'after')
    mkdir(status_dir)
    pg_conf_dir = conf.get('main', 'pg_conf_dir')
    for version in os.listdir(pg_conf_dir):
        version_conf_dir = os.path.join(pg_conf_dir, version)
        for cluster in os.listdir(version_conf_dir):
            cluster_conf_dir = os.path.join(version_conf_dir, cluster)
            pg_conf = os.path.join(cluster_conf_dir, 'postgresql.conf')
            if not is_mirror(pg_conf):
                continue
            new_status = is_active(pg_conf)
            label = new_status and 'OK' or 'GAGAL'
            print(f'{version} {cluster} {label}')
            status_file = f'postgresql-{version}-{cluster}.txt'
            status_file = os.path.join(status_dir, status_file)
            if os.path.exists(status_file):
                with open(status_file, 'rb') as f:
                    old_status = f.read()
                old_status = old_status.decode('utf8')
            else:
                old_status = None
            with open(status_file, 'wb') as f:
                f.write(new_status.encode('utf8'))
            if new_status != old_status:
                d = dict(status_file=status_file)
                cmd = status_change_cmd.format(**d)
                print(cmd)
                os.system(cmd)