Module: FastlyCTL::Fetcher

Defined in:
lib/fastlyctl/fetcher.rb

Class Method Summary collapse

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
# File 'lib/fastlyctl/fetcher.rb', line 3

def self.api_request(method, path, options={})
  options[:endpoint] ||= :api
  options[:params] ||= {}
  options[:headers] ||= {}
  options[:body] ||= nil
  options[:disable_token] ||= false
  options[:expected_responses] ||= [200]
  options[:use_vnd] ||= false

  headers = {"Accept" => "application/json", "Connection" => "close", "User-Agent" => "FastlyCTL: https://github.com/fastly/fastlyctl"}

  if options[:endpoint] == :app
    headers["Referer"] = FastlyCTL::FASTLY_APP
    headers["Fastly-API-Request"] = "true"
  end

  if FastlyCTL::Token && !options[:disable_token]
    headers["Fastly-Key"] = FastlyCTL::Token
  end

  headers["Content-Type"] = "application/x-www-form-urlencoded" if (method == :post || method == :put)

  if options[:use_vnd]
    headers["Accept"] = "application/vnd.api+json"

    if (method == :post || method == :put)
      headers["Content-Type"] = "application/vnd.api+json"
    end
    options[:expected_responses].push(*[201,202,203,204])
  end

  headers.merge!(options[:headers]) if options[: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_RT_API}#{path}"

  response = Typhoeus::Request.new(
    url,
    method: method,
    params: options[:params],
    headers: headers,
    body: options[:body]
  ).run

  if !options[:expected_responses].include?(response.response_code)
    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 (options[: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



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
# File 'lib/fastlyctl/fetcher.rb', line 201

def self.create_token(options)
  thor = Thor::Shell::Basic.new

  headers = {}
  resp = FastlyCTL::Fetcher.api_request(:post, "/tokens", {
    disable_token: true,
    endpoint: :api,
    body: options,
    headers: headers,
    expected_responses: [200,400]
  })

  if resp.has_key?("msg") && resp["msg"] == "2fa.verify"
    thor.say("\nTwo factor auth enabled on account, second factor needed.")
    code = thor.ask('Please enter verification code:', echo: false)

    headers = {}
    headers["Fastly-OTP"] = code
    resp = FastlyCTL::Fetcher.api_request(:post, "/tokens", {
      disable_token: true,
      endpoint: :api,
      body: options,
      headers: headers
    })
  elsif resp.has_key?("msg")
    abort "ERROR: #{resp}"
  end

  thor.say("\n#{resp["id"]} created.")

  return resp
end

.domain_to_service_id(domain) ⇒ Object



100
101
102
103
104
105
106
107
108
# File 'lib/fastlyctl/fetcher.rb', line 100

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



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/fastlyctl/fetcher.rb', line 110

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



165
166
167
168
169
170
171
172
173
# File 'lib/fastlyctl/fetcher.rb', line 165

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



151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/fastlyctl/fetcher.rb', line 151

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



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/fastlyctl/fetcher.rb', line 126

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

.upload_snippet(service, version, content, name) ⇒ Object



175
176
177
178
179
180
# File 'lib/fastlyctl/fetcher.rb', line 175

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



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/fastlyctl/fetcher.rb', line 182

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