#==============================================================#
# File      :   pgbouncer.ini
# Desc      :   Pgbouncer Main Config for {{ pg_instance }}
# Time      :   {{ '%Y-%m-%d %H:%M' | strftime }}
# Host      :   {{ pg_instance }} @ {{ inventory_hostname }}:{{ pg_port }}
# Path      :   /etc/pgbouncer/pgbouncer.ini
# Note      :   ANSIBLE MANAGED, DO NOT CHANGE!
# License   :   Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright :   2018-2026  Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
{% set pg_listen_address = pg_listen | replace('${ip}', inventory_hostname) | replace('${lo}', '127.0.0.1') %}
{% if pg_vip_enabled|bool and not pg_vip_address.startswith('127.0.0') and '/' in pg_vip_address %}
{% set pg_listen_address = pg_listen_address | replace('${vip}', pg_vip_address.split('/')[0]) %}
{% endif %}

[users]
%include /etc/pgbouncer/useropts.txt

[databases]
%include /etc/pgbouncer/database.txt

[pgbouncer]
pool_mode                   = {{ pgbouncer_poolmode }}
listen_addr                 = {{ pg_listen_address }}
listen_port                 = {{ pgbouncer_port }}
admin_users                 = {{ pg_dbsu|default('postgres') }}, {{ pg_admin_username|default('dbuser_dba') }}
stats_users                 = {{ pg_dbsu|default('postgres') }}, {{ pg_monitor_username|default('dbuser_monitor') }}

# Auth & SSL
auth_type                   = hba
auth_file                   = /etc/pgbouncer/userlist.txt
auth_hba_file               = /etc/pgbouncer/pgb_hba.conf
{% if pgbouncer_auth_query | default(false) | bool %}
auth_user                   = {{ pg_dbsu }}
auth_query                  = SELECT username, password FROM monitor.pgbouncer_auth($1)
{% endif %}

client_tls_sslmode          = {{ pgbouncer_sslmode }}
client_tls_cert_file        = /pg/cert/server.crt
client_tls_key_file         = /pg/cert/server.key
client_tls_ca_file          = /pg/cert/ca.crt
server_reset_query          = DISCARD ALL
server_reset_query_always   = 0
unix_socket_dir             = /run/postgresql
pidfile                     = /run/postgresql/pgbouncer.pid
logfile                     = {{ pgbouncer_log_dir|default('/pg/log/pgbouncer') }}/pgbouncer.log
application_name_add_host   = 0
max_client_conn             = 20000
min_pool_size               = 0
default_pool_size           = 50
reserve_pool_size           = 30
reserve_pool_timeout        = 1
server_lifetime             = 600
max_db_connections          = 100
max_user_connections        = 100
server_round_robin          = 0
log_connections             = 0
log_disconnections          = 0
ignore_startup_parameters   = {{ pgbouncer_ignore_param|join(', ') }}
max_prepared_statements     = 256
