Module: VMC::Cli::TunnelHelper

Included in:
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



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

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



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

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_infoObject



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

def invalidate_tunnel_app_info
  @tunnel_url = nil
  @tunnel_app_info = nil
end

#pick_tunnel_port(port) ⇒ Object



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

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) ⇒ Object



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

def push_caldecott(token)
  client.create_app(
    tunnel_appname,
    { :name => tunnel_appname,
      :staging => {:framework => "sinatra"},
      :uris => ["#{tunnel_uniquename}.#{VMC::Cli::Config.suggest_url}"],
      :instances => 1,
      :resources => {:memory => 64},
      :env => ["CALDECOTT_AUTH=#{token}"]
    }
  )

  Command::Apps.new(@options).send(:upload_app_bits, tunnel_appname, HELPER_APP)

  invalidate_tunnel_app_info
end

#resolve_symbols(str, info, local_port) ⇒ Object



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

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_caldecottObject



318
319
320
321
322
# File 'lib/cli/tunnel_helper.rb', line 318

def start_caldecott
  Command::Apps.new(@options).start(tunnel_appname)

  invalidate_tunnel_app_info
end

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



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

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(service, local_port, conn_info, auth) ⇒ Object



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

def start_tunnel(service, local_port, conn_info, auth)
  display "Starting tunnel to #{service.bold} on port #{local_port.to_s.bold}."

  @local_tunnel_thread = Thread.new do
    Caldecott::Client.start({
      :local_port => local_port,
      :tun_url => tunnel_url,
      :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_caldecottObject



312
313
314
315
316
# File 'lib/cli/tunnel_helper.rb', line 312

def stop_caldecott
  Command::Apps.new(@options).stop(tunnel_appname)

  invalidate_tunnel_app_info
end

#tunnel_app_infoObject



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

def tunnel_app_info
  return @tun_app_info if @tunnel_app_info
  begin
    @tun_app_info = client.app_info(tunnel_appname)
  rescue => e
    @tun_app_info = nil
  end
end

#tunnel_appnameObject



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

def tunnel_appname
  "caldecott"
end

#tunnel_authObject



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

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

  nil
end

#tunnel_bound?(service) ⇒ Boolean

Returns:

  • (Boolean)


99
100
101
# File 'lib/cli/tunnel_helper.rb', line 99

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

#tunnel_connection_info(type, service, token) ⇒ Object



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

def tunnel_connection_info(type, service, token)
  display "Getting tunnel connection info: ", false
  response = nil
  10.times do
    begin
      response = RestClient.get(tunnel_url + "/" + VMC::Client.path("services", service), "Auth-Token" => token)
      break
    rescue RestClient::Exception
      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)
  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) ⇒ Boolean

Returns:

  • (Boolean)


77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/cli/tunnel_helper.rb', line 77

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

  begin
    response = RestClient.get(
      "#{tunnel_url}/info",
      "Auth-Token" => token
    )

    info = JSON.parse(response)
    if info["version"] == HELPER_VERSION
      true
    else
      stop_caldecott
      false
    end
  rescue RestClient::Exception
    stop_caldecott
    false
  end
end

#tunnel_pushed?Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/cli/tunnel_helper.rb', line 73

def tunnel_pushed?
  not tunnel_app_info.nil?
end

#tunnel_uniquenameObject



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

def tunnel_uniquename
  random_service_name(tunnel_appname)
end

#tunnel_urlObject



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

def tunnel_url
  return @tunnel_url if @tunnel_url

  tun_url = tunnel_app_info[: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 @tunnel_url = url
    end
  end

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

#wait_for_tunnel_endObject



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

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



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

def wait_for_tunnel_start(port)
  10.times do |n|
    begin
      TCPSocket.open('localhost', port)
      display '' if n > 0
      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