Module: VMC::Cli::TunnelHelper

Included in:
Command::Apps, Command::Services
Defined in:
lib/cli/tunnel_helper.rb

Constant Summary collapse

PORT_RANGE =
10
HELPER_APP =
File.expand_path("../../../caldecott_helper", __FILE__)
HELPER_VERSION =

bump this AND the version info reported by HELPER_APP/server.rb this is to keep the helper in sync with any updates here

'0.0.4'

Instance Method Summary collapse

Instance Method Details

#display_tunnel_connection_info(info) ⇒ Object



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
# File 'lib/cli/tunnel_helper.rb', line 150

def display_tunnel_connection_info(info)
  display ''
  display "Service connection info: "

  to_show = [nil, nil, nil] # reserved for user, pass, db name
  info.keys.each do |k|
    case k
    when "host", "hostname", "port", "node_id"
      # skip
    when "user", "username"
      # prefer "username" over "user"
      to_show[0] = k unless to_show[0] == "username"
    when "password"
      to_show[1] = k
    when "name"
      to_show[2] = k
    else
      to_show << k
    end
  end
  to_show.compact!

  align_len = to_show.collect(&:size).max + 1

  to_show.each do |k|
    # TODO: modify the server services rest call to have explicit knowledge
    # about the items to return.  It should return all of them if
    # the service is unknown so that we don't have to do this weird
    # filtering.
    display "  #{k.ljust align_len}: ", false
    display "#{info[k]}".yellow
  end
  display ''
end

#grab_ephemeral_portObject



219
220
221
222
223
224
225
226
# File 'lib/cli/tunnel_helper.rb', line 219

def grab_ephemeral_port
  socket = TCPServer.new('0.0.0.0', 0)
  socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)
  Socket.do_not_reverse_lookup = true
  port = socket.addr[1]
  socket.close
  return port
end

#invalidate_tunnel_app_info(infra) ⇒ Object



65
66
# File 'lib/cli/tunnel_helper.rb', line 65

def invalidate_tunnel_app_info(infra)
end

#pick_tunnel_port(port) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/cli/tunnel_helper.rb', line 204

def pick_tunnel_port(port)
  original = port

  PORT_RANGE.times do |n|
    begin
      TCPSocket.open('localhost', port)
      port += 1
    rescue
      return port
    end
  end

  grab_ephemeral_port
end

#push_caldecott(token, infra) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/cli/tunnel_helper.rb', line 294

def push_caldecott(token,infra)
  manifest = {
      :name => tunnel_appname(infra),
      :staging => {:framework => "sinatra", :runtime => "ruby18" },
      :uris => ["#{tunnel_uniquename(infra)}.#{client.base_for_infra(infra)}"],
      :instances => 1,
      :resources => {:memory => 64},
      :env => ["CALDECOTT_AUTH=#{token}"]
    }
  manifest[:infra] = { :provider => infra } if infra 

  client.create_app(
    tunnel_appname(infra),
    manifest
  )

  apps_cmd.send(:upload_app_bits, tunnel_appname(infra), HELPER_APP, infra)

  invalidate_tunnel_app_info(infra)
end

#resolve_symbols(str, info, local_port) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/cli/tunnel_helper.rb', line 251

def resolve_symbols(str, info, local_port)
  str.gsub(/\$\{\s*([^\}]+)\s*\}/) do
    case $1
    when "host"
      # TODO: determine proper host
      "localhost"
    when "port"
      local_port
    when "user", "username"
      info["username"]
    else
      info[$1] || ask($1)
    end
  end
end

#start_caldecott(infra) ⇒ Object



321
322
323
324
325
# File 'lib/cli/tunnel_helper.rb', line 321

def start_caldecott(infra)
  apps_cmd.start(tunnel_appname(infra))

  invalidate_tunnel_app_info(infra)
end

#start_local_prog(clients, command, info, port) ⇒ Object



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/cli/tunnel_helper.rb', line 267

def start_local_prog(clients, command, info, port)
  client = clients[File.basename(command)]

  cmdline = "#{command} "

  case client
  when Hash
    cmdline << resolve_symbols(client["command"], info, port)
    client["environment"].each do |e|
      if e =~ /([^=]+)=(["']?)([^"']*)\2/
        ENV[$1] = resolve_symbols($3, info, port)
      else
        err "Invalid environment variable: #{e}"
      end
    end
  when String
    cmdline << resolve_symbols(client, info, port)
  else
    err "Unknown client info: #{client.inspect}."
  end

  display "Launching '#{cmdline}'"
  display ''

  system(cmdline)
end

#start_tunnel(local_port, conn_info, auth, infra) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/cli/tunnel_helper.rb', line 185

def start_tunnel(local_port, conn_info, auth, infra)
  @local_tunnel_thread = Thread.new do
    Caldecott::Client.start({
      :local_port => local_port,
      :tun_url => tunnel_url(infra),
      :dst_host => conn_info['hostname'],
      :dst_port => conn_info['port'],
      :log_file => STDOUT,
      :log_level => ENV["VMC_TUNNEL_DEBUG"] || "ERROR",
      :auth_token => auth,
      :quiet => true
    })
  end

  at_exit { @local_tunnel_thread.kill }
end

#stop_caldecott(infra) ⇒ Object



315
316
317
318
319
# File 'lib/cli/tunnel_helper.rb', line 315

def stop_caldecott(infra)
  apps_cmd.stop(tunnel_appname(infra))

  invalidate_tunnel_app_info(infra)
end

#tunnel_app_info(infra) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/cli/tunnel_helper.rb', line 28

def tunnel_app_info(infra)
  begin
    client.app_info(tunnel_appname(infra))
  rescue => e
    nil
  end
end

#tunnel_appname(infra) ⇒ Object



24
25
26
# File 'lib/cli/tunnel_helper.rb', line 24

def tunnel_appname(infra)
  infra ? "caldecott-#{infra}" : "caldecott"
end

#tunnel_auth(infra) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/cli/tunnel_helper.rb', line 36

def tunnel_auth(infra)
  tunnel_app_info(infra)[:env].each do |e|
    name, val = e.split("=", 2)
    return val if name == "CALDECOTT_AUTH"
  end
  nil
end

#tunnel_bound?(service, infra) ⇒ Boolean

Returns:

  • (Boolean)


93
94
95
# File 'lib/cli/tunnel_helper.rb', line 93

def tunnel_bound?(service,infra)
  tunnel_app_info(infra)[:services].include?(service)
end

#tunnel_connection_info(type, service, token, infra) ⇒ Object



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
# File 'lib/cli/tunnel_helper.rb', line 97

def tunnel_connection_info(type, service, token, infra)
  display "Getting tunnel connection info: ", false
  response = nil
  10.times do
    begin
      response = RestClient.get(tunnel_url(infra) + "/" + VMC::Client.path("services", service), "Auth-Token" => token)
      break
    rescue RestClient::Exception => e
      puts "Error infra: #{infra}, url: #{tunnel_url(infra)}"
      display tunnel_url(infra)
      puts e.message.red
      sleep 1
    end

    display ".", false
  end

  unless response
    err "Expected remote tunnel to know about #{service}, but it doesn't"
  end

  display "OK".green

  info = JSON.parse(response)
  info["infra"] = infra
  case type
  when "rabbitmq"
    uri = Addressable::URI.parse info["url"]
    info["hostname"] = uri.host
    info["port"] = uri.port
    info["vhost"] = uri.path[1..-1]
    info["user"] = uri.user
    info["password"] = uri.password
    info.delete "url"

  # we use "db" as the "name" for mongo
  # existing "name" is junk
  when "mongodb"
    info["name"] = info["db"]
    info.delete "db"

  # our "name" is irrelevant for redis
  when "redis"
    info.delete "name"
  end

  ['hostname', 'port', 'password'].each do |k|
    err "Could not determine #{k} for #{service}" if info[k].nil?
  end

  info
end

#tunnel_healthy?(token, infra) ⇒ Boolean

Returns:

  • (Boolean)


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/cli/tunnel_helper.rb', line 72

def tunnel_healthy?(token,infra)
  return false unless tunnel_app_info(infra)[:state] == 'STARTED'

  begin
    response = RestClient.get(
      "#{tunnel_url(infra)}/info",
      "Auth-Token" => token
    )
    info = JSON.parse(response)
    if info["version"] == HELPER_VERSION
      true
    else
      stop_caldecott(infra)
      false
    end
  rescue RestClient::Exception
    stop_caldecott(infra)
    false
  end
end

#tunnel_pushed?(infra) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/cli/tunnel_helper.rb', line 68

def tunnel_pushed?(infra)
  not tunnel_app_info(infra).nil?
end

#tunnel_uniquename(infra) ⇒ Object



20
21
22
# File 'lib/cli/tunnel_helper.rb', line 20

def tunnel_uniquename(infra)
  random_service_name(tunnel_appname(infra))
end

#tunnel_url(infra) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/cli/tunnel_helper.rb', line 44

def tunnel_url(infra)

  tun_url = tunnel_app_info(infra)[:uris][0]

  ["https", "http"].each do |scheme|
    url = "#{scheme}://#{tun_url}"
    begin
      RestClient.get(url)

    # https failed
    rescue Errno::ECONNREFUSED

    # we expect a 404 since this request isn't auth'd
    rescue RestClient::ResourceNotFound
      return url
    end
  end

  err "Cannot determine URL for #{tun_url}"
end

#wait_for_tunnel_endObject



244
245
246
247
248
249
# File 'lib/cli/tunnel_helper.rb', line 244

def wait_for_tunnel_end
  display "Open another shell to run command-line clients or"
  display "use a UI tool to connect using the displayed information."
  display "Press Ctrl-C to exit..."
  @local_tunnel_thread.join
end

#wait_for_tunnel_start(port) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/cli/tunnel_helper.rb', line 228

def wait_for_tunnel_start(port)
  10.times do |n|
    begin
      client = TCPSocket.open('localhost', port)
      display '' if n > 0
      client.close
      return true
    rescue => e
      display "Waiting for local tunnel to become available", false if n == 0
      display '.', false
      sleep 1
    end
  end
  err "Could not connect to local tunnel."
end