def validate_directory(d: str, msg: str = "{} {}") -> None:
    """Ensure directory exists and is writable.

    .. note::
        If the directory does not exist, :func:`validate_directory` will attempt to create it.

    :param d: the directory to be checked.
    :param msg: a message to be thrown when raising :class:`~patroni.exceptions.PatroniException`, if any issue is
        faced. It must contain 2 placeholders to be used by :func:`format`:

            * The first placeholder will be replaced with path *d*;
            * The second placeholder will be replaced with the error condition.

    :raises:
        :class:`~patroni.exceptions.PatroniException`: if any issue is observed while validating *d*. Can be thrown if:

            * *d* did not exist, and :func:`validate_directory` was not able to create it; or
            * *d* is an existing directory, but Patroni is not able to write to that directory; or
            * *d* is an existing file, not a directory.
    """
    if not os.path.exists(d):
        try:
            os.makedirs(d)
        except OSError as e:
            logger.error(e)
            if e.errno != errno.EEXIST:
                raise PatroniException(msg.format(d, "couldn't create the directory"))
    elif os.path.isdir(d):
        try:
            fd, tmpfile = tempfile.mkstemp(dir=d)
            os.close(fd)
            os.remove(tmpfile)
        except OSError:
            raise PatroniException(msg.format(d, "the directory is not writable"))
    else:
        raise PatroniException(msg.format(d, "is not a directory"))
Ensure directory exists and is writable.

    .. note::
        If the directory does not exist, :func:`validate_directory` will attempt to create it.

    :param d: the directory to be checked.
    :param msg: a message to be thrown when raising :class:`~patroni.exceptions.PatroniException`, if any issue is
        faced. It must contain 2 placeholders to be used by :func:`format`:

            * The first placeholder will be replaced with path *d*;
            * The second placeholder will be replaced with the error condition.

    :raises:
        :class:`~patroni.exceptions.PatroniException`: if any issue is observed while validating *d*. Can be thrown if:

            * *d* did not exist, and :func:`validate_directory` was not able to create it; or
            * *d* is an existing directory, but Patroni is not able to write to that directory; or
            * *d* is an existing file, not a directory.
    
patroni/utils.py