Skip to content
Snippets Groups Projects
test_postgresql.py 13.8 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
#!/usr/bin/env python3
"""This test check the current state of the PostgreSQL database cluster."""

import imp
import os
import re
import socket
import sys
import time

import psycopg2

GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
DEF = "\033[0m"


def is_ha(port: int) -> bool:
    """Check wether this setup is using higlhy-available databases.

    :param port: Port number
    :type port: int
    :return: Wether it is a highly-available setup or not
    :rtype: bool
    """

    return port == 54321


def get_haproxy_conf(path: str = "/etc/haproxy/haproxy.cfg") -> dict:
    """Get HAProxy configuration in a dictionary.

    :param path: HAProxy configuration file, defaults to "/etc/haproxy/haproxy.cfg"
    :type path: str
    :return: HAProxy configuration file content
    :rtype: dict
    """

    # init configuration dictionary
    conf: dict = {}

    # load configuration file
    try:
        with open(path) as data:
            lines = data.readlines()
    except EnvironmentError:
        return conf

    # define patterns
    pattern_block = re.compile(r"^([a-zA-Z0-9_.-]+ *[a-zA-Z0-9_.-]+)")
    pattern_param = re.compile(r"^\s+([ /:()|a-zA-Z0-9_.-]+)")

    # parse configuration file
    for line in lines:
        match_block = pattern_block.match(line)
        if match_block:
            block = match_block.group(1)
            conf[block] = []
        else:
            match_param = pattern_param.match(line)
            if match_param:
                param = match_param.group(1)
                conf[block].append(param)

    return conf


def get_nodes(conf: dict) -> dict:
    """Get the list of nodes from HAProxy configuration.

    :param conf: The HAProxy configuration file content
    :type conf: dict
    :return: The list of nodes found in HAProxy configuration
    :rtype: dict
    """

    servers: dict = {}

    for item in conf.keys():
        if "pgsql-primary" in item:
            # filter `server` lines
            server_lines = [x for x in conf[item] if x.startswith("server ")]
            for line in server_lines:
                # split line
                elements = line.split()

                # get needed elements
                name = elements[1]
                address = elements[2].split(":")
                host = address[0]
                port = address[1]
                rephacheck = elements[7]

                # update dictionary
                servers.update(
                    {name: {"host": host, "port": port, "rephacheck": rephacheck}}
                )

    return servers


def check_odd_number(number: int) -> bool:
    """Check if we have an odd number of nodes, ensuring we can have a quorum.

    :param number: The number of nodes in the cluster
    :type number: int
    :return: Wether it as an odd number or not
    :rtype: bool
    """

    modulo = number % 2

    return modulo != 0


def get_node_state(host: str, port: int) -> str:
    """Get the curent state of node from its RepHACheck daemon.

    :param node: The node's hostname or IP address
    :param port: The node's port on which RepHACheck is listening
    :type node: str
    :type port: int
    :return: The current state of the node accordind to its RepHACheck daemon
    :rtype: str
    """

    # connect and get tcp stream data
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, port))
    data = client.recv(1024)
    client.close()
    # extract string from data output
    state = data.decode("utf-8").rstrip()

    return state


def check_primary(nodes: dict) -> tuple:
    """Check if we have a primary in the nodes.

    :param nodes: The dictionary containing nodes and their informations
    :type nodes: dict
    :return: Wether the nodes list contains a primary server
    :rtype: tuple
    """

    for node in nodes.keys():
        host = nodes[node]["address"]
        port = nodes[node]["rephacheck"]
        if get_node_state(host, port) == "primary":
            return True, node

    return False, None


def check_standby(nodes: dict) -> tuple:
    """Check if we have a standby in the nodes.

    :param nodes: The dictionary containing nodes and their informations
    :type nodes: dict
    :return: Wether the nodes list contains a standby server
    :rtype: tuple
    """

    for node in nodes.keys():
        host = nodes[node]["address"]
        port = nodes[node]["rephacheck"]
        if get_node_state(host, port) == "standby":
            return True, node

    return False, None


def check_witness(nodes: dict) -> tuple:
    """Check if we have a witness in the nodes.

    :param nodes: The dictionary containing nodes and their informations
    :type nodes: dict
    :return: Wether the nodes list contains a witness server
    :rtype: tuple
    """

    for node in nodes.keys():
        host = nodes[node]["address"]
        port = nodes[node]["rephacheck"]
        if get_node_state(host, port) == "witness":
            return True, node

    return False, None


def check_fenced(nodes: dict) -> tuple:
    """Check if the cluster have a fenced node.

    :param nodes: The dictionary containing nodes and their informations
    :type nodes: dict
    :return: Wether the nodes list contains a fenced server
    :rtype: tuple
    """

    for node in nodes.keys():
        host = nodes[node]["address"]
        port = nodes[node]["rephacheck"]
        if get_node_state(host, port) == "fenced":
            return True, node

    return False, None


# pylint: disable=bad-continuation
def check_write(
    host: str, port: int, user: str, pswd: str, name: str = "postgres"
) -> bool:
    """Check if we can write data on this node.

    :param host: Database server's hostname or IP address
    :type host: str
    :param port: Database server's port
    :type port: int
    :param user: Database username
    :type user: str
    :param pswd: Database username's password
    :type pswd: str
    :param pswd: Database name
    :type pswd: str
    :return: Wether it is writeable or not
    :rtype: bool
    """

    # connection
    try:
        client = psycopg2.connect(
            dbname=name, user=user, password=pswd, host=host, port=port
        )
    except psycopg2.Error:
        print("{}Cannot connect to the database{}".format(RED, DEF))
        return False

    # query
    try:
        psql = client.cursor()
        psql.execute("CREATE TABLE es_test (id serial PRIMARY KEY);")
        psql.execute("DROP TABLE es_test;")
    except psycopg2.Error:
        return False

    # close
    psql.close()
    client.close()

    return True


# pylint: disable=bad-continuation
def check_read(
    host: str, port: int, user: str, pswd: str, name: str = "postgres"
) -> bool:
    """Check if we can read data on this node.

    :param host: Database server's hostname or IP address
    :type host: str
    :param port: Database server's port
    :type port: int
    :param user: Database username
    :type user: str
    :param pswd: Database username's password
    :type pswd: str
    :param pswd: Database name
    :type pswd: str
    :return: Wether it is writeable or not
    :rtype: bool
    """

    # connection
    try:
        client = psycopg2.connect(
            dbname=name, user=user, password=pswd, host=host, port=port
        )
    except psycopg2.Error:
        print("{}Cannot connect to the database{}".format(RED, DEF))
        return False

    # query
    try:
        psql = client.cursor()
        psql.execute("SELECT;")
    except psycopg2.Error:
        return False

    # close
    psql.close()
    client.close()

    return True


def check_replication(primary: dict, standby: dict) -> bool:
    """Check if replication is working between the primary and standby servers.

    :param primary: Connection details for primary server
    :type primary: dict
    :param standby: Connection details for standby server
    :type standby: dict
    :return: Wether replication between primary/stanbdy is working or not
    :rtype: bool
    """

    # connections
    try:
        primary_client = psycopg2.connect(**primary)
        standby_client = psycopg2.connect(**standby)
    except psycopg2.Error:
        print("{}Cannot connect to the databases{}".format(RED, DEF))
        return False

    # queries
    try:
        primary_psql = primary_client.cursor()
        primary_psql.execute("CREATE TABLE es_test (id serial PRIMARY KEY);")
        time.sleep(1)
        standby_psql = primary_client.cursor()
        standby_psql.execute("SELECT * FROM es_test;")
        primary_psql.execute("DROP TABLE es_test;")
    except psycopg2.Error:
        return False

    # close
    primary_psql.close()
    standby_psql.close()
    primary_client.close()
    standby_client.close()

    return True


def check_listen(host: str, port: int) -> bool:
    """Check if server is listening (TCP only).

    :param host: The hostname or IP address to bind
    :param port: The port number to bind
    :type host: str
    :type port: int
    :return: Wether the `host` is listening on TCP/`port`
    :rtype: bool
    """

    # try to connect to the port used by psql-primary frontend
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = client.connect_ex((host, port))
    client.close()

    return result == 0


def check_ha(db_conn: dict, errors: int = 0, warnings: int = 0) -> tuple:
    """Run all tests for a highly-available setup.

    :param db_conn: Database connection parameters
    :type db_conn: dict
    :param errors: Error counter, defaults to 0
    :param errors: int, optional
    :param warnings: Warning counter, defaults to 0
    :param warnings: int, optional
    :return: Numbers of errors and warnings
    :rtype: tuple
    """

    db_host = db_conn["host"]
    db_user = db_conn["user"]
    db_pass = db_conn["pass"]

    # get haproxy conf
    ha_conf = get_haproxy_conf()

    # get nodes data
    nodes = get_nodes(ha_conf)

    # check haproxy
    if not check_listen(db_host, 54321):
        print("{}HAProxy pgsql-primary frontend is not listening{}".format(RED, DEF))
        errors += 1
    else:
        print("HAProxy pgsql-primary frontend is listening")
    if not check_listen(db_host, 54322):
        print("{}HAProxy pgsql-standby frontend is not listening{}".format(RED, DEF))
        errors += 1
    else:
        print("HAProxy pgsql-standby frontend is listening")

    # check remotes
    for node in nodes:
        node_host = nodes[node]["address"]
        node_port = nodes[node]["port"]
        if not check_listen(node_host, node_port):
            print("{}Cannot bind {}:{}{}".format(RED, node_host, node_port, DEF))
            errors += 1
        else:
            print("Can bind {}:{}".format(node_host, node_port))

    # check fenced
    fenced, node = check_fenced(nodes)
    if fenced:
        print("{}Node `{}` is fenced{}".format(RED, node, DEF))
        errors += 1
    else:
        print("No fenced node found")

    # check replication
    primary = {
        "dbname": "postgres",
        "user": db_user,
        "password": db_pass,
        "host": db_host,
        "port": 54321,
    }
    standby = {
        "dbname": "postgres",
        "user": db_user,
        "password": db_pass,
        "host": db_host,
        "port": 54322,
    }
    if not check_replication(primary, standby):
        print("{}Cannot replicate data between primary/standby{}".format(RED, DEF))
        errors += 1
    else:
        print("Can replicate data between primary/standby")

    return errors, warnings


def check_local(db_conn: dict, errors: int = 0, warnings: int = 0) -> tuple:
    """Run all tests for a highly-available setup.

    :param db_conn: Database connection parameters
    :type db_conn: dict
    :param errors: Error counter, defaults to 0
    :param errors: int, optional
    :param warnings: Warning counter, defaults to 0
    :param warnings: int, optional
    :return: Numbers of errors and warnings
    :rtype: tuple
    """

    db_host = db_conn["host"]
    db_port = db_conn["port"]
    db_user = db_conn["user"]
    db_pass = db_conn["pass"]

    # check listen
    if not check_listen(db_host, db_port):
        print("{}Cannot connect to {}:{}{}".format(RED, db_host, db_port, DEF))
        errors += 1

    # check read
    if not check_read(db_host, db_port, db_user, db_pass):
        print(
            "{}Cannot read data on {}@{}:{}{}".format(
                RED, db_user, db_host, db_port, DEF
            )
        )
        errors += 1
    else:
        print("Can read data on {}@{}:{}".format(db_user, db_host, db_port))

    # check write
    if not check_write(db_host, db_port, db_user, db_pass):
        print(
            "{}Cannot write data on {}@{}:{}{}".format(
                RED, db_user, db_host, db_port, DEF
            )
        )
        errors += 1
    else:
        print("Can write data on {}@{}:{}".format(db_user, db_host, db_port))

    return errors, warnings


def main():
    """Run all checks and exits with corresponding exit code."""

    # envsetup utils path
    cwd = os.path.dirname(__file__)
    utils = os.path.join(cwd, "..", "utils.py")

    # check envsetup utils presence
    if not os.path.isfile(utils):
        print("{} not found.".format(utils))
        sys.exit(1)

    # load envsetup utils
    es_utils = imp.load_source("es_utils", utils)

    # load configuration
    conf = es_utils.load_conf()

    # get database configuration
    db_host = conf.get("DB_HOST", "127.0.0.1")
    db_port = conf.get(int("DB_PORT"), 5432)
    db_user = conf.get("DB_USER", "postgres")
    db_pass = conf.get("DB_PG_ROOT_PWD")
    db_conf = {"host": db_host, "port": db_port, "user": db_user, "pass": db_pass}

    # determine if HA setup
    if is_ha(db_port):
        print("This setup is using a HA database")

        errors, warnings = check_ha(db_conf)
    else:
        print("This setup is using a local database")

        errors, warnings = check_local(db_conf)

    if errors:
        sys.exit(1)
    elif warnings:
        sys.exit(2)
    else:
        sys.exit(0)


if __name__ == "__main__":
    main()