Hash :
2e8a3d5b
Author :
Date :
2016-02-18T09:27:48
1 2 3 4 5 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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
defmodule ExOvh.Ovh.OpenstackApi.Webstorage.Cache do
@moduledoc :false
use GenServer
alias ExOvh.Ovh.OpenstackApi.Webstorage.Supervisor, as: WebStorageSupervisor
import ExOvh.Query.Ovh.Webstorage, only: [get_webstorage_credentials: 1]
@get_credentials_retries 10
@get_credentials_sleep_interval 150
#####################
# Public
#####################
@doc "Starts the genserver"
def start_link({client, config, opts}, service) do
Og.context(__ENV__, :debug)
GenServer.start_link(__MODULE__, {client, service}, [name: gen_server_name(client, service)])
end
def get_credentials(service), do: get_credentials(ExOvh, service)
def get_credentials(client, service) do
unless supervisor_exists?(client, service), do: Supervisor.start_child(WebStorageSupervisor, [service])
get_credentials(client, service, 0)
end
def get_credentials_token(service), do: get_credentials_token(ExOvh, service)
def get_credentials_token(client, service), do: get_credentials(client, service).token
def get_swift_endpoint(service), do: get_swift_endpoint(ExOvh, service)
def get_swift_endpoint(client, service) do
credentials = get_credentials(client, service)
path = URI.parse(credentials.swift_endpoint) |> Map.get(:path)
{version, account} = String.split_at(path, 4)
endpoint = List.first(String.split(credentials.swift_endpoint, account))
endpoint
end
def get_account(service), do: get_account(ExOvh)
def get_account(client, service) do
credentials = get_credentials(client, service)
path = URI.parse(credentials.swift_endpoint) |> Map.get(:path)
{version, account} = String.split_at(path, 4)
account
end
#####################
# Genserver Callbacks
#####################
# trap exits so that terminate callback is invoked
# the :lock key is to allow for locking during the brief moment that the access token is being refreshed
def init({client, service}) do
Og.context(__ENV__, :debug)
:erlang.process_flag(:trap_exit, :true)
create_ets_table(client, service)
{:ok, credentials} = identity(service)
credentials = Map.put(credentials, :lock, :false)
:ets.insert(ets_tablename(client, service), {:credentials, credentials})
expires = to_seconds(credentials.token_expires_on)
Task.start_link(fn -> monitor_expiry(expires) end)
{:ok, {client, service, credentials}}
end
def handle_call(:add_lock, _from, {client, service, credentials}) do
Og.context(__ENV__, :debug)
new_credentials = Map.put(credentials, :lock, :true)
:ets.insert(ets_tablename(client, service), {:credentials, new_credentials})
{:reply, :ok, {client, service, new_credentials}}
end
def handle_call(:remove_lock, _from, {client, service, credentials}) do
Og.context(__ENV__, :debug)
new_credentials = Map.put(credentials, :lock, :false)
:ets.insert(ets_tablename(client, service), {:credentials, new_credentials})
{:reply, :ok, {client, service, new_credentials}}
end
def handle_call(:update_credentials, _from, {client, service, credentials}) do
Og.context(__ENV__, :debug)
{:ok, new_credentials} = identity(service)
|> Map.put(credentials, :lock, :false)
:ets.insert(ets_tablename(client, service), {:credentials, new_credentials})
{:reply, :ok, {client, service, new_credentials}}
end
def handle_call(:stop, _from, state) do
Og.context(__ENV__, :debug)
{:stop, :shutdown, :ok, state}
end
def terminate(:shutdown, {client, service, credentials}) do
Og.context(__ENV__, :debug)
:ets.delete(ets_tablename(client, service)) # explicilty remove
:ok
end
#####################
# Private
#####################
defp gen_server_name(client, service), do: String.to_atom(Atom.to_string(client) <> service)
defp ets_tablename(client, service), do: String.to_atom(Atom.to_string(client) <> "-" <> service)
#@spec identity(service :: String.t, username :: String.t, password :: String.t)
# :: {:ok, map()} | {:error, map()} ??
# This function probably should be broken down into smaller parts
def identity(service) do
{:ok, resp} = ExOvh.ovh_request(get_webstorage_credentials(service), %{})
%{
"endpoint" => endpoint,
"login" => login,
"password" => password,
"tenant" => tenant
} = resp.body
params = %{"auth" =>
%{
"passwordCredentials" => %{"username" => login, "password" => password}
}
}
options = %{
body: params |> Poison.encode!,
headers: %{ "Content-Type": "application/json; charset=utf-8" },
timeout: 10_000
}
resp = HTTPotion.request(:post, endpoint <> "/tokens", options)
unless resp.status_code >= 200 and resp.status_code <= 203, do: raise resp.body
%{
"access" =>
%{
"token" => %{
"expires" => expires_on,
"id" => token,
"issued_at" => created_on
},
}
} = Poison.decode!(resp.body)
params = %{"auth" =>
%{
"tenantName" => tenant,
"token" => %{"id" => token}}
}
options = %{
body: params |> Poison.encode!,
headers: %{ "Content-Type": "application/json; charset=utf-8" },
timeout: 10_000
}
resp = HTTPotion.request(:post, endpoint <> "/tokens", options)
unless resp.status_code >= 200 and resp.status_code <= 203, do: raise resp.body
%{
"serviceCatalog" => [
%{
"endpoints" => [%{"publicURL" => swift_endpoint}],
"name" => "swift",
},
%{
"endpoints" => [%{"publicURL" => identity_endpoint}],
"name" => "keystone",
}
],
"token" => %{
"expires" => token_expires_on,
"id" => token,
"issued_at" => token_created_on,
},
"user" => _user
} = Poison.decode!(resp.body) |> Map.get("access")
{:ok,
%{
token: token,
token_expires_on: expires_on,
token_created_on: token_created_on,
swift_endpoint: swift_endpoint,
identity_endpoint: identity_endpoint,
service: service
}
}
end
defp get_credentials(client, service, index) do
Og.context(__ENV__, :debug)
if ets_tablename(client, service) in :ets.all() do
[credentials: credentials] = :ets.lookup(ets_tablename(client, service), :credentials)
if credentials.lock === :true do
if index > @get_credentials_retries do
raise "Cannot retrieve openstack credentials from ets table, #{__ENV__.module}, #{__ENV__.line}"
else
:timer.sleep(@get_credentials_sleep_interval)
get_credentials(client, service, index + 1)
end
else
credentials
end
else
if index > @get_credentials_retries do
raise "Cannot retrieve openstack credentials from ets table, #{__ENV__.module}, #{__ENV__.line}"
else
:timer.sleep(@get_credentials_sleep_interval)
get_credentials(client, service, index + 1)
end
end
end
defp monitor_expiry(expires) do
Og.context(__ENV__, :debug)
interval = (expires - 30) * 1000
:timer.sleep(interval)
{:reply, :ok, _credentials} = GenServer.call(self(), :add_lock)
{:reply, :ok, _credentials} = GenServer.call(self(), :update_credentials)
{:reply, :ok, credentials} = GenServer.call(self(), :remove_lock)
expires = to_seconds(credentials["expires"])
monitor_expiry(expires)
end
defp create_ets_table(client, service) do
Og.context(__ENV__, :debug)
ets_options = [
:set, # type
:protected, # read - all, write this process only.
:named_table,
{:heir, :none}, # don't let any process inherit the table. when the ets table dies, it dies.
{:write_concurrency, :false},
{:read_concurrency, :true}
]
unless ets_tablename(client, service) in :ets.all() do
:ets.new(ets_tablename(client, service), ets_options)
end
end
defp to_seconds(iso_time) do
{:ok, expiry_ndt, offset} = Calendar.NaiveDateTime.Parse.iso8601(iso_time)
{:ok, expiry_dt_utc} = Calendar.NaiveDateTime.with_offset_to_datetime_utc(expiry_ndt, offset)
{:ok, now} = Calendar.DateTime.from_erl(:calendar.universal_time(), "UTC")
{:ok, seconds, _microseconds, _when} = Calendar.DateTime.diff(expiry_dt_utc, now)
if seconds > 0 do
seconds
else
0
end
end
defp supervisor_exists?(client, service) do
Process.whereis(registered_supervisor_name(client, service))
end
defp registered_supervisor_name(client, service) do
String.to_atom(Atom.to_string(client) <> service)
end
end