Class: API

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/peas/api.rb

Constant Summary collapse

LONG_POLL_TIMEOUT =
10 * 60
LONG_POLL_INTERVAL =
0.5

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAPI

This allows base_uri to be dynamically set. Useful for testing



14
15
16
# File 'lib/peas/api.rb', line 14

def initialize
  self.class.base_uri Peas.api_domain
end

Class Method Details

.duplex_socket(socket) ⇒ Object

Create 2 threads to allow raw TTY to be sent at the same time as outputting data from the socket.



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/peas/api.rb', line 140

def self.duplex_socket(socket)
  threads = []

  # Copy STDIN to socket
  threads << Thread.start do
    STDIN.raw do |stdin|
      IO.copy_stream stdin, socket
    end
    socket.close
  end

  # Write response to STDOUT
  threads << Thread.start do
    begin
      while (chunk = socket.readpartial(512))
        print chunk
      end
    rescue EOFError
    end
    threads.first.kill
  end

  threads.each(&:join)
end

.stream_job(job) ⇒ Object

Stream the output of a Switchboard job



109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/peas/api.rb', line 109

def self.stream_job(job)
  API.stream_output "subscribe.job_progress.#{job}" do |line|
    if line.key? 'status'
      if line['status'] == 'failed'
        raise line['body']
      elsif line['status'] == 'complete'
        break
      end
    end
    puts line['body'] if line['body']
  end
end

.stream_output(switchboard_command) ⇒ Object

Stream data from the Switchboard server



123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/peas/api.rb', line 123

def self.stream_output(switchboard_command)
  socket = API.switchboard_connection
  socket.puts switchboard_command
  begin
    while (line = socket.gets)
      if block_given?
        yield JSON.parse line
      else
        puts line
      end
    end
  rescue Interrupt, Errno::ECONNRESET
  end
end

.switchboard_connectionObject



95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/peas/api.rb', line 95

def self.switchboard_connection
  socket = TCPSocket.new Peas.host, Peas::SWITCHBOARD_PORT
  ssl = OpenSSL::SSL::SSLSocket.new socket
  ssl.sync_close = true
  ssl.connect
  ssl.puts API.new.api_key
  unless ssl.gets.strip == 'AUTHORISED'
    ssl.close
    raise 'Unauthoirsed access to Switchboard connection.'
  end
  ssl
end

Instance Method Details

#api_keyObject

Get the API key from local cache, or request a new one



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

def api_key
  # First check local storage
  key = Peas.config['api_key']
  return key if key
  # Other wise request a new one
  key_path = "#{ENV['HOME']}/.ssh/id_rsa"
  unless File.exist? key_path
    exit_now! 'Please add an SSH key'
  end
  username = ENV['USER'] # TODO: Ensure cross platform
  params = {
    username: username,
    public_key: File.read("#{key_path}.pub")
  }
  response = request('POST', '/auth/request', params, false, false)
  doc = response['message']['sign']
  digest = OpenSSL::Digest::SHA256.new
  keypair = OpenSSL::PKey::RSA.new(File.read(key_path))
  signature = keypair.sign(digest, doc)
  encoded = Base64.urlsafe_encode64(signature)
  params = {
    username: username,
    signed: encoded
  }
  response = request('POST', '/auth/verify', params, false, false)
  key = response['message']['api_key']
  Peas.update_config api_key: key
  key
end

#check_versions(json) ⇒ Object

Check CLI client is up to date.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/peas/api.rb', line 79

def check_versions(json)
  # Only check major and minor versions
  version_mismatch = false
  api_version = json['version'].split('.')
  client_version = Peas::VERSION.split('.')
  if api_version[0] != client_version[0]
    version_mismatch = true
  else
    version_mismatch = true if api_version[1] != client_version[1]
  end
  return unless version_mismatch
  Peas.warning_message "Your version of the CLI client is out of date " \
    "(Client: #{Peas::VERSION}, API: #{json['version']}). " \
    "Please update using `gem install peas-cli`."
end

#request(verb, method, query = {}, auth = true, print = true) ⇒ Object

Generic wrapper to the Peas API ‘verb` HTTP verb `method` API method, eg; /app/create `query` Query params `auth` Whether to authenticate against the API. Eg; /auth/request doesn’t need auth ‘print` Whether to output or return the response



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/peas/api.rb', line 24

def request(verb, method, query = {}, auth = true, print = true)
  options = { query: query }
  options[:headers] = { 'x-api-key' => api_key } if auth
  request_args = [
    verb.to_s.downcase,
    "#{method}",
    options
  ]
  response = self.class.send(request_args.shift, *request_args).body
  json = response ? JSON.parse(response) : {}
  # If there was an HTTP-level error
  raise json['error'].color(:red) if json.key? 'error'
  # Successful responses
  if json.key? 'job'
    # Long-running jobs need to stream from the Switchboard server
    API.stream_job json['job']
  else
    check_versions(json)
    puts json['message'] if print
    json
  end
end