Skip to content

Instantly share code, notes, and snippets.

@michaeldauria
Created May 29, 2012 21:28
Show Gist options
  • Save michaeldauria/2830829 to your computer and use it in GitHub Desktop.
Save michaeldauria/2830829 to your computer and use it in GitHub Desktop.
Migrate from mongodb master/slave to replica sets
#!/bin/env ruby
# Caveat: your must ensure no writes are going into the system
# Total time for this migration, including a restart of mongo
# is less than 10s
require 'mongo'
replica_set = 'replica_set_name'
primary_host = 'primary.local'
primary_port = 27017
secondary_host = 'secondary.local'
secondary_port = 27017
puts 'initialize replica set'
primary = Mongo::Connection.new(primary_host, primary_port, { safe: true })
begin
puts primary['admin'].command(replSetInitiate: nil)
rescue
end
primary.close
primary = Mongo::Connection.new(primary_host, primary_port, { safe: true })
print 'writing something'
begin
primary['test']['replset'].insert({write: 1})
rescue
print '.'
sleep(2)
retry
end
puts ''
puts 'pulling oplog for write'
fake_write = primary['local']['oplog.rs'].find().to_a.last
print 'clone oplog entry'
secondary = Mongo::Connection.new(secondary_host, secondary_port, { safe: true })
secondary['local'].create_collection('oplog.rs', { capped: true, size: 4003196912 }) # 3.72GB
begin
secondary['local']['oplog.rs'].insert(fake_write)
rescue
print '.'
sleep(2)
retry
end
puts ''
puts 'add secondary member'
replset_config = primary['local']['system.replset'].find().to_a.first
replset_config['members'] << { _id: 1, host: [ secondary_host, secondary_port.to_s ].join(':') }
replset_config['version'] += 1
primary['admin'].command(replSetReconfig: replset_config)
puts 'done'
@josegonzalez
Copy link

You could have two different data dirs, but I guess moving within a datacenter isn't too bad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment