Class: OsCtld::Console::TTY

Inherits:
Object
  • Object
show all
Includes:
OsCtl::Lib::Utils::Log, OsCtl::Lib::Utils::System, Utils::SwitchUser
Defined in:
lib/osctld/console/tty.rb

Overview

Represents a container’s tty.

Each tty has its own thread that passes data between the tty and connected clients. Clients can be connected even if the tty is not available, i.e. the container can be stopped.

Direct Known Subclasses

Console

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils::SwitchUser

#ct_attach, #ct_syscmd

Constructor Details

#initialize(ct, n) ⇒ TTY

Returns a new instance of TTY.



20
21
22
23
24
25
26
27
# File 'lib/osctld/console/tty.rb', line 20

def initialize(ct, n)
  @ct = ct
  @n = n
  @mutex = Mutex.new
  @clients = []
  @wake_r, @wake_w = IO.pipe
  @opened = false
end

Instance Attribute Details

#ctObject (readonly)

Returns the value of attribute ct.



18
19
20
# File 'lib/osctld/console/tty.rb', line 18

def ct
  @ct
end

#nObject (readonly)

Returns the value of attribute n.



18
19
20
# File 'lib/osctld/console/tty.rb', line 18

def n
  @n
end

#tty_in_ioObject (protected)

Returns the value of attribute tty_in_io.



191
192
193
# File 'lib/osctld/console/tty.rb', line 191

def tty_in_io
  @tty_in_io
end

#tty_out_ioObject (protected)

Returns the value of attribute tty_out_io.



191
192
193
# File 'lib/osctld/console/tty.rb', line 191

def tty_out_io
  @tty_out_io
end

#tty_pidObject (protected)

Returns the value of attribute tty_pid.



191
192
193
# File 'lib/osctld/console/tty.rb', line 191

def tty_pid
  @tty_pid
end

Instance Method Details

#add_client(socket) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/osctld/console/tty.rb', line 169

def add_client(socket)
  log(:info, ct, "Connecting client to TTY #{n}")

  sync do
    @clients << socket

    if opened?
      wake
    elsif ct.state == :running
      open
      wake
    end
  end
end

#client_read(io) ⇒ Object (protected)



230
231
232
233
234
235
# File 'lib/osctld/console/tty.rb', line 230

def client_read(io)
  io.read_nonblock(4096)
rescue IOError, Errno::ECONNRESET
  remove_client(io)
  nil
end

#closeObject



184
185
186
187
# File 'lib/osctld/console/tty.rb', line 184

def close
  wake(:stop)
  @thread.join if @thread
end

#on_closeObject (protected)



242
# File 'lib/osctld/console/tty.rb', line 242

def on_close; end

#openObject



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
142
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
# File 'lib/osctld/console/tty.rb', line 77

def open
  sync { @opened = true }

  log(:info, ct, "Opening TTY #{n}")

  in_r, in_w = IO.pipe
  out_r, out_w = IO.pipe

  CGroup.mkpath_all(ct.entry_cgroup_path.split('/'), chown: ct.user.ugid)

  pid = Process.fork do
    $stdin.reopen(in_r)
    $stdout.reopen(out_w)
    $stderr.reopen(out_w)

    in_w.close
    out_r.close

    @wake_r.close
    @wake_w.close

    SwitchUser.close_fds(except: [
                           0, 1, 2,
                           in_r, out_w
                         ])

    Process.setproctitle("osctld: #{ct.pool.name}:#{ct.id} tty#{n}")

    SwitchUser.switch_to(
      ct.user.sysusername,
      ct.user.ugid,
      ct.user.homedir,
      ct.entry_cgroup_path
    )

    lxc_ct = LXC::Container.new(ct.id, ct.lxc_home)
    fd = lxc_ct.console_fd(n)
    rows, cols = fd.winsize

    buf = ''

    begin
      loop do
        rs, = IO.select([$stdin, fd])

        rs.each do |io|
          case io
          when $stdin
            buf << $stdin.read_nonblock(4096)

            while (i = buf.index("\n"))
              cmd = JSON.parse(buf[0..i], symbolize_names: true)

              if cmd[:keys]
                fd.write(Base64.strict_decode64(cmd[:keys]))
                fd.flush
              end

              if cmd[:rows] && cmd[:cols]
                new_rows = cmd[:rows].to_i
                new_cols = cmd[:cols].to_i

                if new_rows > 0 && new_cols > 0 \
                  && (new_rows != rows || new_cols != cols)
                  fd.winsize = [cmd[:rows], cmd[:cols]]
                end
              end

              buf = buf[i + 1..]
            end

          when fd
            $stdout.write(fd.read_nonblock(4096))
            $stdout.flush
          end
        end
      end
    rescue IOError
      exit
    end
  end

  in_r.close
  out_w.close

  sync do
    self.tty_pid = pid
    self.tty_in_io = in_w
    self.tty_out_io = out_r
  end
end

#opened?Boolean (protected)

Returns:

  • (Boolean)


193
194
195
# File 'lib/osctld/console/tty.rb', line 193

def opened?
  @opened
end

#remove_client(io) ⇒ Object (protected)



237
238
239
240
# File 'lib/osctld/console/tty.rb', line 237

def remove_client(io)
  log(:info, ct, "Disconnecting client from TTY #{n}")
  sync { @clients.delete(io) }
end

#startObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/osctld/console/tty.rb', line 29

def start
  @thread = Thread.new do
    pid = nil

    catch(:stop) do
      loop do
        clients, select_rs = watch_ios

        rs, = IO.select(select_rs)

        rs.each do |io|
          if clients.include?(io)
            data = client_read(io)
            next if data.nil? || tty_in_io.nil?

            tty_write(tty_in_io, data)

          elsif io == tty_out_io
            data = tty_read(tty_out_io)
            next if data.nil?

            clients.each do |c|
              c.write(data)
              c.flush
            rescue SystemCallError
              remove_client(c)
            end

          elsif io == @wake_r
            reason = @wake_r.readline.strip
            throw(:stop) if reason == 'stop'
            next
          end
        end
      end
    end

    sync { @clients.each(&:close) }

    # TODO: why is this happening?
    begin
      Process.wait(tty_pid) if tty_pid
    rescue Errno::ECHILD => e
      log(:warn, ct, "Error occurred when closing tty0: #{e.message}")
    end
  end
end

#syncObject (protected)



244
245
246
247
248
249
250
# File 'lib/osctld/console/tty.rb', line 244

def sync(&)
  if @mutex.owned?
    yield
  else
    @mutex.synchronize(&)
  end
end

#tty_read(io) ⇒ Object (protected)



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/osctld/console/tty.rb', line 209

def tty_read(io)
  io.read_nonblock(4096)
rescue IOError, Errno::ECONNRESET => e
  log(:info, ct, "Closing TTY #{n} (#{e.class}: #{e.message})")

  sync do
    @opened = false
    self.tty_pid = nil
    self.tty_in_io = nil
    self.tty_out_io = nil
  end

  on_close
  nil
end

#tty_write(io, data) ⇒ Object (protected)



225
226
227
228
# File 'lib/osctld/console/tty.rb', line 225

def tty_write(io, data)
  io.write(data)
  io.flush
end

#wake(reason = '') ⇒ Object (protected)



197
198
199
# File 'lib/osctld/console/tty.rb', line 197

def wake(reason = '')
  @wake_w.puts(reason.to_s)
end

#watch_iosObject (protected)



201
202
203
204
205
206
207
# File 'lib/osctld/console/tty.rb', line 201

def watch_ios
  clients = sync { @clients.clone }

  ret = clients + [@wake_r]
  ret << tty_out_io if tty_out_io
  [clients, ret]
end