Skip to content

Instantly share code, notes, and snippets.

@jcsalterego
Created December 19, 2011 19:42
Show Gist options
  • Select an option

  • Save jcsalterego/1498555 to your computer and use it in GitHub Desktop.

Select an option

Save jcsalterego/1498555 to your computer and use it in GitHub Desktop.
module Tern
module Db
module Reach
class Migration
attr_accessor :instance, :error
# Constructor
# * +instance+ :: Valid tern instance
def initialize(instance)
self.instance = instance
end
# Moves reach tern to destination reach shard
# Any exceptions raised will abort the entire process,
# log the error and set @error for potential use by the caller,
# e.g. rake task
# * +dest_reach_shard+ :: Destination reach shard
def execute_now!(dest_reach_shard)
set_dest_reach_shard(dest_reach_shard)
preflight
start
copy
verify
finish
rescue => e
logger.error(e)
self.error = e
false
end
# Preflight checks
def preflight
if meta.migrating?
raise("Instance is already migrating. Aborting.")
elsif meta.queueing?
raise("Instance is already queued; assigned workers "
"may exist. Aborting.")
elsif src_reach_shard == dest_reach_shard
raise("Source and destination reach shards are the same. "
"Aborting.")
elsif !src_reach_client.node("/").exists?
raise("Source reach shard tern instance does not exist. "
"[This is an impossible situation!] Aborting.")
elsif dest_reach_client.node("/").exists?
raise("Destination reach shard tern instance already exists. "
"Aborting.")
elsif reach_currently_running?
raise("Reach is currently running for this instance. Aborting.")
else
logger.info("Preflight checks passed.")
end
end
# Set migration status and queue
def start
meta.update_attributes(
:status_id=>Tern::Db::MetaInstance::MIGRATING,
:queue=>meta_queue)
logger.info("Set migration status and queue to #{queue}")
end
# Copies periods and deliveries with rsync
def copy
rsync_dirs(src_reach_client.node("/").path,
dest_reach_client.node("/").path)
end
# Calculates checksums for all period files in the source and
# destination reach shards. If there is a discrepancy, raise
# an exception with details.
def verify
src_checksums = period_checksums(src_reach_client)
dest_checksums = period_checksums(dest_reach_client)
if src_checksums != dest_checksums
raise checksum_diff_msg(src_checksums,dest_checksums)
end
end
# Updates the meta instance
def finish
if not migrating?
raise("Attempting to finish but meta tern is NOT in "
"migration mode. This is potentially very bad! Aborting.")
elsif meta.reach_shard == dest_reach_shard
raise("Attempting to finish but meta tern is ALREADY in "
"destination reach shard. This is potentially very bad! "
"Aborting.")
end
logger.info("Moving from #{src_reach_shard.name} to "
"#{dest_reach_shard.name}")
meta.update_attributes(:reach_shard_id=>dest_shard.id)
logger.info("Updating instance counts for #{src_reach_shard.name} "
"and #{dest_reach_shard.name}")
dest_reach_shard.add_instance!
src_reach_shard.remove_instance!
meta.update_attributes(:status_id=>Tern::Db::MetaInstance::ONLINE)
logger.info("Online on #{dest_reach_shard.name}, "
"queued at #{meta_queue}")
end
private
# Check resque workers to see if reach is running for instance
def reach_currently_running?
# XXX check resque workers..
false
end
# Sets the destination reach shard and client
def set_dest_reach_shard(dest_reach_shard)
self.dest_reach_shard = dest_reach_shard
# force creation of destination reach client
dest_reach_client
end
# Given two checksum hashes, show differing keys.
# Meant to be used with exception messages/logging.
# * +cks1+ :: First checksum hash
# * +cks2+ :: Second checksum hash
def checksum_diff_msg(cks1,cks2)
rv = []
keys = Set.new(cks1.keys) | Set.new(cks2.keys)
keys.each do |key|
if cks1[key] != cks2[key]
rv << ("Checksums for #{key} differ: "
"#{cks1[key] || 'nil'} and #{cks2[key] || 'nil'}")
end
end
rv.join("\n")
end
# Given a reach client, calculate the period checksums
# Assumes zst-based period files
# * +reach_client+ :: Reach client tied to shard and tern instance
def period_checksums(reach_client)
dir = reach_client.node("/periods").path
glob = "{,1,2,3,4}","*.zst"
md5_checksums(:dir=>dir,:glob=>glob)
end
###################
## MD5 and rsync ##
###################
# Multi-platform MD5 sum calculator
# * +opts[:dir]+ :: base directory
# * +opts[:glob]+ :: glob pattern
def md5_checksums(opts={})
if (platform=`uname`) =~ /Darwin/
darwin_md5_checksums(opts)
elsif platform =~ /Linux/
linux_md5_checksums(opts)
else
raise "Unknown platform, could not calculate md5sum. Aborting."
end
end
# Calculate MD5 checksums on Darwin/OSX
def darwin_md5_checksums(opts={})
# Example `md5` output:
# 0b2ef2cd363fcd598b8ec6de09237d4d test.json
# 578043b5264750d44928e957a9b996db test.log
rv = `cd #{opts[:dir]} && md5 -r #{opts[:glob]}`
if $?.exitstatus != 0
raise "Unclean exit (code=#{$?.exitstatus}) by md5sum. Aborting"
end
rv.split(/\n/).inject({}) do |h,line|
words = line.strip.split
unless words.empty?
h[words[1]] = words[0]
end
h
end
end
# Calculate MD5 checksums on Linux
def linux_md5_checksums(opts={})
rv = `cd #{opts[:dir]} && md5sum #{opts[:glob]}`
if $?.exitstatus != 0
raise "Unclean exit (code=#{$?.exitstatus}) by md5sum. Aborting"
end
# XXX process that stuff, yo
rv.split(/\n/).inject({}) do |h,line|
words = line.strip.split
unless words.empty?
# ...
end
h
end
{}
end
# Wrapper for +rsync+ for copying directories locally
# * +src_path+ :: Source path
# * +dest_path+ :: Destination path
def rsync_dirs(src_path,dest_path)
rv = `rsync -av #{src_path}/ #{dest_path}/`
if $?.exitstatus != 0
raise "Unclean exit (code=#{$?.exitstatus}) by rsync. Aborting"
end
# return last line of output for good measure
rv.split(/\n/)[-1]
end
#######################################
## Convenience & Memoization Methods ##
#######################################
def src_reach_shard
@src_reach_shard ||= meta.reach_shard
end
def src_reach_client
@src_reach_client ||= meta.reach_shard.new_client(instance)
end
def dest_reach_client
@dest_reach_client ||= dest_reach_shard.new_client(instance)
end
def meta
@meta ||= instance.meta
end
def logger
@logger ||= Logging::NsLogger.new(
"#{instance.name}::Reach::Migration",instance.logger)
end
def meta_queue
@meta_queue ||= "tweetreach:stream:#{instance.name}"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment