Class: HSDeploy::Target::HostingStack::ApiClient

Inherits:
Object
  • Object
show all
Defined in:
lib/hsdeploy/target/hostingstack/api_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server, app_name, auth) ⇒ ApiClient

Returns a new instance of ApiClient.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 26

def initialize(server, app_name, auth)
  @app_name = app_name
  @server = server
  if auth.has_key? :refresh_token
    @refresh_token = auth[:refresh_token]
    @auth_method = :refresh_token
  elsif auth.has_key? :email
    @auth_method = :password
    @email = auth[:email]
    @password = auth[:password]
  else
    @auth_method = :password
  end
end

Instance Attribute Details

#app_nameObject (readonly)

Returns the value of attribute app_name.



25
26
27
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 25

def app_name
  @app_name
end

#auth_methodObject (readonly)

Returns the value of attribute auth_method.



25
26
27
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 25

def auth_method
  @auth_method
end

#emailObject (readonly)

Returns the value of attribute email.



25
26
27
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 25

def email
  @email
end

#passwordObject (readonly)

Returns the value of attribute password.



25
26
27
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 25

def password
  @password
end

#refresh_tokenObject (readonly)

Returns the value of attribute refresh_token.



25
26
27
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 25

def refresh_token
  @refresh_token
end

#serverObject (readonly)

Returns the value of attribute server.



25
26
27
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 25

def server
  @server
end

Instance Method Details

#auth!Object



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
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 46

def auth!
  return if @auth

  @client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET, :site => "http://#{server}/", :token_url => '/oauth2/token', :raise_errors => false) do |builder|
    builder.use Faraday::Request::Multipart
    builder.use Faraday::Request::UrlEncoded
    builder.adapter :net_http
  end

  @auth = false
  tries = 0
  while not @auth
    if tries != 0 && HighLine.new.ask("Would you like to try again? (y/n): ") != 'y'
      return
    end
    token = nil
    handled_error = false
    begin
      if @auth_method == :password
        if !@email.nil? && !@password.nil?
          # Upgrade from previous configuration file
          print "Logging in..."
          begin
            token = @client.password.get_token(@email, @password, :raise_errors => true)
            token = token.refresh!
            @email = nil
            @password = nil
          rescue StandardError => e
            @email = nil
            @password = nil
            tries = 0
            retry
          ensure
            print "\r"
          end
        else
          tries += 1
          $logger.info "Please specify your %s login data" % [HSDeploy::Target::HostingStack.cloud_name]
          email =    HighLine.new.ask("E-mail:   ")
          password = HighLine.new.ask("Password: ") {|q| q.echo = "*" }
          print "Authorizing..."
          begin
            token = @client.password.get_token(email, password, :raise_errors => true)
            token = token.refresh!
          ensure
            print "\r"
          end
          puts "Authorization succeeded."
        end
      else
        params = {:client_id      => @client.id,
                  :client_secret  => @client.secret,
                  :grant_type     => 'refresh_token',
                  :refresh_token  => @refresh_token
                  }
        token = @client.get_token(params)
      end
    rescue OAuth2::Error => e
      handled_error = true
      print "Authorization failed"
      token = nil
      details = MultiJson.decode(e.response.body) rescue nil
      if details
        puts ": #{details['error_description']}"
        re_auth if details['error']
      else
        puts "."
      end
    rescue EOFError
      exit 1
    rescue Interrupt
      exit 1
    rescue StandardError => e
      $logger.debug "ERROR: #{e.inspect}"
      $logger.info "\nAn Error occured. Please try again in a Minute or contact %s support: %s" % [HSDeploy::Target::HostingStack.cloud_name, HSDeploy::Target::HostingStack.support_email]
      puts ""
      tries += 1
    end
    @auth = token
    if not token and not handled_error
      puts "Authorization failed."
    end
  end
  
  @refresh_token = token.refresh_token
  @auth_method = :refresh_token
end

#call(method, method_name, data = {}) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 134

def call(method, method_name, data = {})
  auth!
  method_name = '/' + method_name unless method_name.nil?
  url = Addressable::URI.parse("http://#{@server}/api/cli/v1/apps/#{@app_name}#{method_name}.json")
  opts = method==:get ? {:params => data} : {:body => data}
  opts.merge!({:headers => {'Accept' => 'application/json'}})
  response = @auth.request(method, url.path, opts)
  if not [200,201].include?(response.status)
    raise ApiError.new(response)
  end
  MultiJson.decode(response.body)
end

#cancel_exec(cli_task_id, command_id) ⇒ Object



275
276
277
278
279
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 275

def cancel_exec(cli_task_id, command_id)
  call :delete, "cli_tasks/#{cli_task_id}", {} unless cli_task_id.nil?
  call :delete, "commands/#{command_id}", {} unless command_id.nil?
  nil
end

#deploy(code_token) ⇒ Object



199
200
201
202
203
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 199

def deploy(code_token)
  initial_response = call :post, 'deploy', {:code_token => code_token}
  return nil if not initial_response
  initial_response["token"]
end

#deploy_status(deploy_token, opts) ⇒ Object



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
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 211

def deploy_status(deploy_token, opts)
  start = Time.now
  timing = []
  previous_status = nil
  print "-----> Started deployment '%s'" % deploy_token
  
  while true
    sleep 1
    resp = call :get, 'deploy_status', {:deploy_token => deploy_token}
    
    if resp["message"].nil?
      puts resp
      puts "...possibly done."
      break
    end
    if resp["message"] == 'finished'
      puts "\n-----> FINISHED after %d seconds!" % (Time.now-start)
      break
    end
    
    status = resp["message"].gsub('["', '').gsub('"]', '')
    if previous_status != status
      case status
      when "build"
        puts "\n-----> Building/updating virtual machine..."
      when "deploy"
        print "\n-----> Copying virtual machine to app hosts"
      when "publishing"
        print "\n-----> Updating HTTP gateways"
      when "cleanup"
        print "\n-----> Removing old deployments"
      end
      previous_status = status
    end
    
    logs = resp["logs"]
    if logs
      puts "" if status != "build" # Add newline after the dots
      puts logs
      timing << [Time.now-start, status, logs]
    else
      timing << [Time.now-start, status]
      if status == 'error'
        if logs.nil? or logs.empty?
          raise "ERROR after %d seconds!" % (Time.now-start)
        end
      elsif status != "build"
        print "."
        STDOUT.flush
      end
    end
  end
ensure
  save_timing_data timing if opts[:timing]
end

#exec(command) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 281

def exec(command)
  name = "cli#{Time.now}"
  response = call :post, 'commands', {:command => {:name => name, :command => command}}
  return nil if not response
  command_id = response["command"]["id"]

  response = call :post, 'cli_tasks', {:cli_task => {:name => name, :command_id => command_id}}
  return nil if not response
  cli_task_id = response["cli_task"]["id"]

  response = call :post, "cli_tasks/#{cli_task_id}/dispatch_task", {}
  return nil if not response
  token = response["token"]
  puts "---> Launching..."

  while true do
    response = call :get, "cli_tasks/#{cli_task_id}/drain_status", {:token => token}
    unless response["logs"].nil?
      puts response["logs"]
    end
    if response["message"] == "success"
      puts "---> Done."
      break
    end
    if response["message"] == "failure"
      puts "---> Failed."
      break
    end
    sleep 1
  end

  nil
ensure
  cancel_exec cli_task_id, command_id
end

#human_filesize(path) ⇒ Object



267
268
269
270
271
272
273
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 267

def human_filesize(path)
  size = File.size(path)
  units = %w{B KB MB GB TB}
  e = (Math.log(size)/Math.log(1024)).floor
  s = "%.1f" % (size.to_f / 1024**e)
  s.sub(/\.?0*$/, units[e])
end

#infoObject



151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 151

def info
  response = call :get, nil
  return nil if not response
  data = {}
  response["app"].each do |k,v|
    next unless v.kind_of?(String)
    data[k.to_sym] = v
  end
  data
rescue ApiError => e
  if e.response.status == 404
    raise "ERROR: Application does not exist on server"
  end
end

#re_authObject



41
42
43
44
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 41

def re_auth
  @auth_method = :password
  @auth = nil
end

#save_timing_data(data) ⇒ Object



205
206
207
208
209
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 205

def save_timing_data(data)
  File.open('deploytool-timingdata-%d.json' % (Time.now), 'w') do |f|
    f.puts data.to_json
  end
end

#to_hObject



147
148
149
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 147

def to_h
  {:server => @server, :app_name => @app_name, :email => email, :password => @password, :refresh_token => @refresh_token, :auth_method => @auth_method}
end

#uploadObject



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
# File 'lib/hsdeploy/target/hostingstack/api_client.rb', line 166

def upload
  puts "-----> Packing code tarball..."
  
  ignore_regex = [
    /(^|\/).{1,2}$/,
    /(^|\/).git\//,
    /^.hsdeployrc$/,
    /^log\//,
    /(^|\/).DS_Store$/,
    /(^|\/)[^\/]+\.(bundle|o|so|rl|la|a)$/,
    /^vendor\/gems\/[^\/]+\/ext\/lib\//
  ]
  
  appfiles = Dir.glob('**/*', File::FNM_DOTMATCH)
  appfiles.reject! {|f| File.directory?(f) }
  appfiles.reject! {|f| ignore_regex.map {|r| !f[r] }.include?(false) }
  
  # TODO: Shouldn't upload anything that's in gitignore
  
  # Construct a temporary zipfile
  tempfile = Tempfile.open("ecli-upload.zip")
  Zip::ZipOutputStream.open(tempfile.path) do |z|
    appfiles.each do |appfile|
      z.put_next_entry appfile
      z.print IO.read(appfile)
    end
  end
  
  puts "-----> Uploading %s code tarball..." % human_filesize(tempfile.path)
  initial_response = call :post, 'upload', {:code => Faraday::UploadIO.new(tempfile, "application/zip")}
  initial_response["code_token"]
end