Sha256: 652e1d818a296f3f2f80b7cfea78db8e562b863985b473abfb6fc1c36cafc9ad

Contents?: true

Size: 1.5 KB

Versions: 7

Compression:

Stored size: 1.5 KB

Contents

module CouchTomato
  class Replicator
    # Timeout for a single database replication.
    READ_TIMEOUT = 24 * 60 * 60 # 24 hours in seconds

    def initialize(src_server, dst_server = nil)
      @src_server = CouchRest::Server.new(src_server)
      @dst_server = dst_server ? CouchRest::Server.new(dst_server) : @src_server

      @db_names = @src_server.databases
    end

    def replicate(src_db_name, dst_db_name)
      raise "Source database '#{src_db_name}' does not exist" unless @db_names.include?(src_db_name)

      @dst_server.database!(dst_db_name)

      src_uri = URI.parse(@src_server.uri)
      dst_uri = URI.parse(@dst_server.uri)

      http = Net::HTTP.new(dst_uri.host, dst_uri.port)
      http.read_timeout = READ_TIMEOUT
      http.post('/_replicate', "{\"source\": \"#{src_uri}/#{src_db_name}\", \"target\": \"#{dst_uri}/#{dst_db_name}\"}")
    end

    def replicate_all(suffix = nil)
      @db_names.each do |db_name|
        replicate(db_name, "#{db_name}#{suffix}")
      end
    end

    def replicate_env!(from_env, to_env, prefix=nil)
      source_dbs = @db_names.select do |e|
        if prefix
          e =~ /^#{prefix}_/ && e =~ /_#{from_env}$/
        else
          e =~ /_#{from_env}$/
        end
      end

      source_dbs.each do |source_db|
        target_db = source_db.gsub(/_#{from_env}$/, "_#{to_env}")
        
        puts "Recreating #{target_db}"
        CouchRest::Database.new(@dst_server, target_db).recreate!
        replicate(source_db, target_db)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
couch_tomato-0.2.0 lib/couch_tomato/replicator.rb
couch_tomato-0.1.5 lib/couch_tomato/replicator.rb
couch_tomato-0.1.4 lib/couch_tomato/replicator.rb
couch_tomato-0.1.3 lib/couch_tomato/replicator.rb
couch_tomato-0.1.2 lib/couch_tomato/replicator.rb
couch_tomato-0.1.1 lib/couch_tomato/replicator.rb
couch_tomato-0.1.0 lib/couch_tomato/replicator.rb