Greg Karékinian 21119fff08 Add a custom resource to set up PostgreSQL 12
Supports both primary and replica. The access rules and firewall have to
be set up outside of the custom resource, so they are part of the
recipes instead

Refs #160
2020-05-11 18:23:11 +02:00

77 lines
2.7 KiB
Ruby

#
# Cookbook:: kosmos-postgresql
# Recipe:: replica
#
# The MIT License (MIT)
#
# Copyright:: 2019, Kosmos Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
postgresql_version = "12"
postgresql_service = "postgresql@#{postgresql_version}-main"
postgresql_custom_server postgresql_version do
role "replica"
tls true unless node.chef_environment == "development"
end
service postgresql_service do
supports restart: true, status: true, reload: true
action [:enable]
end
postgresql_data_bag_item = data_bag_item('credentials', 'postgresql')
primary = postgresql_primary
unless primary.nil?
postgresql_data_dir = "/var/lib/postgresql/#{postgresql_version}/main"
if node['kosmos-postgresql']['ready_to_set_up_replica']
execute "set up replication" do
command <<-EOF
systemctl stop #{postgresql_service}
mv #{postgresql_data_dir} #{postgresql_data_dir}.old
PGPASSWORD=#{postgresql_data_bag_item['replication_password']} pg_basebackup -h #{primary[:ipaddress]} -U replication -D #{postgresql_data_dir} -R
chown -R postgres:postgres #{postgresql_data_dir}
systemctl start #{postgresql_service}
EOF
sensitive true
not_if { ::File.exist? "#{postgresql_data_dir}/standby.signal" }
end
end
postgresql_access "replication" do
access_type "host"
access_db "replication"
access_user "replication"
access_addr "#{primary[:ipaddress]}/32"
access_method "md5"
# notification does not work, as postgresql_access always says the
# resource was already up to date
notifies :reload, "service[#{postgresql_service}]", :immediately
end
# On the next Chef run the replica will be set up
node.normal['kosmos-postgresql']['ready_to_set_up_replica'] = true
end
include_recipe "kosmos-postgresql::firewall"