Module: OsCtld::CGroup

Includes:
OsCtl::Lib::Utils::Log
Defined in:
lib/osctld/cgroup.rb,
lib/osctld/cgroup/param.rb

Defined Under Namespace

Classes: ContainerParams, Param, Params

Constant Summary collapse

FS =
'/sys/fs/cgroup'.freeze
ROOT_GROUP =
'osctl'.freeze
DELEGATE_FILES =
File.read('/sys/kernel/cgroup/delegate').strip.split
MUTEX =
Mutex.new

Class Method Summary collapse

Class Method Details

.abs_cgroup_path(subsys, *path) ⇒ String

Return an absolute path to a cgroup

Parameters:

  • subsys (String)

    subsystem

  • path (String)

Returns:

  • (String)


71
72
73
74
75
76
77
# File 'lib/osctld/cgroup.rb', line 71

def self.abs_cgroup_path(subsys, *path)
  if v1?
    File.join(FS, real_subsystem(subsys), *path)
  else
    File.join(FS, *path)
  end
end

.abs_cgroup_path_exist?(subsys, *path) ⇒ Boolean

Check if cgroup exists

Parameters:

  • subsys (String)

    subsystem

  • path (String)

Returns:

  • (Boolean)


83
84
85
# File 'lib/osctld/cgroup.rb', line 83

def self.abs_cgroup_path_exist?(subsys, *path)
  exist?(abs_cgroup_path(subsys, *path))
end

.attach_to(type, path, pid: nil, debug: false) ⇒ Object

Attach process to a cgroup

Parameters:

  • type (String)

    subsystem

  • path (Array<String>)

    paths to create

  • pid (Integer, nil) (defaults to: nil)

    pid to attach, default to the current process

  • debug (Boolean) (defaults to: false)

    enable extra logging



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/osctld/cgroup.rb', line 192

def self.attach_to(type, path, pid: nil, debug: false)
  cgroup = File.join(abs_cgroup_path(type), *path)

  attached = false
  attach_pid = pid || Process.pid

  ['cgroup.procs', 'tasks'].each do |tasks|
    begin
      File.open(File.join(cgroup, tasks), 'w') do |f|
        f.puts(attach_pid)
      end
    rescue Errno::ENOENT
      next
    end

    if debug
      log(:debug, :cgroup, "Attached PID #{attach_pid} to cgroup #{cgroup}")
    end

    attached = true
    break
  end

  unless attached
    raise "unable to attach pid #{attach_pid} to cgroup #{cgroup.inspect}"
  end

  nil
end

.attach_to_all(path, pid: nil) ⇒ Object

Attach process to a cgroup in all subsystems

Parameters:

  • path (Array<String>)

    paths to create

  • pid (Integer, nil) (defaults to: nil)

    pid to attach, default to the current process



225
226
227
228
229
# File 'lib/osctld/cgroup.rb', line 225

def self.attach_to_all(path, pid: nil)
  subsystems.each do |subsys|
    attach_to(subsys, path, pid:)
  end
end

.available_controllers(cgroup) ⇒ Array<String>

Parameters:

  • cgroup (String)

    absolute path of the cgroup

Returns:

  • (Array<String>)


282
283
284
# File 'lib/osctld/cgroup.rb', line 282

def self.available_controllers(cgroup)
  File.read(File.join(cgroup, 'cgroup.controllers')).strip.split
end

.create(cgroup, delegate:, type:, base:) ⇒ Boolean

Create cgroup

Parameters:

  • cgroup (String)

    absolute cgroup path

  • delegate (Boolean)

    delegate controllers on cgroupv2

  • type (String)

    subsystem

  • base (String)

    absolute path to subsystem root

Returns:

  • (Boolean)

    true if created, false if already existed



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/osctld/cgroup.rb', line 166

def self.create(cgroup, delegate:, type:, base:)
  created = false

  sync do
    begin
      Dir.mkdir(cgroup)
      created = true
    rescue Errno::EEXIST
      created = false
    end

    if created && v2? && delegate
      CGroup.delegate_available_controllers(cgroup)
    end

    init_cgroup(type, base, cgroup) if created
  end

  created
end

.delegate_available_controllers(cgroup) ⇒ Object

Enable all available controllers on cgroup

Parameters:

  • cgroup (String)

    absolute path of the cgroup



272
273
274
275
276
277
278
# File 'lib/osctld/cgroup.rb', line 272

def self.delegate_available_controllers(cgroup)
  cmd = available_controllers(cgroup).map do |controller|
    "+#{controller}"
  end.join(' ')

  File.write(File.join(cgroup, 'cgroup.subtree_control'), cmd)
end

.exist?(abs_path) ⇒ Boolean

Check if cgroup at path exists

Parameters:

  • abs_path (String)

    absolute cgroup path, including ‘/sys/fs/cgroup`

Returns:

  • (Boolean)


90
91
92
# File 'lib/osctld/cgroup.rb', line 90

def self.exist?(abs_path)
  Dir.exist?(abs_path) && File.exist?(File.join(abs_path, 'cgroup.procs'))
end

.freeze_tree(path) ⇒ Object

Freeze cgroup at path

Parameters:

  • path (String)


409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/osctld/cgroup.rb', line 409

def self.freeze_tree(path)
  abs_path = abs_cgroup_path('freezer', path)

  if v1?
    state = File.join(abs_path, 'freezer.state')

    begin
      File.write(state, 'FROZEN')
    rescue SystemCallError => e
      log(:warn, "Unable to freeze #{abs_path}: #{e.message} (#{e.class})")
    end

  else
    state = File.join(abs_path, 'cgroup.freeze')

    begin
      File.write(state, '1')
    rescue SystemCallError => e
      log(:warn, "Unable to freeze #{abs_path}: #{e.message} (#{e.class})")
    end
  end
end

.get_cgroup_pids(subsys, path) ⇒ Array<Integer>

Get a list of processes in a cgroup

Parameters:

  • subsys (String)
  • path (String)

    cgroup path relative to the subsystem

Returns:

  • (Array<Integer>)


394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/osctld/cgroup.rb', line 394

def self.get_cgroup_pids(subsys, path)
  pids = []

  File.open(File.join(abs_cgroup_path(subsys, path), 'cgroup.procs')) do |f|
    f.each_line do |line|
      pid = line.strip.to_i
      pids << pid if pid > 0
    end
  end

  pids
end

.get_process_cgroups(pid) ⇒ Hash<String, String>

Get process cgroups, v1-only

Parameters:

  • pid (Integer)

Returns:

  • (Hash<String, String>)

    subsystem => cgroup path, relative to the mountpoint



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/osctld/cgroup.rb', line 344

def self.get_process_cgroups(pid)
  raise 'CGroup.get_process_cgroups is for cgroup v1 only' unless CGroup.v1?

  ret = {}

  File.open(File.join('/proc', pid.to_s, 'cgroup')) do |f|
    f.each_line do |line|
      s = line.strip

      # Hierarchy ID
      colon = s.index(':')
      next if colon.nil?

      s = s[(colon + 1)..]

      # Controllers
      colon = s.index(':')
      next if colon.nil?

      subsystems = if colon == 0
                     'unified'
                   else
                     s[0..(colon - 1)].split(',').map do |subsys|
                       # Remove name= from named controllers
                       if (eq = subsys.index('='))
                         subsys[(eq + 1)..]
                       else
                         subsys
                       end
                     end.join(',')
                   end

      s = s[(colon + 1)..]

      # Path
      next if s.nil?

      path = s

      ret[subsystems] = path
    end
  end

  ret
end

.inherit_param(base, cgroup, param) ⇒ Object

Inherit cgroup parameter from the parent cgroup

The parameter is considered to be set if it isn’t empty. If the parent cgroup does not have the parameter set, it is inherited from its own parent and so on, all the way to the root cgroup defined by ‘base`. All parents will inherit the parameter as well.

Parameters:

  • base (String)

    absolute path to the root cgroup

  • cgroup (String)

    absolute path of the created cgroup

  • param (String)

    parameter name



260
261
262
263
264
265
266
267
268
# File 'lib/osctld/cgroup.rb', line 260

def self.inherit_param(base, cgroup, param)
  v = File.read(File.join(cgroup, param)).strip
  return v unless v.empty?
  raise "parameter #{param} not set in root cgroup #{base}" if base == cgroup

  v = inherit_param(base, File.dirname(cgroup), param)
  set_param(File.join(cgroup, param), [v])
  v
end

.initObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/osctld/cgroup.rb', line 15

def self.init
  begin
    @version = File.read(RunState::CGROUP_VERSION).strip.to_i
  rescue Errno::ENOENT
    @version = 1
  end

  @version = 1 unless [1, 2].include?(@version)

  @subsystems =
    if @version == 1
      Dir.entries(FS) - ['.', '..']
    else
      ['']
    end
end

.init_cgroup(type, base, cgroup) ⇒ Object

Initialize cgroup after it was created.

This is used to ensure that ‘cpuset` cgroups have parameters `cpuset.cpus` and `cpuset.mems` set.

Parameters:

  • type (String)

    cgroup subsystem

  • base (String)

    absolute path to the root cgroup

  • cgroup (String)

    absolute path of the created cgroup



239
240
241
242
243
244
245
246
247
248
# File 'lib/osctld/cgroup.rb', line 239

def self.init_cgroup(type, base, cgroup)
  case type
  when 'cpuset'
    if v1?
      inherit_param(base, cgroup, 'cpuset.cpus')
      inherit_param(base, cgroup, 'cpuset.mems')
      set_param(File.join(cgroup, 'cgroup.clone_children'), ['1'])
    end
  end
end

.mkpath(type, path, chown: nil, attach: false, leaf: true, pid: nil, debug: false) ⇒ Boolean

Create CGroup a path, optionally chowning the last CGroup or attaching the current process into it.

For example, ‘path` `[’osctl’, ‘subgroup’, ‘subsubgroup’]‘ will create `osctl/subgroup/subsubgroup` in the chosen subsystem. If `chown` or `attach` is set, it has an effect on the last group, i.e. `subsubgroup`,

Parameters:

  • type (String)

    subsystem

  • path (Array<String>)

    paths to create

  • chown (Integer) (defaults to: nil)

    chown the last group to ‘chown`:`chown`

  • attach (Boolean) (defaults to: false)

    attach the current process to the last group

  • leaf (Boolean) (defaults to: true)

    do not delegate controllers to the last cgroup

  • pid (Integer, nil) (defaults to: nil)

    pid to attach, default to the current process

  • debug (Boolean) (defaults to: false)

    enable extra logging

Returns:

  • (Boolean)

    ‘true` if the last component was created, `false` if it already existed



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
# File 'lib/osctld/cgroup.rb', line 110

def self.mkpath(type, path, chown: nil, attach: false, leaf: true, pid: nil, debug: false)
  base = abs_cgroup_path(type)
  tmp = []
  created = false

  path.each_with_index do |name, i|
    tmp << name
    cgroup = File.join(base, *tmp)

    created = create(
      cgroup,
      delegate: i + 1 < path.length || (!leaf && !attach),
      type:,
      base:
    )
  end

  if chown
    cgroup = File.join(base, *path)

    File.chown(chown, chown, cgroup)
    File.chown(chown, chown, File.join(cgroup, 'cgroup.procs'))

    if v2? || type == 'unified'
      DELEGATE_FILES.each do |f|
        File.chown(chown, chown, File.join(cgroup, f))
      rescue Errno::ENOENT
        # ignore
      end
    end
  end

  attach_to(type, path, pid:, debug:) if attach

  created
end

.mkpath_all(path, chown: nil, attach: false, leaf: true, pid: nil, debug: false) ⇒ Object

Create cgroup path in all subsystems, see selfself.mkpath

Parameters:

  • path (Array<String>)

    paths to create

  • chown (Integer) (defaults to: nil)

    chown the last group to ‘chown`:`chown`

  • attach (Boolean) (defaults to: false)

    attach the current process to the last group

  • leaf (Boolean) (defaults to: true)

    do not delegate controllers to the last cgroup

  • pid (Integer, nil) (defaults to: nil)

    pid to attach, default to the current process

  • debug (Boolean) (defaults to: false)

    enable extra logging



154
155
156
157
158
# File 'lib/osctld/cgroup.rb', line 154

def self.mkpath_all(path, chown: nil, attach: false, leaf: true, pid: nil, debug: false)
  subsystems.each do |subsys|
    mkpath(subsys, path, chown:, attach:, pid:, debug:)
  end
end

.real_subsystem(subsys) ⇒ Object

Convert a single subsystem name to the mountpoint name, because some CGroup subsystems are mounted in a shared mountpoint.



47
48
49
50
51
52
# File 'lib/osctld/cgroup.rb', line 47

def self.real_subsystem(subsys)
  return 'cpu,cpuacct' if %w[cpu cpuacct].include?(subsys)
  return 'net_cls,net_prio' if %w[net_cls net_prio].include?(subsys)

  subsys
end

.rmpath(subsystem, path) ⇒ Object

Remove cgroup path

Parameters:

  • subsystem (String)
  • path (String)

    path to remove, relative to the subsystem



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/osctld/cgroup.rb', line 313

def self.rmpath(subsystem, path)
  abs_path = abs_cgroup_path(subsystem, path)

  # Remove subdirectories recursively
  Dir.entries(abs_path).each do |dir|
    next if ['.', '..'].include?(dir)
    next unless Dir.exist?(File.join(abs_path, dir))

    rmpath(subsystem, File.join(path, dir))
  end

  # Remove directory
  Dir.rmdir(abs_path)

  if CGroup.v2?
    # Remove pinned links for the cgroup
    Devices::V2::BpfProgramCache.prune_cgroup_links(abs_path)
  end
rescue Errno::ENOENT
  # pass
end

.rmpath_all(path) ⇒ Object

Remove cgroup path in all subsystems

Parameters:

  • path (String)

    path to remove, relative to subsystem



337
338
339
# File 'lib/osctld/cgroup.rb', line 337

def self.rmpath_all(path)
  subsystems.each { |subsys| rmpath(subsys, path) }
end

.set_param(path, value) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/osctld/cgroup.rb', line 287

def self.set_param(path, value)
  raise CGroupFileNotFound.new(path, value) unless File.exist?(path)

  ret = true

  value.each do |v|
    log(:info, :cgroup, "Set #{path}=#{v}")

    begin
      File.write(path, v.to_s)
    rescue StandardError => e
      log(
        :warn,
        :cgroup,
        "Unable to set #{path}=#{v}: #{e.message}"
      )
      ret = false
    end
  end

  ret
end

.subsystem_pathsHash<Symbol, String>

Returns:

  • (Hash<Symbol, String>)


61
62
63
64
65
# File 'lib/osctld/cgroup.rb', line 61

def self.subsystem_paths
  %i[cpu cpuacct memory pids].to_h do |subsys|
    [subsys, abs_cgroup_path(real_subsystem(subsys.to_s))]
  end
end

.subsystemsArray<String>

Returns a list of mounted CGroup subsystems on the system

Returns:

  • (Array<String>)


56
57
58
# File 'lib/osctld/cgroup.rb', line 56

def self.subsystems
  @subsystems
end

.sync(&block) ⇒ Object



470
471
472
473
474
475
476
# File 'lib/osctld/cgroup.rb', line 470

def self.sync(&block)
  if MUTEX.owned?
    block.call
  else
    MUTEX.synchronize(&block)
  end
end

.thaw_tree(path) ⇒ Object

Thaw all frozen cgroups under path

Parameters:

  • path (String)


434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/osctld/cgroup.rb', line 434

def self.thaw_tree(path)
  abs_path = abs_cgroup_path('freezer', path)

  Dir.entries(abs_path).each do |dir|
    next if ['.', '..'].include?(dir)
    next unless Dir.exist?(File.join(abs_path, dir))

    thaw_tree(File.join(path, dir))
  end

  if v1?
    state = File.join(abs_path, 'freezer.state')

    begin
      if %w[FREEZING FROZEN].include?(File.read(state).strip)
        log(:info, "Thawing #{abs_path}")
        File.write(state, 'THAWED')
      end
    rescue SystemCallError => e
      log(:warn, "Unable to thaw #{abs_path}: #{e.message} (#{e.class})")
    end

  else
    state = File.join(abs_path, 'cgroup.freeze')

    begin
      if File.read(state).strip == '1'
        log(:info, "Thawing #{abs_path}")
        File.write(state, '0')
      end
    rescue SystemCallError => e
      log(:warn, "Unable to thaw #{abs_path}: #{e.message} (#{e.class})")
    end
  end
end

.v1?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/osctld/cgroup.rb', line 37

def self.v1?
  @version == 1
end

.v2?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/osctld/cgroup.rb', line 41

def self.v2?
  @version == 2
end

.version1, 2

Returns cgroup hierarchy version.

Returns:

  • (1, 2)

    cgroup hierarchy version



33
34
35
# File 'lib/osctld/cgroup.rb', line 33

def self.version
  @version
end