Class: MistFiles

Inherits:
Object
  • Object
show all
Defined in:
lib/mistfiles.rb,
lib/mistfiles/objects.rb,
lib/mistfiles/containers.rb,
lib/mistfiles/send_request.rb,
lib/mistfiles/authentication.rb

Constant Summary collapse

RS_SERVICE_TYPES =
["object-store", "rax:object-cdn"]
VERB_MAP =
{
  :get    => Net::HTTP::Get,
  :post   => Net::HTTP::Post,
  :put    => Net::HTTP::Put,
  :patch  => Net::HTTP::Patch,
  :delete => Net::HTTP::Delete,
  :head   => Net::HTTP::Head
}
DEFAULT_HTTP_HEADERS =
{
  "Accept" => "application/json",
  "Content-Type" => "application/json"
}
AuthenticationError =
Class.new(StandardError)
RACKSPACE_US_URL =
"https://identity.api.rackspacecloud.com/"
RACKSPACE_UK_URL =
"https://lon.identity.api.rackspacecloud.com/"

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ MistFiles

Returns a new instance of MistFiles.



9
10
11
12
13
14
15
# File 'lib/mistfiles.rb', line 9

def initialize(opts={})
  @username = opts[:username] || opts["username"]
  @api_key = opts[:api_key] || opts["api_key"]
  @region = (opts[:region] || opts["region"]).downcase.to_sym
  @british = (opts[:british] || opts["british"]) || false
  @internal = (opts[:internal] || opts["internal"]) || false
end

Instance Method Details

#auth_if_necessary!Object



56
57
58
# File 'lib/mistfiles/authentication.rb', line 56

def auth_if_necessary!
  authenticate! unless authenticated?
end

#authenticate!Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/mistfiles/authentication.rb', line 18

def authenticate!
  json_body = {
    :auth => {
      "RAX-KSKEY:apiKeyCredentials" => {
        :username => @username,
        :apiKey => @api_key
      }
    }
  }
  
  res = send_request(
    :host => @british ? RACKSPACE_UK_URL : RACKSPACE_US_URL,
    :path => "/v2.0/tokens",
    :method => :post,
    :body_type => :json,
    :params => json_body
  )

raise AuthenticationError, "HTTP error #{res.code}" if res.code < 200 || res.code > 299
  
  body = JSON.parse(res.body)
  raise AuthenticationError, "#{self.class}: Invalid response data, something must be wrong." unless body.member?("access")
  access = body["access"]

  @token = access["token"]["id"]
  @expires = DateTime.parse(access["token"]["expires"])
  @user = access["user"]
  @user[:id] = @user.delete "id"
  @user[:username] = @user.delete "name"
  @user[:default_region] = @user.delete("RAX-AUTH:defaultRegion").downcase.to_sym
  
  catalog = access["serviceCatalog"].select { |service| RS_SERVICE_TYPES.include?(service["type"]) }.each_with_object({}) { |entry,ctlg| ctlg[entry["type"]] = entry["endpoints"] }
  
  @cdn_catalog = Hash[catalog["rax:object-cdn"].map{ |endpt| [endpt["region"].downcase.to_sym, endpt["publicURL"]] }]
  @files_catalog = Hash[catalog["object-store"].map{ |endpt| [endpt["region"].downcase.to_sym, endpt[@internal ? "internalURL" : "publicURL"]] }]
  nil
end

#authenticated?Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/mistfiles/authentication.rb', line 14

def authenticated?
  @token && @token.length > 0 && @expires && @expires.to_time.to_i > Time.now.to_i
end

#cdn_settings(params = {}) ⇒ Object



98
99
100
101
102
103
104
105
106
# File 'lib/mistfiles/containers.rb', line 98

def cdn_settings(params={})
auth_if_necessary!
  container = params[:container] || params["container"]
  send_request(
    :host => @cdn_catalog[@region],
    :path => "/#{container}",
    :method => :head
  )
end

#cdn_settings=(params = {}) ⇒ Object

parameters :ttl => The ttl in seconds :enabled => A true or false value indicating the CDN status of the container :log_retention => Whether RackSpace should store CDN access logs in the container. IMPORTANT: if the log_retention parameter is passed, this request will not be able to



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/mistfiles/containers.rb', line 76

def cdn_settings=(params={})
auth_if_necessary!
  container = params[:container] || params["container"]
  ttl = (params[:ttl] || params["ttl"]).to_i.to_s
  enabled = (params[:enabled] || params["enabled"]) ? "True" : "False"
  log_retention = params[:log_retention] || params["log_retention"]
  
  headers = {}
  headers["X-Ttl"] = ttl unless ttl.nil? || ttl.empty?
  headers["X-Cdn-Enabled"] = container unless container.nil? || container.empty?
  headers["X-Log-Retention"] = log_retention if params.member?(:log_retention) || params.member?("log_retention")
  
  method = headers.member?("X-Log-Retention") ? :post : :put
  
  send_request(
    :host => @cdn_catalog[@region],
    :path => "/#{container}",
    :method => method,
    :headers => headers
  )
end

#create_container(params = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/mistfiles/containers.rb', line 6

def create_container(params={})
auth_if_necessary!
  container = params[:container] || params["container"]
  headers = params[:headers] || params["headers"]
  send_request(
    :host => @files_catalog[@region],
    :path => "/#{container}",
    :method => :put,
    :params => params || {},
    :headers => headers
  )
end

#create_object(params = {}) ⇒ Object Also known as: update_object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/mistfiles/objects.rb', line 6

def create_object(params={})
auth_if_necessary!
  # Required parameters
  data = params[:data] || params["data"]
  container = params[:container] || params["container"]
  object = params[:object] || params["object"]
  
  # optional parameters
  content_type = params[:content_type] || params["content_type"] # can be detected by Rackspace
  delete_at = (params[:delete_at] || params["delete_at"]).to_i
  delete_after = (params[:delete_after] || params["delete_after"]).to_i
  name = (params[:name] || params["name"])
  
  # TODO: Implement X-Copy-From
  
  headers = {
    "ETag" => Digest::MD5.digest(data)
  }
  
  # Either X-Detect-Content-Type or Content-Type is required
  headers["X-Detect-Content-Type"] = "True" if content_type.nil?
  headers["Content-Type"] = content_type unless content_type.nil?
  headers["X-Object-Meta-name"] = name unless name.nil?
  
  send_request(
    :host => @files_catalog[@region],
    :path => "/#{container}/#{object}",
    :method => :put,
    :body_type => :raw,
    :params => data,
    :headers => headers
  )
end

#delete_object(params = {}) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/mistfiles/objects.rb', line 44

def delete_object(params={})
auth_if_necessary!
  container = params[:container] || params["container"]
  object = params[:object] || params["object"]
  send_request(
    :host => @files_catalog[@region],
    :path => "/#{container}/#{object}",
    :method => :delete
  )
end

#destroy_container(params = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/mistfiles/containers.rb', line 32

def destroy_container(params={})
auth_if_necessary!
  container = params[:container] || params["container"]
  send_request(
    :host => @files_catalog[@region],
    :path => "/#{container}",
    :method => :delete,
    :params => params || {}
  )
end

#get_object(params = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/mistfiles/objects.rb', line 55

def get_object(params={})
auth_if_necessary!
  ontainer = params[:container] || params["container"]
  object = params[:object] || params["object"]
  headers = params[:headers] || params["headers"]
  send_request(
    :host => @files_catalog[@region],
    :path => "/#{container}/#{object}",
    :method => :get,
    :params => params || {},
    :headers => headers,
    :parse_json => false
  )
end

#http(opts = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/mistfiles/send_request.rb', line 41

def http(opts={})
  @http_objs ||= {}
  
  uri = opts[:uri] || opts["uri"]
  http = @http_objs[uri.host]
  return http unless http.nil?
  
  http = Net::HTTP.new uri.host, uri.port
  if uri.port == 443
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  end
  @http_objs[uri.host] = http
  http
end

#list_containers(params = {}) ⇒ Object

list_containers(params={}) :limit => the number of containers to return :marker => returns results after the container name specified here :end_marker => retuns results before the container name



47
48
49
50
51
52
53
54
# File 'lib/mistfiles/containers.rb', line 47

def list_containers(params={})
  auth_if_necessary!
  send_request(
    :host => @files_catalog[@region],
    :method => :get,
    :params => params || {}
  )
end

#list_objects(params = {}) ⇒ Object

lists objects ALSO gets container metadata



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/mistfiles/containers.rb', line 58

def list_objects(params={})
  auth_if_necessary!
  
  container = (params[:container] || params["container"])
  
  send_request(
    :host => @files_catalog[@region],
    :path => "/#{container}",
    :method => :get,
    :params => params || {}
  )
end

#send_request(opts = {}) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/mistfiles/send_request.rb', line 57

def send_request(opts={})
  parse_json  = (opts[:parse_json] || opts["parse_json"]) == true
  host        = opts[:host] || opts["host"]
  path        = opts[:path] || opts["path"] || ""
  method      = (opts[:method] || opts["method"]).to_sym
  params      = opts[:params] || opts["params"] || {}
  body        = opts[:body] || opts["body"]
  body_type   = (opts[:body_type] || opts["body_type"] || :ignored).to_sym
  headers     = DEFAULT_HTTP_HEADERS.merge(opts[:headers] || opts["headers"] || {})
  headers.merge!({ "X-Auth-Token" => @token }) unless @token.nil? || @token.empty?
  
  uri = URI.parse host
  path = uri.path + path
  
  request = 
  case method
  when :get
    path << "?" + URI.encode_www_form(params) unless params.empty?
    VERB_MAP[method].new path
  else
    request = VERB_MAP[method].new path
    case body_type
    when :json
      request.body = 
      case params
      when String
        params
      else
        params.to_json
      end
    when :form_data
      request.set_form_data params
    when :raw
      request.body = body
    end
    request
  end
  
  headers.each { |k,v| request.add_field k,v }

  MistFilesResponse.new(
	:response => http(:uri => uri).request(request),
	:parse_json => parse_json
)
end

#update_container(params = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/mistfiles/containers.rb', line 19

def update_container(params={})
auth_if_necessary!
  container = params[:container] || params["container"]
  headers = params[:headers] || params["headers"]
  send_request(
    :host => @files_catalog[@region],
    :path => "/#{container}",
    :method => :post,
    :params => params || {},
    :headers => headers
  )
end