Created
July 4, 2012 09:53
-
-
Save mickey/3046449 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'yaml' | |
require 'base64' | |
require 'openssl' | |
require 'net/https' | |
require "rexml/document" | |
class CloudfrontInvalidator | |
def initialize(cf_id, *urls) | |
@batch = "purging " + Time.now.to_s | |
@cf_id = cf_id | |
@url = URI.parse "https://cloudfront.amazonaws.com/2012-05-05/distribution/#{@cf_id}/invalidation" | |
@urls = urls | |
purge! | |
end | |
private | |
def purge! | |
resp = post | |
if resp.code == '201' | |
puts "== OK purging #{@urls.join(",")}" | |
puts "current jobs: #{get}" | |
else | |
puts "== ERROR \n#{resp.body}" | |
puts "current jobs:\n#{get}" | |
end | |
end | |
def response(method, data='') | |
req = Net::HTTP.new(@url.host, @url.port) | |
req.use_ssl = true | |
req.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
req.send_request(method, @url.path, data, headers) | |
end | |
def post | |
response 'POST', purge_list | |
end | |
def get | |
resp_list response 'GET' | |
end | |
def resp_list(resp) | |
list = [] | |
REXML::Document.new(resp.body).each_element("/InvalidationList/InvalidationSummary") do |el| | |
list << el.elements["Id"].text + ":" + el.elements["Status"].text | |
end | |
list.join("\n") | |
end | |
def purge_list | |
<<-EOF | |
<InvalidationBatch> | |
<Paths> | |
<Quantity>#{@urls.size}</Quantity> | |
<Items> | |
#{@urls.map {|u| "<Path>" + u + "</Path>"}.join("")} | |
</Items> | |
</Paths> | |
<CallerReference>#{@batch}</CallerReference> | |
</InvalidationBatch> | |
EOF | |
end | |
def headers | |
s3_credentials = YAML::load_file(File.expand_path('../../config/s3.yml', __FILE__)) | |
abort s3_credentials.inspect unless s3_credentials[Rails.env.to_sym] | |
s3_credentials = s3_credentials[Rails.env.to_sym] | |
date = Time.now.strftime('%a, %d %b %Y %H:%M:%S %Z') | |
signer = OpenSSL::Digest::Digest.new('sha1') | |
digest = OpenSSL::HMAC.digest(signer, s3_credentials['secret_access_key'], date) | |
auth = Base64.encode64(digest).strip | |
{ 'Date' => date, | |
'Authorization'=> ["AWS #{s3_credentials['access_key_id']}:#{auth}"].join(',') } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment