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.



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

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.



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

def ct
  @ct
end

#nObject (readonly)

Returns the value of attribute n.



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

def n
  @n
end

#tty_in_ioObject (protected)

Returns the value of attribute tty_in_io.



195
196
197
# File 'lib/osctld/console/tty.rb', line 195

def tty_in_io
  @tty_in_io
end

#tty_out_ioObject (protected)

Returns the value of attribute tty_out_io.



195
196
197
# File 'lib/osctld/console/tty.rb', line 195

def tty_out_io
  @tty_out_io
end

#tty_pidObject (protected)

Returns the value of attribute tty_pid.



195
196
197
# File 'lib/osctld/console/tty.rb', line 195

def tty_pid
  @tty_pid
end

Instance Method Details

#add_client(socket) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/osctld/console/tty.rb', line 174

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)



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

def client_read(io)
  io.read_nonblock(4096)

rescue IOError, Errno::ECONNRESET
  remove_client(io)
  nil
end

#closeObject



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

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

#on_closeObject (protected)



248
249
250
# File 'lib/osctld/console/tty.rb', line 248

def on_close

end

#openObject



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
168
169
170
171
172
# File 'lib/osctld/console/tty.rb', line 81

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..-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)


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

def opened?
  @opened
end

#remove_client(io) ⇒ Object (protected)



243
244
245
246
# File 'lib/osctld/console/tty.rb', line 243

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

#startObject



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
76
77
78
79
# File 'lib/osctld/console/tty.rb', line 30

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|
              begin
                c.write(data)
                c.flush

              rescue SystemCallError
                remove_client(c)
              end
            end

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

    sync { @clients.each { |c| c.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)



252
253
254
255
256
257
258
# File 'lib/osctld/console/tty.rb', line 252

def sync
  if @mutex.owned?
    yield
  else
    @mutex.synchronize { yield }
  end
end

#tty_read(io) ⇒ Object (protected)



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/osctld/console/tty.rb', line 213

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)



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

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

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



201
202
203
# File 'lib/osctld/console/tty.rb', line 201

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

#watch_iosObject (protected)



205
206
207
208
209
210
211
# File 'lib/osctld/console/tty.rb', line 205

def watch_ios
  clients = sync { @clients.clone }

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