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



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

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

#invalidate_tunnel_app_infoObject



59
60
61
62
# File 'lib/cli/tunnel_helper.rb', line 59

def invalidate_tunnel_app_info
  @tunnel_url = nil
  @tunnel_app_info = nil
end

#pick_tunnel_port(port) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/cli/tunnel_helper.rb', line 197

def pick_tunnel_port(port)
  original = port

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

  err "Could not pick a port between #{original} and #{original + PORT_RANGE - 1}"
end

#push_caldecott(token) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/cli/tunnel_helper.rb', line 270

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({}).send(:upload_app_bits, tunnel_appname, HELPER_APP)

  invalidate_tunnel_app_info
end

#resolve_symbols(str, info, local_port) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/cli/tunnel_helper.rb', line 234

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



293
294
295
296
297
# File 'lib/cli/tunnel_helper.rb', line 293

def start_caldecott
  Command::Apps.new({}).start(tunnel_appname)

  invalidate_tunnel_app_info
end

#start_local_prog(client, info, port) ⇒ Object



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

def start_local_prog(client, info, port)
  case client
  when Hash
    cmdline = resolve_symbols(client["command"], info, port)
    client["environment"].each do |e|
      e =~ /([^=]+)=(["']?)([^"']*)\2/
      ENV[$1] = resolve_symbols($3, info, port)
    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



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/cli/tunnel_helper.rb', line 178

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 => "ERROR",
      :auth_token => auth,
      :quiet => true
    })
  end

  at_exit { @local_tunnel_thread.kill }
end

#stop_caldecottObject



287
288
289
290
291
# File 'lib/cli/tunnel_helper.rb', line 287

def stop_caldecott
  Command::Apps.new({}).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_bound?(service) ⇒ Boolean

Returns:

  • (Boolean)


90
91
92
# File 'lib/cli/tunnel_helper.rb', line 90

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

#tunnel_connection_info(type, service, token) ⇒ Object



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

def tunnel_connection_info(type, service, token)
  display "Getting tunnel connection info: ", false
  response = nil
  10.times do
    begin
      response = RestClient.get("#{tunnel_url}/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)


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

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)


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

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



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cli/tunnel_helper.rb', line 37

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



227
228
229
230
231
232
# File 'lib/cli/tunnel_helper.rb', line 227

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



212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/cli/tunnel_helper.rb', line 212

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