Skip to content

Instantly share code, notes, and snippets.

@user454322
Created November 23, 2015 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save user454322/c4fbfd93360960513625 to your computer and use it in GitHub Desktop.
Save user454322/c4fbfd93360960513625 to your computer and use it in GitHub Desktop.
CouchDB replication
#!/usr/bin/env ruby
#Start CouchDB replication with
#curl -X POST -d '{"source":"https://user:passwd@src_ip:6984/source_db", "target":"https://user:passwd@dst_ip:6984/dst_db", continuous:true}' -H 'Content-Type: application/json' https://host:6984/_replicator
# This script checks a list of databases that should be replicating and their last replication time.
# If the replication hasn't been updated in an hour, an email is sent to 'email@example.com'
# with the subject 'CouchDB replication problem'.
#'/etc/couchdb/monitoring-config.json'
#{
# "protocol": "http",
# "host":"myhost.com",
# "port":5984,
# "user":"db_user",
# "password":"XXXXX",
#
#
# "smtp_host":"smtp.example.com",
# "smtp_port":587,
# "smtp_user_name":"email@example.com",
# "smtp_password":"xxxxxx"
#}
require "rubygems"
require "json"
require "mail"
LAST_UPDATE_LIMIT_IN_SECONDS=3600
REPLICATED_DB=["mydb", "yourdb", "ourdb"]
def check_replication(task)
source = task['source']
target = task['target']
updated_on = task['updated_on']
return false unless target.include? source
return false unless (Time.now.to_i - updated_on) > LAST_UPDATE_LIMIT_IN_SECONDS
true
end
def send_email(config, msg)
options = {
:address => config['smtp_host'],
:port => config['smtp_port'],
:domain => 'example.com',
:user_name => config['smtp_user_name'],
:password => config['smtp_password'],
:authentication => 'plain',
:enable_starttls_auto => true }
Mail.defaults do
delivery_method :smtp, options
end
Mail.deliver do
to 'email@example.com'
from 'DBA@example.com'
subject 'CouchDB replication problem'
body "#{msg}"
end
end
config = JSON.parse(File.read('/etc/couchdb/monitoring-config.json'))
url="#{config['protocol']}://#{config['user']}:#{config['password']}@#{config['host']}:#{config['port']}/_active_tasks"
string = `curl -s #{url}`
tasks = JSON.parse(string)
databases = REPLICATED_DB.dup
message = ""
tasks.each { |t|
next unless t['type'] == 'replication'
databases.delete(t['source'])
next unless check_replication(t)
message << sprintf("Replication task [%s] doesn't look right:\n", t['replication_id'])
message << sprintf(" source:'%s' target:'%s'\n", t['source'], t['target'])
message << sprintf(" last update %d s ago\n", Time.now.to_i - t['updated_on'])
message << sprintf(" %s\n\n",t)
}
message << "Couldn't find replication for #{databases}" unless databases.empty?
if !message.empty?
#`logger -s "CouchDB replication: #{message}"`
send_email(config, message)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment