Class: OsCtld::Commands::Container::Start

Inherits:
Logged
  • Object
show all
Includes:
OsCtl::Lib::Utils::Log, OsCtl::Lib::Utils::System, Utils::Container, Utils::SwitchUser
Defined in:
lib/osctld/commands/container/start.rb

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 included from Utils::Container

#get_image_path, #get_repositories, #remove_accounting_cgroups

Methods inherited from Logged

#base_execute

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

#execute(ct) ⇒ Object



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
46
47
48
49
50
51
52
# File 'lib/osctld/commands/container/start.rb', line 17

def execute(ct)
  return start_queued(ct) if opts[:queue]

  event_queue = nil

  manipulate(ct) do
    event_queue = Eventd.subscribe
    ret = start_now(ct)

    # Exit if we don't need to wait
    if ret != :wait
      Eventd.unsubscribe(event_queue)
      return ret

    elsif opts[:wait] === false
      Eventd.unsubscribe(event_queue)
      return ok
    end

    # Wait for the container to enter state `running`
    progress('Waiting for the container to start')
    started, msg = wait_for_ct(event_queue, ct)
    Eventd.unsubscribe(event_queue)

    case started
    when :running
      ok
    when :timeout
      error(msg || 'timed out while waiting for container to start')
    when :error
      error(msg || 'container failed to start')
    else
      error(msg || 'unknown error')
    end
  end
end

#findObject



12
13
14
15
# File 'lib/osctld/commands/container/start.rb', line 12

def find
  ct = DB::Containers.find(opts[:id], opts[:pool])
  ct || error!('container not found')
end

#start_now(ct) ⇒ Object (protected)



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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/osctld/commands/container/start.rb', line 83

def start_now(ct)
  error!('start not available') unless ct.can_start?
  return ok if %i[starting running].include?(ct.state) && !opts[:force]

  # Remove pre-existing accounting cgroups to reset counters
  remove_accounting_cgroups(ct)

  # Initiate run configuration
  ct.init_run_conf

  # Remove any left-over temporary mounts
  ct.mounts.prune

  # Mount datasets
  begin
    ct.run_conf.mount
  rescue SystemCommandFailed => e
    return error("failed to mount dataset: #{e.message}")
  end

  # Pre-start distconfig hook
  DistConfig.run(ct.run_conf, :pre_start)

  # CPU scheduler
  CpuScheduler.schedule_ct(ct.run_conf)

  # Optionally add new mounts
  (opts[:mounts] || []).each do |mnt|
    ct.mounts.add(mnt)
  end

  # Reset log file
  File.open(ct.log_path, 'w').close
  File.chmod(0o660, ct.log_path)
  File.chown(0, ct.user.ugid, ct.log_path)

  # Update LXC configuration
  ct.lxc_config.configure

  # Console dir
  console_dir = File.join(ct.pool.console_dir, ct.id)
  FileUtils.mkdir_p(console_dir)
  File.chown(ct.user.ugid, 0, console_dir)
  File.chmod(0o700, console_dir)

  # Remove stray sockets
  sock_path = Console.socket_path(ct)
  if File.exist?(sock_path)
    log(:info, ct, "Removing leftover tty0 socket at #{sock_path}")

    begin
      File.unlink(sock_path)
    rescue Errno::ENOENT
      # Continue if the socket was already deleted
    end
  end

  # Containers are started through two wrappers: pty-wrapper and osctld-ct-start.
  #
  # pty-wrapper is used to allocate a pty and provide access to input/output
  # of the started process.
  #
  # osctld-ct-start is used to reset oom_score_adj to zero, since pty-wrapper
  # have its own oom_score_adj set to -1000 to ensure the OOM killer will
  # not target it. oom_score_adj is inherited on fork, so the process
  # pty-wrapper starts has it set to -1000 as well. Because the process
  # is already run as an unprivileged user, changing oom_score_adj will leave
  # oom_score_adj_min untouched. That would let all container users to disable
  # OOM killer altogether, so osctld-ct-start pings back to osctld, which is
  # running with CAP_SYS_RESOURCE and can set both obj_score_adj and
  # obj_score_adj_min to zero. When it's done, osctld-ct-start execs to
  # lxc-start.
  cmd = [
    OsCtld.bin('osctld-ct-wrapper'),
    "#{ct.pool.name}:#{ct.id}",
    Console.socket_path(ct),
    OsCtld.bin('osctld-ct-start'),
    ct.pool.name,
    ct.id,
    'lxc-start',
    '-P', ct.lxc_home,
    '-n', ct.id,
    '-o', ct.log_path,
    '-l', opts[:debug] ? 'DEBUG' : 'ERROR',
    '-F'
  ]

  r, w = IO.pipe

  progress('Starting container')
  pid = SwitchUser.fork_and_switch_to(
    ct.user.sysusername,
    ct.user.ugid,
    ct.user.homedir,
    ct.wrapper_cgroup_path,
    prlimits: ct.prlimits.export,
    oom_score_adj: -1000,
    keep_fds: [w],
    syslogns_tag: ct.syslogns_tag
  ) do
    # Closed by SwitchUser.fork_and_switch_to
    # r.close

    # This is to remove all Ruby related environment variables, because
    # lxc-start then passes them to hooks, which can make the hooks fail
    # when ruby or osctld gems are upgraded.
    SwitchUser.clear_ruby_env

    wrapper_pid = Process.spawn(
      *cmd,
      pgroup: true, in: :close, out: :close, err: :close
    )

    w.puts(wrapper_pid.to_s)
  end

  w.close
  wrapper_pid = r.readline.strip.to_i
  r.close

  progress('Connecting console')

  begin
    Console.connect_tty0(ct, wrapper_pid)
  rescue Errno::ENOENT
    log(:warn, ct, 'Unable to connect to tty0')
  end

  Process.wait(pid)
  :wait
end

#start_queued(ct) ⇒ Object (protected)



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/osctld/commands/container/start.rb', line 56

def start_queued(ct)
  progress('Joining the queue')

  if opts[:wait] === false
    ct.pool.autostart_plan.enqueue(
      ct,
      priority: opts[:priority],
      start_opts: opts
    )
    return ok
  end

  ret = ct.pool.autostart_plan.start_ct(
    ct,
    priority: opts[:priority],
    start_opts: opts,
    client_handler:
  )

  if ret.nil?
    ok('Timed out')

  else
    ret
  end
end

#wait_for_ct(event_queue, ct) ⇒ Array<Symbol, String> (protected)

Wait for the container to start or fail

Returns:

  • (Array<Symbol, String>)

    :running, :timeout or :error and string message



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/osctld/commands/container/start.rb', line 217

def wait_for_ct(event_queue, ct)
  # Sequence of events that lead to the container being started.
  # We're accepting even `stopping` and `stopped`, since when the container
  # is being restarted, these events may be received and should not cause
  # this method to exit.
  sequence = %i[stopping stopped starting running]
  last_i = nil
  wait_until =
    if opts[:wait] == 'infinity'
      nil
    else
      Time.now + (opts[:wait] || Container::DEFAULT_START_TIMEOUT)
    end

  loop do
    if wait_until
      timeout = wait_until - Time.now
      return [:timeout] if timeout < 0
    end

    if timeout.nil? || timeout > 15
      timeout = 15
    end

    event = event_queue.pop(timeout:)

    if event.nil?
      if Daemon.get.stopping?
        log(:info, ct, 'osctld is shutting down, giving up waiting')
        return [:error, 'osctld is shutting down']
      end

      next
    end

    if event.type == :osctld_shutdown
      log(:info, ct, 'osctld is shutting down, giving up waiting')
      return [:error, 'osctld is shutting down']
    end

    # Ignore irrelevant events
    next if event.type != :state \
            || event.opts[:pool] != ct.pool.name \
            || event.opts[:id] != ct.id

    state = event.opts[:state]
    cur_i = sequence.index(state)

    return [:error] if cur_i.nil? || (last_i && cur_i < last_i)
    return [:running] if state == sequence.last

    last_i = cur_i
  end
end