PostgreSQL no Raspberry Pi com FreeBSD 13

Instalação

Usando o FreeBSD 13 no Raspberry Pi 4, vamos mostrar como instalar, inicializar, permitir conexões remotas, criar usuário e banco de dados no PostgreSQL.

Instalação do PostgreSQL 13

A instalação é feita através do gerenciador de pacotes pkg, um utilitário usado para gerenciar pacotes, que instala e atualiza pacotes a partir de repositórios remotos. Tanto o PostgreSQL quanto as dependências instaladas mostram informações durante a sua instalação.

root@pi:/home/freebsd # pkg install postgresql13-server postgresql13-client postgresql13-contrib
Updating FreeBSD repository catalogue...
FreeBSD repository is up to date.
All repositories are up to date.
The following 12 package(s) will be affected (of 0 checked):

New packages to be INSTALLED:
	icu: 68.2,1
	libedit: 3.1.20210216,1
	libffi: 3.3_1
	libxml2: 2.9.10_4
	llvm11: 11.0.1
	lua52: 5.2.4
	perl5: 5.32.1_1
	postgresql13-client: 13.3
	postgresql13-contrib: 13.3
	postgresql13-server: 13.3
	python37: 3.7.10
	readline: 8.1.0

Number of packages to be installed: 12

The process will require 929 MiB more space.
149 MiB to be downloaded.

Proceed with this action? [y/N]: y
...
[11/12] Installing postgresql13-server-13.3...
===> Creating groups.
Creating group 'postgres' with gid '770'.
===> Creating users
Creating user 'postgres' with uid '770'.
===> Creating homedir(s)

  =========== BACKUP YOUR DATA! =============
  As always, backup your data before
  upgrading. If the upgrade leads to a higher
  major revision (e.g. 9.6 -> 10), a dump
  and restore of all databases is
  required. This is *NOT* done by the port!
  See https://www.postgresql.org/docs/current/upgrading.html
  ===========================================
[11/12] Extracting postgresql13-server-13.3: 100%
[12/12] Installing postgresql13-contrib-13.3...
[12/12] Extracting postgresql13-contrib-13.3: 100%
=====
Message from python37-3.7.10:

--
Note that some standard Python modules are provided as separate ports
as they require additional dependencies. They are available as:

py37-gdbm       databases/py-gdbm@py37
py37-sqlite3    databases/py-sqlite3@py37
py37-tkinter    x11-toolkits/py-tkinter@py37
=====
Message from postgresql13-client-13.3:

--
The PostgreSQL port has a collection of "side orders":

postgresql-docs
  For all of the html documentation

p5-Pg
  A perl5 API for client access to PostgreSQL databases.

postgresql-tcltk
  If you want tcl/tk client support.

postgresql-jdbc
  For Java JDBC support.

postgresql-odbc
  For client access from unix applications using ODBC as access
  method. Not needed to access unix PostgreSQL servers from Win32
  using ODBC. See below.

ruby-postgres, py-psycopg2
  For client access to PostgreSQL databases using the ruby & python
  languages.

postgresql-plperl, postgresql-pltcl & postgresql-plruby
  For using perl5, tcl & ruby as procedural languages.

postgresql-contrib
  Lots of contributed utilities, postgresql functions and
  datatypes. There you find pg_standby, pgcrypto and many other cool
  things.

etc...
=====
Message from postgresql13-server-13.3:

--
For procedural languages and postgresql functions, please note that
you might have to update them when updating the server.

If you have many tables and many clients running, consider raising
kern.maxfiles using sysctl(8), or reconfigure your kernel
appropriately.

The port is set up to use autovacuum for new databases, but you might
also want to vacuum and perhaps backup your database regularly. There
is a periodic script, /usr/local/etc/periodic/daily/502.pgsql, that
you may find useful. You can use it to backup and perform vacuum on all
databases nightly. Per default, it performs `vacuum analyze'. See the
script for instructions. For autovacuum settings, please review
~postgres/data/postgresql.conf.

If you plan to access your PostgreSQL server using ODBC, please
consider running the SQL script /usr/local/share/postgresql/odbc.sql
to get the functions required for ODBC compliance.

Please note that if you use the rc script,
/usr/local/etc/rc.d/postgresql, to initialize the database, unicode
(UTF-8) will be used to store character data by default.  Set
postgresql_initdb_flags or use login.conf settings described below to
alter this behaviour. See the start rc script for more info.

To set limits, environment stuff like locale and collation and other
things, you can set up a class in /etc/login.conf before initializing
the database. Add something similar to this to /etc/login.conf:
---
postgres:\
	:lang=en_US.UTF-8:\
	:setenv=LC_COLLATE=C:\
	:tc=default:
---
and run `cap_mkdb /etc/login.conf'.
Then add 'postgresql_class="postgres"' to /etc/rc.conf.

======================================================================

To initialize the database, run

  /usr/local/etc/rc.d/postgresql initdb

You can then start PostgreSQL by running:

  /usr/local/etc/rc.d/postgresql start

For postmaster settings, see ~postgres/data/postgresql.conf

NB. FreeBSD's PostgreSQL port logs to syslog by default
    See ~postgres/data/postgresql.conf for more info

NB. If you're not using a checksumming filesystem like ZFS, you might
    wish to enable data checksumming. It can be enabled during
    the initdb phase, by adding the "--data-checksums" flag to
    the postgresql_initdb_flags rcvar. Otherwise you can enable it later by
    pg_checksums.  Check the initdb(1) manpage for more info
    and make sure you understand the performance implications.

======================================================================

To run PostgreSQL at startup, add
'postgresql_enable="YES"' to /etc/rc.conf
=====
Message from postgresql13-contrib-13.3:

--
The PostgreSQL contrib utilities have been installed. Please see
/usr/local/share/doc/postgresql/contrib/README
for more information.

Inicialização da base de dados do PostgreSQL

Após a instalação, é necessário inicializar a base de dados do PostgreSQL e iniciar o serviço postgresql:

root@pi:/home/freebsd # /usr/local/etc/rc.d/postgresql oneinitdb
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locales
  COLLATE:  C
  CTYPE:    C.UTF-8
  MESSAGES: C.UTF-8
  MONETARY: C.UTF-8
  NUMERIC:  C.UTF-8
  TIME:     C.UTF-8
The default text search configuration will be set to "english".

Data page checksums are disabled.

creating directory /var/db/postgres/data13 ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... UTC
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

initdb: warning: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    /usr/local/bin/pg_ctl -D /var/db/postgres/data13 -l logfile start

root@pi:/home/freebsd # : Iniciar o PostgreSQL
root@pi:/home/freebsd # service postgresql onestart
2021-06-08 08:37:12.419 UTC [91682] LOG:  ending log output to stderr
2021-06-08 08:37:12.419 UTC [91682] HINT:  Future log output will go to log destination "syslog".

Usuários do banco de dados

Vamos agora atribuir uma senha ao usuário postgres, criar um usuário com nome pguser, que vai ser dono do banco de dados pgbase, e o usuário halley.

root@pi:/home/freebsd # psql --username=postgres
postgres=# ALTER USER postgres WITH PASSWORD 'postgrespwd';
ALTER ROLE
postgres=# CREATE USER pguser WITH PASSWORD 'pguserpwd';
CREATE ROLE
postgres=# CREATE DATABASE pgbase WITH OWNER pguser;
CREATE DATABASE
postgres=# CREATE USER halley WITH PASSWORD 'halleypwd';
CREATE ROLE

Permitir conexões remotas

Após a instalação, o PostgreSQL permite apenas conexões locais, para permitir conexões remotas o arquivo postgresql.conf precisa ser editado, removido o comentário da linha listen_addresses e especificado de quais endereços de IP serão aceitas as conexões, nesse caso de qualquer endereço (*). Os comandos sockstat emitidos antes e após a edição dos arquivos mostram as diferenças.

root@pi:/home/freebsd # sockstat -4 -6 -P tcp -p 5432
USER     COMMAND    PID   FD PROTO  LOCAL ADDRESS         FOREIGN ADDRESS
postgres postgres   91682 6  tcp6   ::1:5432              *:*
postgres postgres   91682 7  tcp4   127.0.0.1:5432        *:*

root@pi:/home/freebsd # ee /var/db/postgres/data13/postgresql.conf
...
 - Connection Settings -

listen_addresses = '*'                  # what IP address(es) to listen on;
                                        # comma-separated list of addresses;
                                        # defaults to 'localhost'; use '*' for all
...

Embora o PostgreSQL esteja escutando todos os endereços de IP, no arquivo de configuração de autenticação dos clientes, pg_hba.conf, só serão atendidas autenticações de clientes que estejam no hospedeiro local ou na rede local.

root@pi:/home/freebsd # ee /var/db/postgres/data13/pg_hba.conf
# PostgreSQL Client Authentication Configuration File
# ===================================================
#
# Refer to the "Client Authentication" section in the PostgreSQL
# documentation for a complete description of this file.  A short
# synopsis follows.
#
# This file controls: which hosts are allowed to connect, how clients
# are authenticated, which PostgreSQL user names they can use, which
# databases they can access.  Records take one of these forms:
#
# local         DATABASE  USER  METHOD  [OPTIONS]
# host          DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostssl       DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostnossl     DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostgssenc    DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostnogssenc  DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
...
# CAUTION: Configuring the system for local "trust" authentication
# allows any local user to connect as any PostgreSQL user, including
# the database superuser.  If you do not trust all your local users,
# use another authentication method.

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# IPv4 local area network connections
host    all             all             192.168.100.0/24        md5

Após a edição dos arquivos de configuração, o PostgreSQL precisa ser reiniciado.

root@pi:/home/freebsd # service postgresql onerestart
2021-05-26 11:14:11.820 UTC [1308] LOG:  ending log output to stderr
2021-05-26 11:14:11.820 UTC [1308] HINT:  Future log output will go to log destination "syslog".

Executando novamente o comando sockstat pode-se ver que agora o PostgreSQL está escutando todos os endereços de IP, e não mais apenas o hospedeiro local.

root@pi:/home/freebsd # sockstat -4 -6 -P tcp -p 5432
USER     COMMAND    PID   FD PROTO  LOCAL ADDRESS         FOREIGN ADDRESS
postgres postgres   91738 6  tcp6   *:5432                *:*
postgres postgres   91738 7  tcp4   *:5432                *:*

Início automático do PostgreSQL

Para o serviço postgresql ser iniciado automaticamente quando o sistema operacional é carregado, deve ser adicionada a linha postgresql_enable=“YES” ao arquivo /etc/rc.conf. Em vez de editar o arquivo, podemos fazer isso conforme mostrado abaixo:

root@pi:/home/freebsd # service postgresql oneenable
postgresql enabled in /etc/rc.conf

Acesso remoto ao banco de dados

Finalmente vamos testar o acesso remoto ao PostgreSQL a partir de outro computador da rede:

halley@bsd:~ $ psql --username=pguser --host=raspberry.pi --dbname=pgbase --password
Password:
psql (13.3)
Type "help" for help.

pgbase=>

Referências

* * *