Admin Workshop
Admin Workshop
PostgreSQL
administration fundamentals
workshop for beginners
Investment Analytics
Data Service
CC BY 2.0
February 2, 2020 PostgreSQL administration beginners' workshop 3
By HPI
CC BY-SA 3.0
CC BY-NC-ND 2.0
February 2, 2020 PostgreSQL administration beginners' workshop 5
PostgreSQL in operating system
• RDBMS SW installed -> Postgres instances -> databases managed by instance.
/usr/lib/postgresql/12/{lib,bin} /usr/lib/postgresql/9.6/{lib,bin}
ts_data
web lv_data
usr1 /dev/sdb
lv_temp
usr2
ts_temp
cardb
ts_sales /dev/sdc
sales
approle1
approle2 ts_dwh
dwh /dev/sdd
autovacuum
WAL writer
statistics
collector
February 2, 2020 PostgreSQL administration beginners' workshop 12
Postgres instance processes (release 10) root@debian:~# pstree -laps 405
systemd,1
└─postgres,405 -D /var/lib/postgresql/10/warehouse
├─postgres,410
bgworker – background worker process, starting from postgres ├─postgres,411
├─postgres,412
release 10 used to provide logical replication feature, some parallel ├─postgres,413
├─postgres,414
operations (sequential scan…) are supported, see └─postgres,415
max_worker_processes configuration parameter. Extension modules
might create bgworker processes even in previous releases.
5432/tcp
Postmaster pg_hba.conf
Backend process Main postgres process, listen Once postmaster receives
for network connections connection, it consults HBA rules to
work_mem
work_mem (default port 5432) and fork decide, whether permit or reject
work_mem
new server backend process connection from a machine using a
to handle client requests user to connect to a database.
Postmaster
Starts instance, allocates
postgresql.conf shared memory, listen for shared_buffers
connections and fork new
processes for them
Postmaster
Backend process Starts instance, allocates
work_mem shared memory, listen for shared_buffers
work_mem
work_mem connections and fork new
processes for them
Backend process
work_mem Background writer …
work_mem
work_mem
autovacuum
disk
Client
shared_buffers
Page
Client 1’
4 4’
3
1 3’
Backend process
Backend process work_mem
work_mem
work_mem
work_mem 2 2’
work_mem
work_mem
disk
CC BY-NC-ND 2.0
• Server connectivity to port 5432 (or any other we want use for Postgres)
• On DB server run netcat utility on desired port (without IP nc will listen on all interfaces)
root@debian:~# nc -vl -p 5432
listening on [any] 5432 ...
root@debian:~# nc -vln -s 192.168.151.16 -p 5432
listening on [192.168.151.16] 5432 ...
• Check connection from remote client to DB server
root@ubuntu:~# nc -vzn 192.168.151.16 5432
Connection to 192.168.151.16 5432 port [tcp/*] succeeded!
psql (10.1)
version
--------------------------------------------------------------------------------------------------------
PostgreSQL 10.1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2), 64-bit
• Disabled page checksum are default, can’t be changed by a configuration parameter, page_checksums are
part of cluster initialization, --data-checksums option of initdb utility, but on Debian/Ubuntu there are few
additional utilities to consider, like pg_createcluster which is integrated to OS and accepts data checksums
as well.
• pg_conftool
• Show or set configuration value without editing configuration file by hand
• pg_ctlcluster
• pg_ctlcluster 10 warehouse start … instance control, what else one might expect ☺
• pg_renamecluster, pg_dropcluster
• self explanatory utility names, most of them are suitable for automation
• RH/Fedora/CentOS • Debian/Ubuntu
• as already mentioned, • pg_lsclusters show us that information for log file
under data directory • /var/log/postgresql/postgresql-<version>-
• log rotation has to be <cluster_name>.log
configured in postgres • /var/log/postgresql/postgresql-10-main.log
configuration file or by • /var/log/postgresql/postgresql-10-warehouse.log
creating logrotate rules
• Default data directory • Configuration is in /etc same structure as for logs
• /var/lib/pgsql/12/data/ • /etc/postgresql/<version>/<cluster_name>/postgresql.conf
• Log files directory • /etc/postgresql/10/main/postgresql.conf
• /var/lib/pgsql/12/data/log • /etc/postgresql/10/warehouse/postgresql.conf
• pg_log for ver. <= 9.6
• postgresql-common also configure log rotation
• /etc/logrotate.d/postgresql-common
February 2, 2020 PostgreSQL administration beginners' workshop 34
psql console
• \h – list available help on SQL commands
=# \h drop index
Command: DROP INDEX
Description: remove an index
Syntax:
DROP INDEX [ CONCURRENTLY ] [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]
URL: https://www.postgresql.org/docs/12/sql-dropindex.html
data_directory
------------------------
/var/lib/pgsql/10/data
(1 row)
postgres=# \q
[postgres@localhost ~]$
• We have issued our first select statement and learned how to display a
parameter value and how to quit psql console.
• Let’s explore content of the data directory
• Tweak configuration
• Some parameters are usually subject of change
because defaults are very conservative
• Configure remote server access
• Create roles (users) – no one really wants all DB
traffic to run under postgres user
• Create databases
• … setup BACKUP & RECOVERY procedures
• Setup monitoring and alerting
• By default there is no password for default
postgres superuser account and default
database postgres is created
February 2, 2020
• listen_address
• host based authentication
• archive_mode
• shared_buffers
• Logging configuration
• Backup & recovery procedure
• Always setup REGULAR RECOVERY TEST procedure
• pg_basebackup
• pgBackRest
• Barman
• WAL-E …. and many other backup tools are available
• Replication to a disaster recovery site
February 2, 2020
postgres=# \q
[postgres@fedora ~]$
• Options
• -h server_host
• -U database username
• -d database name, default database is postgres created by initdb utility
• The test obviously failed…
• Why, we have already checked network connectivity and added FW rule for 5432/TCP…?
/usr/lib/postgresql/10/{lib,bin}
SW installation
/usr/lib/postgresql/10/bin/postgres # server binary file
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
(3 rows)
postgres=# select current_setting('server_version');
current_setting
-----------------
10.1
(1 row)
postgres=# \q
CC BY-NC-ND 2.0
February 2, 2020 PostgreSQL administration beginners' workshop 57
Let’s play for a while, before the hard-serious work begins
CC BY-NC 2.0
CC BY-NC 2.0
February 2, 2020 PostgreSQL administration beginners' workshop 59
Logging configuration
• Log rotation (save logs as long as possible, same for OS statistics, sar…)
• log_destination = 'stderr'
• logging_collector = on
• log_directory = 'pg_log'
• log_filename = 'postgresql.log’ # 'postgresql%d.log’ if NOT using logrotate…
• log_truncate_on_rotation = off # on if NOT using logrotate…
• log_rotation_age = 1d # daily if NOT using logrotate
• log_rotation_size = 0 # can be used instead if time rotation, if NOT using…
• log_checkpoints = on
• log_connections = on
• log_disconnections = on
• log_line_prefix = '%t %c %l %r %d %u %x %v %i:'
February 2, 2020 PostgreSQL administration beginners' workshop 60
Logging configuration
• log_lock_waits = on
• log_statement = 'ddl’
• log_temp_files = 2048 # log temporary files equal or larger then [Bytes]
• log_min_duration_statement = 5000 # log statemetns lastimg for … ms – slow queries
• log_timezone = 'Europe/Prague’ # UTC for international companies!
• track_counts = on # default
• track_io_timing = on # use pg_test_timing in advance to test your CPU speed
• autovacuum = on # default
• log_autovacuum_min_duration = 0 # if there are too many log entries 250 [ms]…
• default_tablespace = <some_ts> # create some_ts where public is not usage granted
•February
temp_tablespace
2, 2020 = ‘temp’ #PostgreSQL
create administration
temp tablespace on separate filesystem
beginners' workshop 61
Instance configuration
• shared_buffers = <NN>GB # usually you want to change default value
• work_mem = 64MB # not a per session, but per SQL exec plan node
• maintenance_work_mem = 1GB # index creation, vacuum operations…
• shared_preload_libraries = 'pg_stat_statements’ # must have extension
• wal_level = replica # or higher
• min_wal_size = <NN>GB
• max_wal_size = <NN>GB # This is a soft limit; WAL size can exceed max_wal_size under
special circumstances, like under heavy load, a failing archive_command, or a high
wal_keep_segments setting.
• checkpoint_completion_target = 0.75
CC BY 2.0
CC BY 2.0
• psql can use a pspg pager for interactive browsing through result set, by Pavel
Stěhule ☺ Already in PGDG repositories, ready to install.
February 2, 2020 PostgreSQL administration beginners' workshop 73
CC BY-NC 2.0
CC BY 2.0
postgres=# select line_number, type, database, user_name, address, netmask, auth_method, options from
pg_hba_file_rules where address !~ '::1';
line_number | type | database | user_name | address | netmask | auth_method | options
-------------+------+---------------+-----------+---------------+-----------------+-------------+---------
92 | host | {all} | {all} | 127.0.0.1 | 255.255.255.255 | md5 |
93 | host | {all} | {all} | 192.168.151.0 | 255.255.255.0 | md5 |
99 | host | {replication} | {all} | 127.0.0.1 | 255.255.255.255 | md5 |
(3 rows)
postgres=#
weather=# rollback;
weather=# revoke all on schema public from public;
ROLLBACK
REVOKE
weather=# \dn
List of schemas
Name | Owner
--------+----------
public | postgres
(1 row)
weather=> \dn
List of schemas
Name | Owner
---------+----------
public | postgres
weather | weather
(2 rows)
postgres=# \c weather
You are now connected to database "weather" as user "postgres".
weather=# grant usage on schema weather to weather_app;
GRANT
weather=> \dn+
List of schemas
Name | Owner | Access privileges | Description
---------+----------+-----------------------+------------------------
public | postgres | postgres=UC/postgres | standard public schema
weather | weather | weather=UC/weather +|
| | weather_app=U/weather |
(2 rows)
postgres=# \c weather
You are now connected to database "weather" as user "postgres".
postgres@debian:~$ psql
psql (10.1)
Type "help" for help.
weather=#
February 2, 2020 PostgreSQL administration beginners' workshop 104
Try a better design
• Table was created, but it is owned by the user used to create the table
• we might want to have application tables to be owned by the application (nologin) role only
postgres@debian:~$ psql
psql (10.1)
Type "help" for help.
postgres=# \c weather
You are now connected to database "weather" as user "postgres".
weather=# \dt weather.foo ;
List of relations
Schema | Name | Type | Owner
---------+------+-------+-------------
weather | foo | table | weather_app
(1 row)
weather=# drop table weather.foo ;
DROP TABLE
• or we can crate table under any user with enough privileges and afetrwards
ALTER TABLE foo OWNER TO weather;
postgres@debian:~$ psql
psql (10.1)
Type "help" for help.
postgres=# \c weather
weather=# grant select, insert, update, delete, references on ALL tables in schema
weather to weather_app;
GRANT
weather=# \q
postgres=# \c weather
You are now connected to database "weather" as user "postgres".
weather=# alter default privileges in schema weather grant select, insert, update, delete
on tables to weather_app;
ALTER DEFAULT PRIVILEGES
weather=# alter default privileges in schema weather grant select, usage on sequences to
weather_app;
ALTER DEFAULT PRIVILEGES
weather=# create table weather.foo2(foo2_id bigserial, bar int);
CREATE TABLE
weather=# alter table weather.foo2 owner to weather;
ALTER TABLE
weather=# \q