#!/usr/bin/env ruby require 'webrick' include WEBrick $history = nil $threads = [] $config = { :address => 'rubyforge.lauschmusik.de', :port => 4242, :modules => ["main", "gems"], :htpasswd => "/home/rubyforge/etc/rfsync.htpass", :realm => "rfsync", :serverstring => 'Some piece of code speaking HTTP' } MUTEX = Mutex.new s = HTTPServer.new(:BindAddress => $config[:address], :Port => $config[:port], :ServerSoftware => $config[:serverstring], :SSLEnable => true ) class RfServlet < HTTPServlet::AbstractServlet def sendResult(res, body, code=200, type='text/plain') res.status = code res['Content-Type'] = type res.body = body res end def auth(req, res) @@authenticator.authenticate(req, res) end @@authenticator = HTTPAuth::BasicAuth.new( :UserDB => HTTPAuth::Htpasswd.new($config[:htpasswd]), :Realm => $config[:realm] ) end class SyncServlet < RfServlet def do_GET(req, res) auth(req, res) sendResult(res, "Sync is in process, try again later", 503) and return if MUTEX.locked? target = req.query['target'] if $config[:modules].include?(req.query['target']) sendResult(res, "Invalid module selected for sync", 400) and return if target.nil? $threads << Thread.new { MUTEX.synchronize do $history = {:start => Time.now.to_s, :output => ""} output = `/home/rubyforge/bin/sync #{target}` #output = `/usr/bin/uname -a; sleep 30; echo #{target}` $history[:output], $history[:finish] = output, Time.now.to_s end } sendResult(res, "Triggered sync for #{target}") end end class StatusServlet < RfServlet def do_GET(req, res) auth(req, res) body = "-- Current Time is #{Time.now.to_s} --\n" body += "ATTENTION: sync is currently running!\n" if MUTEX.locked? if $history.nil? body += "-- No completed run yet. --\n" else body += "-- Job started at #{$history[:start]} --\n" body += $history[:output] body += "\n-- Job finished at #{$history[:finish]} --\n" unless $history[:finish].nil? end sendResult(res, body) end end trap("INT") { $threads.each do |t| t.kill if t.alive? end s.shutdown } s.mount('/sync', SyncServlet) s.mount('/status', StatusServlet) s.start