replicate_pri_init.rb 2.22 KB
#
# Author:: Earth U (<sysadmin @ chromedia.com>)
# Cookbook Name:: cfe-mongodb
# Recipe:: replicate_pri_init
#
# Copyright (C) 2016, Chromedia Far East, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# NOTE:
# The recipe cfe-mongodb::replicate must be run before this
#   in order to restart the node beforehand.
# Otherwise, manually restart the node first because that seems to
#   be the only way for an automated rs.initiate() to proceed.
#   Doing it immediately after mongodb install does not work,
#   nor does implementing delay, or even restarting the mongod service.

# NOTE:
# It is recommended that this cookbook be run on secondary and
#   arbiter nodes first, before finally running it on the primary node.

log  = node['mongodb3']['config']['mongod']['systemLog']
port = node['mongodb3']['config']['mongod']['net']['port']

boot_mark    = "#{::File.dirname(log['path'])}/primary_init_mark"
boot_log     = "#{::File.dirname(log['path'])}/primary_init"
is_logrename = log['logRotate'] == 'rename'

boot_script = "#{Chef::Config[:file_cache_path]}/mongodb_pri_bootstrap.js"

template boot_script do
  sensitive true
  variables(
    :db_map         => node[cookbook_name]['db']['map'],
    :db_pass_root   => node[cookbook_name]['db']['pass_root'],
    :db_pass_backup => node[cookbook_name]['db']['pass_backup'],
    :is_logrename   => is_logrename
  )
end

script 'mongodb_pri_bootstrap' do
  interpreter 'bash'
  not_if { ::File.exist?(boot_mark) }
  code <<-CODE
    set -e
    mongo --host 127.0.0.1 --port #{port} --eval "rs.initiate()" >> #{boot_log}
    sleep #{node[cookbook_name]['rs']['delay']}
    mongo #{boot_script} --host 127.0.0.1 --port #{port} >> #{boot_log}
    date > #{boot_mark}
    CODE
end

file boot_script do
  action :delete
end