Module: FastlyCTL::Fetcher
- Defined in:
- lib/fastlyctl/fetcher.rb
Class Method Summary collapse
- .api_request(method, path, options = {}) ⇒ Object
- .create_token(options) ⇒ Object
- .domain_to_service_id(domain) ⇒ Object
- .get_active_version(id) ⇒ Object
- .get_snippets(id, version) ⇒ Object
- .get_vcl(id, version, generated = false) ⇒ Object
- .get_writable_version(id) ⇒ Object
- .login ⇒ Object
- .upload_snippet(service, version, content, name) ⇒ Object
- .upload_vcl(service, version, content, name, is_main = true, is_new = false) ⇒ Object
Class Method Details
.api_request(method, path, options = {}) ⇒ Object
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 |
# File 'lib/fastlyctl/fetcher.rb', line 3 def self.api_request(method, path, ={}) [:endpoint] ||= :api [:params] ||= {} [:headers] ||= {} [:body] ||= nil [:force_session] ||= false [:expected_responses] ||= [200] [:use_vnd] ||= false headers = {"Accept" => "application/json", "Connection" => "close", "User-Agent" => "FastlyCTL: https://github.com/fastly/fastlyctl"} if [:endpoint] == :app headers["Referer"] = FastlyCTL::FASTLY_APP headers["X-CSRF-Token"] = FastlyCTL::Cookies["fastly.csrf"] if FastlyCTL::Cookies["fastly.csrf"] headers["Fastly-API-Request"] = "true" end if FastlyCTL::Token && ![:force_session] headers["Fastly-Key"] = FastlyCTL::Token else headers["Cookie"] = "" if FastlyCTL::Cookies.length > 0 FastlyCTL::Cookies.each do |k,v| headers["Cookie"] << "#{k}=#{v};" end end headers["Content-Type"] = "application/x-www-form-urlencoded" if (method == :post || method == :put) if [:use_vnd] headers["Accept"] = "application/vnd.api+json" if (method == :post || method == :put) headers["Content-Type"] = "application/vnd.api+json" end [:expected_responses].push(*[201,202,203,204]) end headers.merge!([:headers]) if [:headers].count > 0 # dont allow header splitting on anything headers.each do |k,v| headers[k] = v.gsub(/\r|\n/,'') end url = "#{options[:endpoint] == :api ? FastlyCTL::FASTLY_API : FastlyCTL::FASTLY_APP}#{path}" response = Typhoeus::Request.new( url, method: method, params: [:params], headers: headers, body: [:body] ).run if [:expected_responses].include?(response.response_code) if response.headers["Set-Cookie"] response.headers["Set-Cookie"] = [response.headers["Set-Cookie"]] if response.headers["Set-Cookie"].is_a? String response.headers["Set-Cookie"].each do |c| name, value = c.match(/^([^=]*)=([^;]*).*/i).captures FastlyCTL::Cookies[name] = value end end else case response.response_code when 400 error = "400: Bad API request--something was wrong with the request made by FastlyCTL." when 403 error = "403: Access Denied by API. Run login command to authenticate." when 404 error = "404: Service does not exist or bad path requested." when 503 error = "503: Error from Fastly API--see details below." when 0 error = "0: Network connection error occurred." else error = "API responded with status #{response.response_code}." end error += " Method: #{method.to_s.upcase}, Path: #{path}\n" if ([:use_vnd]) begin error_resp = JSON.parse(response.response_body) rescue JSON::ParserError error_resp = {"errors" => [{"title" => "Error parsing response JSON","details" => "No further information available. Please file a github issue at https://github.com/fastly/fastlyctl"}]} end error_resp["errors"].each do |e| next unless e.key?("title") && e.key?("detail") error += e["title"] + " --- " + e["detail"] + "\n" end else error += "Message from API: #{response.response_body}" end abort error end return response.response_body unless (response.headers["Content-Type"] =~ /json$/) if response.response_body.length > 1 begin return JSON.parse(response.response_body) rescue JSON::ParserError abort "Failed to parse JSON response from Fastly API" end else return {} end end |
.create_token(options) ⇒ Object
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 |
# File 'lib/fastlyctl/fetcher.rb', line 239 def self.create_token() thor = Thor::Shell::Basic.new headers = {} headers["Fastly-OTP"] = [:code] if [:code] FastlyCTL::Fetcher.api_request(:post, "/sudo", { force_session: true, endpoint: :api, params: { user: [:user], password: [:pass] }, headers: headers }) params = { name: [:name], scope: [:scope], user: [:user], password: [:pass] } params[:services] = [:services] if [:services] resp = FastlyCTL::Fetcher.api_request(:post, "/tokens", { force_session: true, endpoint: :api, params: params, headers: headers }) thor.say("\n#{resp["id"]} created.") return resp end |
.domain_to_service_id(domain) ⇒ Object
114 115 116 117 118 119 120 121 122 |
# File 'lib/fastlyctl/fetcher.rb', line 114 def self.domain_to_service_id(domain) response = Typhoeus::Request.new(FastlyCTL::FASTLY_APP, method:"FASTLYSERVICEMATCH", headers: { :host => domain}).run abort "Failed to fetch Fastly service ID or service ID does not exist" if response.response_code != 204 abort "Fastly response did not contain service ID" unless response.headers["Fastly-Service-Id"] return response.headers["Fastly-Service-Id"] end |
.get_active_version(id) ⇒ Object
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
# File 'lib/fastlyctl/fetcher.rb', line 124 def self.get_active_version(id) service = self.api_request(:get, "/service/#{id}") max = 1 service["versions"].each do |v| if v["active"] == true return v["number"] end max = v["number"] if v["number"] > max end return max end |
.get_snippets(id, version) ⇒ Object
179 180 181 182 183 184 185 186 187 |
# File 'lib/fastlyctl/fetcher.rb', line 179 def self.get_snippets(id,version) snippet = self.api_request(:get, "/service/#{id}/version/#{version}/snippet") if snippet.length == 0 return false else return snippet end end |
.get_vcl(id, version, generated = false) ⇒ Object
165 166 167 168 169 170 171 172 173 174 175 176 177 |
# File 'lib/fastlyctl/fetcher.rb', line 165 def self.get_vcl(id, version, generated=false) if generated vcl = self.api_request(:get, "/service/#{id}/version/#{version}/generated_vcl") else vcl = self.api_request(:get, "/service/#{id}/version/#{version}/vcl?include_content=1") end if vcl.length == 0 return false else return vcl end end |
.get_writable_version(id) ⇒ Object
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
# File 'lib/fastlyctl/fetcher.rb', line 140 def self.get_writable_version(id) service = self.api_request(:get, "/service/#{id}") active = false version = false max = 1 service["versions"].each do |v| if v["active"] == true active = v["number"].to_i end if active && v["number"].to_i > active && v["locked"] == false version = v["number"] end max = version if version && version > max end return max unless active version = self.api_request(:put, "/service/#{id}/version/#{active}/clone")["number"] unless version return version end |
.login ⇒ Object
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
# File 'lib/fastlyctl/fetcher.rb', line 215 def self.login thor = Thor::Shell::Basic.new user = thor.ask("Username: ") pass = thor.ask("Password: ", :echo => false) resp = FastlyCTL::Fetcher.api_request(:post, "/login", { :endpoint => :app, params: { user: user, password: pass}}) if resp["needs_two_factor_auth"] two_factor = true thor.say("\nTwo factor auth enabled on account, second factor needed.") code = thor.ask('Please enter verification code:', echo: false) resp = FastlyCTL::Fetcher.api_request(:post, "/two_factor_auth/verify", {force_session: true, :endpoint => :app, params: { token: code }} ) else thor.say("\nTwo factor auth is NOT enabled. You should go do that immediately.") end thor.say("Login successful!") return { user: user, pass: pass, two_factor: two_factor, code: code } end |
.upload_snippet(service, version, content, name) ⇒ Object
189 190 191 192 193 194 |
# File 'lib/fastlyctl/fetcher.rb', line 189 def self.upload_snippet(service,version,content,name) return FastlyCTL::Fetcher.api_request(:put, "/service/#{service}/version/#{version}/snippet/#{FastlyCTL::Utils.percent_encode(name)}", {:endpoint => :api, body: { content: content } }) end |
.upload_vcl(service, version, content, name, is_main = true, is_new = false) ⇒ Object
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
# File 'lib/fastlyctl/fetcher.rb', line 196 def self.upload_vcl(service,version,content,name,is_main=true,is_new=false) params = { name: name, main: "#{is_main ? "1" : "0"}", content: content } # try to create, if that fails, update if is_new response = FastlyCTL::Fetcher.api_request(:post, "/service/#{service}/version/#{version}/vcl", {:endpoint => :api, body: params, expected_responses:[200,409]}) if response["msg"] != "Duplicate record" return end end response = FastlyCTL::Fetcher.api_request(:put, "/service/#{service}/version/#{version}/vcl/#{FastlyCTL::Utils.percent_encode(name)}", {:endpoint => :api, body: params, expected_responses: [200,404]}) # The VCL got deleted so recreate it. if response["msg"] == "Record not found" FastlyCTL::Fetcher.api_request(:post, "/service/#{service}/version/#{version}/vcl", {:endpoint => :api, body: params}) end end |