Class: OsCtld::SwitchUser::ContainerControl

Inherits:
Object
  • Object
show all
Includes:
OsCtl::Lib::Utils::Log
Defined in:
lib/osctld/switch_user/container_control.rb

Constant Summary collapse

PATH =
%w(/bin /usr/bin /sbin /usr/sbin /run/current-system/sw/bin)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ ContainerControl

Returns a new instance of ContainerControl



22
23
24
25
26
# File 'lib/osctld/switch_user/container_control.rb', line 22

def initialize(opts)
  @lxc_home = opts[:lxc_home]
  @user_home = opts[:user_home]
  @log_file = opts[:log_file]
end

Class Method Details

.run(cmd, cmd_opts, ct_opts) ⇒ Object

Parameters:

  • cmd (Symbol)

    command to call

  • cmd_opts (Hash)

    command options

  • ct_opts (Hash)

    container options

Options Hash (ct_opts):

  • :lxc_home (String)
  • :user_home (String)
  • :log_file (String)


17
18
19
20
# File 'lib/osctld/switch_user/container_control.rb', line 17

def self.run(cmd, cmd_opts, ct_opts)
  ur = new(ct_opts)
  ur.execute(cmd, cmd_opts)
end

Instance Method Details

#ct_exec_network(opts) ⇒ Object (protected)

Execute command in a stopped container with the network configured

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :init_script (String)

    path to the script used to control the container

  • :net_config (NetConfig)
  • :cmd (String)

    command to execute

  • :stdin (IO)
  • :stdout (IO)
  • :stderr (IO)


164
165
166
167
168
169
170
# File 'lib/osctld/switch_user/container_control.rb', line 164

def ct_exec_network(opts)
  with_configured_network(
    id: opts[:id],
    init_script: opts[:init_script],
    net_config: opts[:net_config],
  ) { ct_exec_running(opts) }
end

#ct_exec_run(opts) ⇒ Object (protected)

Execute command in a stopped container

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :cmd (String)

    command to execute

  • :stdin (IO)
  • :stdout (IO)
  • :stderr (IO)


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
151
152
# File 'lib/osctld/switch_user/container_control.rb', line 126

def ct_exec_run(opts)
  pid = Process.fork do
    STDIN.reopen(opts[:stdin])
    STDOUT.reopen(opts[:stdout])
    STDERR.reopen(opts[:stderr])

    setup_exec_env

    cmd = [
      'lxc-execute',
      '-P', @lxc_home,
      '-n', opts[:id],
      '-o', @log_file,
      '-s', "lxc.environment=PATH=#{PATH.join(':')}",
      '--',
      opts[:cmd],
    ]

    # opts[:cmd] can contain an arbitrary command with multiple arguments
    # and quotes, so the mapping to process arguments is not clear. We use
    # the shell to handle this.
    Process.exec("exec #{cmd.join(' ')}")
  end

  _, status = Process.wait2(pid)
  ok(exitstatus: status.exitstatus)
end

#ct_exec_running(opts) ⇒ Object (protected)

Execute command in a running container

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :cmd (String)

    command to execute

  • :stdin (IO)
  • :stdout (IO)
  • :stderr (IO)


105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/osctld/switch_user/container_control.rb', line 105

def ct_exec_running(opts)
  pid = lxc_ct(opts[:id]).attach(
    stdin: opts[:stdin],
    stdout: opts[:stdout],
    stderr: opts[:stderr]
  ) do
    setup_exec_env
    LXC.run_command(opts[:cmd])
  end

  _, status = Process.wait2(pid)
  ok(exitstatus: status.exitstatus)
end

#ct_kill(opts, ct = nil) ⇒ Object (protected)

Kill container immediately

Parameters:

Options Hash (opts):

  • :id (String)

    container id



52
53
54
55
56
57
58
59
# File 'lib/osctld/switch_user/container_control.rb', line 52

def ct_kill(opts, ct = nil)
  ct ||= lxc_ct(opts[:id])
  ct.stop
  ok

rescue LXC::Error
  error('unable to kill container')
end

#ct_reboot(opts) ⇒ Object (protected)

Request container reboot

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id



78
79
80
81
# File 'lib/osctld/switch_user/container_control.rb', line 78

def ct_reboot(opts)
  ct = lxc_ct(opts[:id])
  ct.reboot
end

#ct_runscript_network(opts) ⇒ Object (protected)

Execute script in a stopped container

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :init_script (String)

    path to the script used to control the container

  • :net_config (NetConfig)
  • :script (String)

    path to the script relative to the rootfs

  • :stdin (IO)
  • :stdout (IO)
  • :stderr (IO)


246
247
248
249
250
251
252
# File 'lib/osctld/switch_user/container_control.rb', line 246

def ct_runscript_network(opts)
  with_configured_network(
    id: opts[:id],
    init_script: opts[:init_script],
    net_config: opts[:net_config],
  ) { ct_runscript_running(opts) }
end

#ct_runscript_run(opts) ⇒ Object (protected)

Execute command in a stopped container

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :script (String)

    path to the script relative to the rootfs

  • :stdin (IO)
  • :stdout (IO)
  • :stderr (IO)
  • :close_fds (Array<IO>)
  • :wait (Boolean)


202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/osctld/switch_user/container_control.rb', line 202

def ct_runscript_run(opts)
  pid = Process.fork do
    STDIN.reopen(opts[:stdin])
    STDOUT.reopen(opts[:stdout])
    STDERR.reopen(opts[:stderr])

    opts[:close_fds] && opts[:close_fds].each { |fd| fd.close }

    setup_exec_env

    cmd = [
      'lxc-execute',
      '-P', @lxc_home,
      '-n', opts[:id],
      '-o', @log_file,
      '-s', "lxc.environment=PATH=#{PATH.join(':')}",
      '--',
      opts[:script],
    ]

    # opts[:cmd] can contain an arbitrary command with multiple arguments
    # and quotes, so the mapping to process arguments is not clear. We use
    # the shell to handle this.
    Process.exec("exec #{cmd.join(' ')}")
  end

  if opts[:wait] === false
    pid
  else
    _, status = Process.wait2(pid)
    ok(exitstatus: status.exitstatus)
  end
end

#ct_runscript_running(opts) ⇒ Object (protected)

Execute script in a running container

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :script (String)

    path to the script relative to the rootfs

  • :stdin (IO)
  • :stdout (IO)
  • :stderr (IO)


179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/osctld/switch_user/container_control.rb', line 179

def ct_runscript_running(opts)
  pid = lxc_ct(opts[:id]).attach(
    stdin: opts[:stdin],
    stdout: opts[:stdout],
    stderr: opts[:stderr]
  ) do
    setup_exec_env
    LXC.run_command(opts[:script])
  end

  _, status = Process.wait2(pid)
  ok(exitstatus: status.exitstatus)
end

#ct_shutdown(opts, ct = nil) ⇒ Object (protected)

Shutdown container cleanly or fail

Parameters:

Options Hash (opts):

  • :id (String)

    container id

  • :timeout (Integer)

    how long to wait for clean shutdown



66
67
68
69
70
71
72
73
# File 'lib/osctld/switch_user/container_control.rb', line 66

def ct_shutdown(opts, ct = nil)
  ct ||= lxc_ct(opts[:id])
  ct.shutdown(opts[:timeout])
  ok

rescue LXC::Error
  error('unable to shutdown container')
end

#ct_status(opts) ⇒ Object (protected)



83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/osctld/switch_user/container_control.rb', line 83

def ct_status(opts)
  ret = {}

  opts[:ids].each do |id|
    ct = lxc_ct(id)

    ret[id] = {
      state: ct.state,
      init_pid: ct.init_pid,
    }
  end

  ok(ret)
end

#ct_stop(opts) ⇒ Object (protected)

Attempt a clean shutdown, fallback to kill

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :timeout (Integer)

    how long to wait for clean shutdown



37
38
39
40
41
42
43
44
45
46
# File 'lib/osctld/switch_user/container_control.rb', line 37

def ct_stop(opts)
  ct = lxc_ct(opts[:id])

  if ct_shutdown(opts, ct)[:status]
    ok

  else
    ct_kill(opts, ct)
  end
end

#error(msg) ⇒ Object (protected)



416
417
418
# File 'lib/osctld/switch_user/container_control.rb', line 416

def error(msg)
  {status: false, message: msg}
end

#execute(cmd, opts) ⇒ Object



28
29
30
# File 'lib/osctld/switch_user/container_control.rb', line 28

def execute(cmd, opts)
  method(cmd).call(opts)
end

#lxc_ct(id) ⇒ Object (protected)



346
347
348
# File 'lib/osctld/switch_user/container_control.rb', line 346

def lxc_ct(id)
  LXC::Container.new(id, @lxc_home)
end

#mount(opts) ⇒ Object (protected)

Relocate mount from the host-shared directory into the correct place

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :shared_dir (String)

    path to the host-shared directory

  • :src (String)

    directory inside `:shared_dir` to relocate

  • :dst (String)

    target mountpoint



265
266
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
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/osctld/switch_user/container_control.rb', line 265

def mount(opts)
  ct = lxc_ct(opts[:id])

  r, w = IO.pipe

  pid = ct.attach(stdout: w) do
    r.close

    begin
      src = File.join(opts[:shared_dir], opts[:src])

      if !Dir.exist?(opts[:shared_dir])
        puts "error:Shared dir not found at: #{opts[:shared_dir]}"

      elsif !Dir.exist?(src)
        puts "error:Source directory not found at: #{src}"

      else
        FileUtils.mkpath(opts[:dst])
        Mount::Sys.move_mount(src, opts[:dst])
        puts 'ok:done'
      end

    rescue => e
      puts "error:Exception (#{e.class}): #{e.message}"

    ensure
      STDOUT.flush
    end
  end

  w.close

  line = r.readline
  Process.wait(pid)
  r.close
  log(:warn, ct, "Mounter exited with #{$?.exitstatus}") if $?.exitstatus != 0

  i = line.index(':')
  return error("invalid return value: #{line.inspect}") unless i

  status = line[0..i-1]
  msg = line[i+1..-1]

  if status == 'ok'
    ok

  else
    error(msg)
  end
end

#ok(out = nil) ⇒ Object (protected)



412
413
414
# File 'lib/osctld/switch_user/container_control.rb', line 412

def ok(out = nil)
  {status: true, output: out}
end

#setup_exec_envObject (protected)



350
351
352
353
354
# File 'lib/osctld/switch_user/container_control.rb', line 350

def setup_exec_env
  ENV.delete_if { |k, _| k != 'TERM' }
  ENV['PATH'] = PATH.join(':')
  ENV['HOME'] = @user_home
end

#unmount(opts) ⇒ Object (protected)

Unmount directory from a container

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :mountpoint (String)


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/osctld/switch_user/container_control.rb', line 321

def unmount(opts)
  ct = lxc_ct(opts[:id])

  pid = ct.attach do
    next unless Dir.exist?(opts[:mountpoint])

    begin
      Mount::Sys.unmount(opts[:mountpoint])

    rescue Errno::EINVAL
      # Not mounted, pass
    end
  end

  Process.wait(pid)

  if $?.exitstatus == 0
    ok

  else
    log(:warn, ct, "Unmounter exited with #{$?.exitstatus}")
    error('unmount failed')
  end
end

#veth_name(opts) ⇒ Object (protected)



254
255
256
257
# File 'lib/osctld/switch_user/container_control.rb', line 254

def veth_name(opts)
  ct = lxc_ct(opts[:id])
  ok(ct.running_config_item("lxc.net.#{opts[:index]}.veth.pair"))
end

#with_configured_network(opts) ⇒ Object (protected)

Start container with lxc-init, configure network and yield

opts has to contain path to a script that will be executed by lxc-init. The purpose of this script is to keep the container running while the network is being configured and the user command is executed. The script has to write `readyn` to standard output, then block on read from standard input and exit.

Parameters:

  • opts (Hash)

Options Hash (opts):

  • :id (String)

    container id

  • :init_script (String)

    path to the script used to control the container

  • :net_config (NetConfig)


369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/osctld/switch_user/container_control.rb', line 369

def with_configured_network(opts)
  ret = nil

  # Pipes for communicating with opts[:init_script]
  in_r, in_w = IO.pipe
  out_r, out_w = IO.pipe

  # Start the container with lxc-init
  init_pid = ct_runscript_run(
    id: opts[:id],
    script: opts[:init_script],
    stdin: in_r,
    stdout: out_w,
    stderr: out_w,
    close_fds: [in_w, out_r],
    wait: false,
  )

  in_r.close
  out_w.close

  # Wait for the container to be started
  if out_r.readline.strip == 'ready'
    # Configure network
    pid = lxc_ct(opts[:id]).attach do
      setup_exec_env
      opts[:net_config].setup
    end

    Process.wait2(pid)

    # Execute user command
    ret = yield
  end

  # Closing in_w will bring down opts[:init_script] and stop the container
  in_w.close
  out_r.close

  _, status = Process.wait2(init_pid)
  ret || ok(exitstatus: status.exitstatus)
end