Class: OsCtld::Commands::Container::Attach

Inherits:
Base
  • Object
show all
Includes:
OsCtl::Lib::Utils::Log, Utils::SwitchUser
Defined in:
lib/osctld/commands/container/attach.rb

Defined Under Namespace

Classes: Shell

Instance Attribute Summary

Attributes inherited from Base

#client, #client_handler, #id, #opts

Instance Method Summary collapse

Methods included from Utils::SwitchUser

#ct_attach, #ct_syscmd

Methods inherited from Base

#base_execute, #call_cmd, #call_cmd!, #error, #error!, handle, #handled, #indirect?, #initialize, #manipulate, #manipulation_holder, #ok, #progress, #request_stop, run, run!

Constructor Details

This class inherits a constructor from OsCtld::Commands::Base

Instance Method Details

#executeObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/osctld/commands/container/attach.rb', line 12

def execute
  ct = DB::Containers.find(opts[:id], opts[:pool])
  error!('container not found') unless ct
  error!('container not running') if ct.state != :running

  base_args = [
    'lxc-attach', '-P', ct.lxc_home,
    '-n', ct.id,
    '--clear-env',
    '--keep-var', 'TERM',
    '-v', 'USER=root',
    '-v', 'LOGNAME=root',
    '-v', 'HOME=/root',
    '-v', "PATH=#{SwitchUser::SYSTEM_PATH.join(':')}",
    '-v', 'HISTFILE=/root/.osctl_ct_attach_history'
  ]

  if opts[:user_shell]
    ok(ct_attach(ct, *base_args))

  else
    shell = find_shell(ct)
    error!('no supported shell located') unless shell

    ok(ct_attach(
         ct,
         *base_args,
         '--keep-var', 'LANG',
         '-v', "PS1=#{prompt(ct, shell)}",
         '--',
         *shell_args(shell)
       ))
  end
end

#find_shell(ct) ⇒ Object (protected)



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/osctld/commands/container/attach.rb', line 49

def find_shell(ct)
  rootfs = File.join('/proc', ct.init_pid.to_s, 'root')

  %i[bash busybox sh].each do |type|
    path = DistConfig.run(ct.get_run_conf, :bin_path)

    begin
      File.lstat(File.join(rootfs, path, type.to_s))
    rescue Errno::ENOENT
      next
    end

    return Shell.new(type, File.join(path, type.to_s))
  end

  nil
end

#prompt(ct, shell) ⇒ Object (protected)



80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/osctld/commands/container/attach.rb', line 80

def prompt(ct, shell)
  case shell.type
  when :bash
    "\\n\\[\\033[1;31m\\][CT #{ct.id}]\\[\\033[0m\\] " \
    '\\[\\033[1;95m\\]\\u@\\h:\\w\\$\\[\\033[0m\\] '

  when :busybox
    "\\n[CT #{ct.id}] \\u@\\h:\\w\\$ "

  when :sh
    "\\n[CT #{ct.id}] $USER@$HOSTNAME:$PWD\\$ "
  end
end

#shell_args(shell) ⇒ Object (protected)



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/osctld/commands/container/attach.rb', line 67

def shell_args(shell)
  case shell.type
  when :bash
    [shell.executable, '--norc']

  when :busybox
    [shell.executable, 'sh']

  when :sh
    [shell.executable]
  end
end