require 'sinatra/base'
require 'haml'
require 'kthxbye'
module Kthxbye
class WebInterface < Sinatra::Base #:nodoc: all
base = File.dirname( File.expand_path(__FILE__) )
set :views, "#{base}/web_interface/views"
set :public, "#{base}/web_interface/public"
set :static, true
set :environment, :development
helpers do
include Rack::Utils
def toggle_poll
if @active
text = "Last update: #{Time.now.strftime("%H:%M:%S")}"
else
text = "Live Poll"
end
"
#{text}
"
end
def url(*path_parts)
[ path_prefix, path_parts ].join("/").squeeze('/')
end
def path_prefix
request.env['SCRIPT_NAME']
end
def show(page, layout=true)
begin
haml page.to_sym, {:layout => layout}, :kthxbye => Kthxbye
rescue Errno::ECONNREFUSED
haml :error, {:layout => false}, :error => "Can't connect to Redis at #{Kthxbye::Config.options[:redis_server]}:#{Kthxbye::Config.options[:redis_port]}"
end
end
def partial(template, local_vars = {})
haml template.to_sym, {:layout => false}, local_vars
end
def current_url
url request.path_info.split("/")
end
def mark_current(page)
'current' if current_url[1..-1] == page.split(" ").first
end
def tab(name)
name.to_s.downcase!
path = url(name)
"#{name}"
end
def tabs
@tabs ||= ["Overview", "Workers (#{Kthxbye.workers.size})", "Failed (#{Kthxbye::Failure.all.size})", "Queues (#{Kthxbye.queues.size})", "Stats"]
end
end
# default route
get "/?" do
redirect url(:overview)
end
%w(overview workers failed queues stats).each do |page|
get "/#{page}" do
show page
end
end
get "/stats/:id" do
show :stats
end
get "/stats/keys/:key" do
show :stats
end
%w(overview workers).each do |page|
get "/#{page}.poll" do
@active = true
content_type "text/plain"
show(page.to_sym, false)
end
end
get "/view_backtrace" do
@backtrace = Kthxbye::Failure.find(params[:id])['backtrace']
haml :view_backtrace, {:layout => :layout}
end
post "/queues/:q/remove" do
Kthxbye.delete_queue(params[:q])
redirect url(:overview)
end
get "/queues/:q" do
@queue = params[:q]
haml :queue, {:layout => :layout}
end
post "/failed/:job/rerun" do
Kthxbye::Failure.rerun(params[:job])
redirect url(:failed)
end
post "/failed/:job/clear" do
job = Kthxbye::Failure.clear_exception(params[:job])
redirect url(:failed)
end
post "/failed/clear" do
Kthxbye::Failure.clear_all
redirect url(:queues)
end
post "/toggle_polling" do
redirect url(:overview)
end
end
end