jam-cloud/ruby/lib/jam_ruby/resque/scheduled/icecast_source_check.rb

62 lines
2.1 KiB
Ruby

require 'json'
require 'resque'
require 'resque-lonely_job'
require 'net/http'
require 'digest/md5'
module JamRuby
# http://blog.bignerdranch.com/1643-never-use-resque-for-serial-jobs/
# periodically scheduled to find sources that need to be brought down, or alternatively, it seems the client failed to start sourcing
class IcecastSourceCheck
extend Resque::Plugins::LonelyJob
@queue = :scheduled_icecast_source_check
@@log = Logging.logger[IcecastSourceCheck]
def self.lock_timeout
# this should be enough time to make sure the job has finished, but not so long that the system isn't recovering from a abandoned job
120
end
def self.perform
@@log.debug("waking up")
IcecastSourceCheck.new.run
@@log.debug("done")
end
def run
# we need to find any mount in the following conditions and then poke it with a websocket msg. here are the conditions:
# * (if sourced_needs_changing_at has gone too far in the past OR sourced_needs_changing_at IS NULL) AND
# ** listeners > 0 and sourced is DOWN (false)
# ** listeners == 0 and sourced is UP (true)
IcecastMount.find_each(lock: true, :conditions => "( (listeners > 0 AND sourced = FALSE) OR (listeners = 0 AND sourced = TRUE) ) AND ( sourced_needs_changing_at IS NULL OR sourced_needs_changing_at < (NOW() - interval '#{APP_CONFIG.icecast_max_sourced_changed} second') ) ", :batch_size => 100) do |mount|
if mount.music_session_id
mount.with_lock do
handle_notifications(mount)
end
end
end
end
def handle_notifications(mount)
if mount.listeners == 0 && mount.sourced
# if no listeners, but we are sourced, then ask it to stop sourcing
@@log.debug("SOURCE_DOWN_REQUEST called on mount #{mount.name}")
mount.notify_source_down_requested
elsif mount.listeners > 0 && !mount.sourced
# if we have some listeners, and still are not sourced, then ask to start sourcing again
@@log.debug("SOURCE_UP_REQUEST called on mount #{mount.name}")
mount.notify_source_up_requested
end
end
end
end