Class: Cnvrg::API

Inherits:
Object
  • Object
show all
Defined in:
lib/cnvrg/api.rb

Direct Known Subclasses

API_V2

Constant Summary collapse

USER_AGENT =
"CnvrgCLI/#{Cnvrg::VERSION}"
ENDPOINT_VERSION =
'v1'

Class Method Summary collapse

Class Method Details

.display_error(response) ⇒ Object



250
251
252
# File 'lib/cnvrg/api.rb', line 250

def self.display_error(response)
    "Oops, an error occurred! Reason: #{response['message']}"
end

.endpoint_uriObject



244
245
246
247
# File 'lib/cnvrg/api.rb', line 244

def self.endpoint_uri
    api = get_api()
    return "#{api}/#{Cnvrg::API::ENDPOINT_VERSION}"
end

.get_apiObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/cnvrg/api.rb', line 13

def self.get_api
    home_dir = File.expand_path('~')
    config = ""
    begin
        if File.exist? home_dir+"/.cnvrg/config.yml"
            config = YAML.load_file(home_dir+"/.cnvrg/config.yml")
        else
            return "https://app.cnvrg.io/api"
        end

    rescue
        return "https://app.cnvrg.io/api"
    end
    if !config or config.empty? or config.to_h[:api].nil?
        return "https://app.cnvrg.io/api"
    else
      return config.to_h[:api]
    end
end

.parse_version(resp) ⇒ Object



254
255
256
257
258
259
260
261
# File 'lib/cnvrg/api.rb', line 254

def self.parse_version(resp)
  begin
    version = resp.headers["cnvrg-version"]
    Cnvrg::Helpers.update_version(version)
  rescue => e
    Cnvrg::Logger.log_error(e)
  end
end

.request(resource, method = 'GET', data = {}, parse_request = true) ⇒ Object



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
# File 'lib/cnvrg/api.rb', line 32

def self.request(resource, method = 'GET', data = {}, parse_request = true)
    resource = URI::encode resource

    # We need to remoe all double slashes from the url to work with the proxy
    resource = resource.gsub(/[\/]{2,}/, "/").gsub("https:/", "https://").gsub("http:/", "http://")

    begin
        n = Netrc.read
    rescue => e
    end

    # Make sure there is an entry for the Acquia API before generating the
    # requests.
    if n['cnvrg.io'].nil?
        puts 'You\'re not logged in'
        puts 'Please log in via `cnvrg login`'
        return
    end

    @user, @pass = n[Cnvrg::Helpers.netrc_domain]
    begin
        if !Helpers.is_verify_ssl

            conn = Faraday.new "#{endpoint_uri}", :ssl => {:verify => false}
        else
            conn = Faraday.new "#{endpoint_uri}"
        end
    conn.headers['Auth-Token'] = @pass
    conn.headers['Authorization'] = "CAPI #{@pass}"
    conn.headers['User-Agent'] = "#{Cnvrg::API::USER_AGENT}"
    conn.options.timeout = 420
        conn.options.open_timeout=180
    case method
      when 'GET'
        retries = 0
        success = false
        while !success and retries < 20
          begin
            response = conn.get "#{resource}", data
            success = true
            Cnvrg::API.parse_version(response)
            if response.to_hash[:status].to_i != 200
              Cnvrg::Logger.log_info("Got back bad status #{response.to_hash[:status]}")
            end
            if [503, 502, 429, 401].include?(response.to_hash[:status].to_i)
              Cnvrg::Logger.log_info("Got back status #{response.to_hash[:status]}, will retry in #{5 * retries} seconds")
              success = false
              sleep(5 * retries)
              retries += 1
              next
            end
          rescue => e
            Cnvrg::Logger.log_error(e)
            sleep(5)
            retries +=1
          end
        end
        if !success
          return false
        end
        if response.to_hash[:status] == 404
          return false
        end
        if parse_request
            JSON.parse(response.body)
        else
            response
        end
    when 'POST', 'PUT'
        conn.options.timeout = 4200
        conn.options.open_timeout = 180
        conn.headers['Content-Type'] = "application/json"
        retries = 0
        success = false
        data = data || {}
        while !success and retries < 20
            begin
                response = conn.post "#{resource}", data.to_json if method.eql? 'POST'
                response = conn.put "#{resource}", data.to_json if method.eql? 'PUT'
                success = true
                Cnvrg::API.parse_version(response)
                if response.to_hash[:status].to_i != 200
                  Cnvrg::Logger.log_info("Got back bad status #{response.to_hash[:status]}")
                end
                if [503, 502, 429, 401].include?(response.to_hash[:status].to_i)
                  Cnvrg::Logger.log_info("Got back status #{response.to_hash[:status]}, will retry in #{5 * retries} seconds")
                  success = false
                  sleep(5 * retries)
                  retries += 1
                  next
                end
            rescue => e
              Cnvrg::Logger.log_error(e)
              sleep(5)
              retries +=1
            end
        end
        if !success
            return false
        end
        if response.to_hash[:status] == 404
          return false
        end
        if parse_request == true
            JSON.parse(response.body)
        else
            response
        end
    when 'POST_JSON'
      conn.options.timeout = 4200
      conn.options.open_timeout = 4200
      conn.headers['Content-Type'] = "application/json"
      new_data = JSON.dump(data)

      retries = 0
      success = false

      while !success and retries < 20
        begin
          response = conn.post "#{resource}", new_data
          success = true
        rescue => e
          Cnvrg::Logger.log_error(e)
          sleep(5)
          retries +=1
        end
      end
      if !success
        return false
      end
      if response.to_hash[:status] == 404
        return false
      end
      if parse_request == true
        JSON.parse(response.body)
      else
        response
      end
    when 'POST_FILE'
        conn = Faraday.new do |fr|
            fr.headers['Auth-Token'] = @pass
            fr.headers['Authorization'] = "CAPI #{@pass}"
            fr.headers['User-Agent'] = "#{Cnvrg::API::USER_AGENT}"
            fr.headers["Content-Type"] = "multipart/form-data"
            if !Helpers.is_verify_ssl
               fr.ssl.verify = false
            end


            fr.request :multipart
            fr.request :url_encoded
            fr.request :retry, max: 2, interval: 0.05,interval_randomness: 0.5, backoff_factor: 2
            fr.adapter :net_http
        end
        conn.options.timeout = 4200
        conn.options.open_timeout =4200


        # what if windows?
        # data[:file] = Faraday::UploadIO.new(data[:absolute_path], content_type)
        if not File.exists? data[:relative_path]
          file_base = File.basename(data[:relative_path])

          begin
              temp_path = File.expand_path('~')+"/.cnvrg/tmp_files/#{file_base}"
              FileUtils.touch(temp_path)
          rescue
              temp_path ="/tmp/#{file_base}"
              FileUtils.touch(temp_path)
          end
        else
          temp_path = data[:relative_path]
        end


        data[:file] = Faraday::UploadIO.new("#{temp_path}", "application/tar+gzip")

        response = conn.post "#{endpoint_uri}/#{resource}", data
        Cnvrg::API.parse_version(response)
        FileUtils.rm_rf(temp_path)
        if response.to_hash[:status] == 404
          return false
        end


        if parse_request == true
            JSON.parse(response.body)
        else
            response
        end
    when 'DELETE'
        response = conn.delete "#{endpoint_uri}/#{resource}", data
        Cnvrg::API.parse_version(response)
        if response.to_hash[:status] == 404
          return false
        end
        if parse_request == true
            JSON.parse(response.body)
        else
            response
        end
    else
    end
    rescue => e
      Cnvrg::Logger.log_error(e)
       return nil
    rescue SignalException
        return false
    end

end