Skip to content

Instantly share code, notes, and snippets.

@pixie79
Last active February 26, 2018 11:06
Show Gist options
  • Save pixie79/947d5fc01be3d92da6532a81232cd212 to your computer and use it in GitHub Desktop.
Save pixie79/947d5fc01be3d92da6532a81232cd212 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Copyright 2016 The Kubernetes Authors. All rights reserved.
#
# 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.
replica_set=${REPLICA_SET}
peers=()
for ID in $(seq 0 $(expr ${REPLICA_COUNT} - 1))
do
peers+=(${NAME}-${ID}.${DOMAIN})
done
echo ${peers[@]} > /work-dir/peers.yaml
script_name=${0##*/}
if [[ "$AUTH" == "true" ]]; then
admin_user="$ADMIN_USER"
admin_password="$ADMIN_PASSWORD"
admin_auth=(-u "$admin_user" -p "$admin_password")
fi
function shutdown_mongo() {
if [[ $# -eq 1 ]]; then
args="timeoutSecs: $1"
else
args='force: true'
fi
echo "Shutting down MongoDB ($args)..."
mongo admin "${admin_auth[@]}" "${ssl_args[@]}" --eval "db.shutdownServer({$args})"
}
my_hostname=$(hostname)
service_name=$(hostname -f)
id=$(echo "${service_name}" | cut -d '.' -f 1 | cut -d '-' -f 2)
echo "Bootstrapping MongoDB replica set member: ${my_hostname}"
echo "Current Peers: ${peers}"
# Generate the ca cert
ca_crt=/ca/tls.crt
if [ -f $ca_crt ]; then
echo "Generating certificate"
ca_key=/ca/tls.key
pem=/work-dir/mongo.pem
ssl_args=(--ssl --sslCAFile $ca_crt --sslPEMKeyFile $pem)
cat >openssl.cnf <<EOL
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = $(echo -n "$my_hostname" | sed s/-[0-9]*$//)
DNS.2 = $my_hostname
DNS.3 = $service_name
DNS.4 = localhost
DNS.5 = 127.0.0.1
EOL
# Generate the certs
openssl genrsa -out mongo.key 2048
openssl req -new -key mongo.key -out mongo.csr -subj "/CN=$my_hostname" -config openssl.cnf
openssl x509 -req -in mongo.csr \
-CA $ca_crt -CAkey $ca_key -CAcreateserial \
-out mongo.crt -days 3650 -extensions v3_req -extfile openssl.cnf
rm mongo.csr
cat mongo.crt mongo.key > $pem
rm mongo.key mongo.crt
fi
echo "Peers: ${peers[@]}"
echo "Starting a MongoDB instance..."
mongod --config /config/mongod.conf &
echo "Waiting for MongoDB to be ready..."
until mongo "${ssl_args[@]}" --eval "db.adminCommand('ping')"; do
echo "Retrying..."
sleep 2
done
echo "Initialized."
# try to find a master and add yourself to its replica set.
# export peers=(mongo-0 mongo-1 mongo-2)
for peer in "${peers[@]}"; do
mongo admin --host "$peer" "${admin_auth[@]}" "${ssl_args[@]}" --eval "rs.isMaster()" | grep '"ismaster" : true'
if [[ $? -eq 0 ]]; then
echo "Found master: $peer"
echo "Adding myself ($service_name) to replica set..."
mongo admin --host "$peer" "${admin_auth[@]}" "${ssl_args[@]}" --eval "rs.add('$service_name:27017')"
echo "Done."
shutdown_mongo "60"
echo "Good bye."
exit 0
fi
done
# else initiate a replica set with yourself.
mongo "${ssl_args[@]}" --eval "rs.status()" | grep "no replset config has been received"
if [[ $? -eq 0 ]]; then
echo "Initiating a new replica set with myself (${service_name})..."
mongo "${ssl_args[@]}" --eval "rs.initiate({'_id': '$replica_set', 'members': [{'_id': ${id}, host: '${service_name}:27017'}]})"
mongo "${ssl_args[@]}" --eval "rs.status()"
if [[ "$AUTH" == "true" ]]; then
# sleep a little while just to be sure the initiation of the replica set has fully
# finished and we can create the user
sleep 3
echo "Creating admin user..."
mongo admin "${ssl_args[@]}" --eval "db.createUser({user: '$admin_user', pwd: '$admin_password', roles: [{role: 'root', db: 'admin'}]})"
fi
echo "Done."
fi
shutdown_mongo
echo "Good bye."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment