Class: OsCtld::Container

Inherits:
Object
  • Object
show all
Includes:
OsCtl::Lib::Utils::File, OsCtl::Lib::Utils::Log, OsCtl::Lib::Utils::System, Assets::Definition, Lockable, Manipulable, Utils::SwitchUser
Defined in:
lib/osctld/container.rb

Defined Under Namespace

Modules: Adaptor, Hooks Classes: Builder, DatasetBuilder, Hints, Impermanence, Importer, LxcConfig, RawConfigs, Recovery, RunConfiguration, RunId, StartMenu

Constant Summary collapse

MAP_MODES =
%w[native zfs].freeze
DEFAULT_START_TIMEOUT =
120
DEFAULT_STOP_TIMEOUT =
300

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils::SwitchUser

#ct_attach, #ct_syscmd

Methods included from Assets::Definition

#define_assets

Methods included from Manipulable

#acquire_manipulation_lock, #init_manipulable, #is_being_manipulated?, #manipulate, #manipulated_by, #release_manipulation_lock

Methods included from Lockable

#exclusively, included, #inclusively, #init_lock, #lock, #unlock

Constructor Details

#initialize(pool, id, user = nil, group = nil, dataset = nil, opts = {}) ⇒ Container

Returns a new instance of Container.

Parameters:

  • pool (Pool)
  • id (String)
  • user (User, nil) (defaults to: nil)
  • group (Group, nil) (defaults to: nil)
  • dataset (String, nil) (defaults to: nil)
  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • load (Boolean)

    load config

  • load_from (String)

    load from this string instead of config file

  • staged (Boolean)

    create a staged container

  • devices (Boolean)

    determines whether devices are initialized

  • map_mode (String)
  • dataset_cache (OsCtl::Lib::Zfs::DatasetCache)


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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/osctld/container.rb', line 47

def initialize(pool, id, user = nil, group = nil, dataset = nil, opts = {})
  init_lock
  init_manipulable

  opts[:load] = true unless opts.has_key?(:load)

  if (user.nil? || group.nil?) && !opts[:load]
    raise ArgumentError, 'either set load: true or provide user and group'
  end

  @pool = pool
  @id = id
  @user = user
  @group = group
  @dataset = dataset
  @map_mode = opts[:map_mode]
  @state = opts[:staged] ? :staged : :unknown
  @ephemeral = false
  @netifs = NetInterface::Manager.new(self)
  @cgparams = nil
  @devices = nil
  @prlimits = nil
  @mounts = nil
  @hostname = nil
  @dns_resolvers = nil
  @nesting = false
  @cpu_package = 'auto'
  @seccomp_profile = nil
  @apparmor = AppArmor.new(self)
  @lxc_config = Container::LxcConfig.new(self)
  @init_cmd = nil
  @raw_configs = Container::RawConfigs.new
  @attrs = Attributes.new
  @run_conf = nil
  @hints = Container::Hints.new(self)

  return unless opts[:load]

  load_opts = {
    init_devices: !opts.has_key?(:devices) || opts[:devices],
    dataset_cache: opts[:dataset_cache]
  }

  if opts[:load_from]
    load_config_string(opts[:load_from], **load_opts)
  else
    load_config_file(config_path, **load_opts)
  end
end

Instance Attribute Details

#apparmorObject

Returns the value of attribute apparmor



26
27
28
# File 'lib/osctld/container.rb', line 26

def apparmor
  @apparmor
end

#archObject

Returns the value of attribute arch



26
27
28
# File 'lib/osctld/container.rb', line 26

def arch
  @arch
end

#attrsObject

Returns the value of attribute attrs



26
27
28
# File 'lib/osctld/container.rb', line 26

def attrs
  @attrs
end

#autostartObject

Returns the value of attribute autostart



26
27
28
# File 'lib/osctld/container.rb', line 26

def autostart
  @autostart
end

#cgparamsObject

Returns the value of attribute cgparams



26
27
28
# File 'lib/osctld/container.rb', line 26

def cgparams
  @cgparams
end

#cpu_packageObject

Returns the value of attribute cpu_package



26
27
28
# File 'lib/osctld/container.rb', line 26

def cpu_package
  @cpu_package
end

#datasetObject

Returns the value of attribute dataset



26
27
28
# File 'lib/osctld/container.rb', line 26

def dataset
  @dataset
end

#devicesObject

Returns the value of attribute devices



26
27
28
# File 'lib/osctld/container.rb', line 26

def devices
  @devices
end

#distributionObject

Returns the value of attribute distribution



26
27
28
# File 'lib/osctld/container.rb', line 26

def distribution
  @distribution
end

#dns_resolversObject

Returns the value of attribute dns_resolvers



26
27
28
# File 'lib/osctld/container.rb', line 26

def dns_resolvers
  @dns_resolvers
end

#ephemeralObject Also known as: ephemeral?

Returns the value of attribute ephemeral



26
27
28
# File 'lib/osctld/container.rb', line 26

def ephemeral
  @ephemeral
end

#groupObject

Returns the value of attribute group



26
27
28
# File 'lib/osctld/container.rb', line 26

def group
  @group
end

#hintsObject (readonly)

Returns the value of attribute hints



26
27
28
# File 'lib/osctld/container.rb', line 26

def hints
  @hints
end

#hostnameObject

Returns the value of attribute hostname



26
27
28
# File 'lib/osctld/container.rb', line 26

def hostname
  @hostname
end

#idObject

Returns the value of attribute id



26
27
28
# File 'lib/osctld/container.rb', line 26

def id
  @id
end

#impermanenceObject

Returns the value of attribute impermanence



26
27
28
# File 'lib/osctld/container.rb', line 26

def impermanence
  @impermanence
end

#init_cmdObject

Returns the value of attribute init_cmd



26
27
28
# File 'lib/osctld/container.rb', line 26

def init_cmd
  @init_cmd
end

#lxc_configObject

Returns the value of attribute lxc_config



26
27
28
# File 'lib/osctld/container.rb', line 26

def lxc_config
  @lxc_config
end

#map_modeObject

Returns the value of attribute map_mode



26
27
28
# File 'lib/osctld/container.rb', line 26

def map_mode
  @map_mode
end

#mountedObject (protected)

Returns the value of attribute mounted



888
889
890
# File 'lib/osctld/container.rb', line 888

def mounted
  @mounted
end

#mountsObject

Returns the value of attribute mounts



26
27
28
# File 'lib/osctld/container.rb', line 26

def mounts
  @mounts
end

#nestingObject

Returns the value of attribute nesting



26
27
28
# File 'lib/osctld/container.rb', line 26

def nesting
  @nesting
end

#netifsObject

Returns the value of attribute netifs



26
27
28
# File 'lib/osctld/container.rb', line 26

def netifs
  @netifs
end

#next_run_confObject (readonly)

Returns the value of attribute next_run_conf



26
27
28
# File 'lib/osctld/container.rb', line 26

def next_run_conf
  @next_run_conf
end

#poolObject

Returns the value of attribute pool



26
27
28
# File 'lib/osctld/container.rb', line 26

def pool
  @pool
end

#prlimitsObject

Returns the value of attribute prlimits



26
27
28
# File 'lib/osctld/container.rb', line 26

def prlimits
  @prlimits
end

#raw_configsObject (readonly)

Returns the value of attribute raw_configs



26
27
28
# File 'lib/osctld/container.rb', line 26

def raw_configs
  @raw_configs
end

#run_confObject (readonly)

Returns the value of attribute run_conf



26
27
28
# File 'lib/osctld/container.rb', line 26

def run_conf
  @run_conf
end

#seccomp_profileObject

Returns the value of attribute seccomp_profile



26
27
28
# File 'lib/osctld/container.rb', line 26

def seccomp_profile
  @seccomp_profile
end

#send_logObject

Returns the value of attribute send_log



26
27
28
# File 'lib/osctld/container.rb', line 26

def send_log
  @send_log
end

#start_menuObject

Returns the value of attribute start_menu



26
27
28
# File 'lib/osctld/container.rb', line 26

def start_menu
  @start_menu
end

#stateObject

Returns the value of attribute state



26
27
28
# File 'lib/osctld/container.rb', line 26

def state
  @state
end

#userObject

Returns the value of attribute user



26
27
28
# File 'lib/osctld/container.rb', line 26

def user
  @user
end

#variantObject

Returns the value of attribute variant



26
27
28
# File 'lib/osctld/container.rb', line 26

def variant
  @variant
end

#vendorObject

Returns the value of attribute vendor



26
27
28
# File 'lib/osctld/container.rb', line 26

def vendor
  @vendor
end

#versionObject

Returns the value of attribute version



26
27
28
# File 'lib/osctld/container.rb', line 26

def version
  @version
end

Class Method Details

.default_dataset(pool, id, dataset_cache: nil) ⇒ Object



21
22
23
24
# File 'lib/osctld/container.rb', line 21

def self.default_dataset(pool, id, dataset_cache: nil)
  name = File.join(pool.ct_ds, id)
  OsCtl::Lib::Zfs::Dataset.new(name, base: name, cache: dataset_cache)
end

Instance Method Details

#abs_apply_cgroup_path(subsystem) ⇒ Object



483
484
485
# File 'lib/osctld/container.rb', line 483

def abs_apply_cgroup_path(subsystem)
  CGroup.abs_cgroup_path(subsystem, base_cgroup_path)
end

#abs_cgroup_path(subsystem) ⇒ Object



479
480
481
# File 'lib/osctld/container.rb', line 479

def abs_cgroup_path(subsystem)
  CGroup.abs_cgroup_path(subsystem, cgroup_path)
end

#assetsObject



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

def assets
  define_assets do |add|
    # Datasets
    add.dataset(
      dataset.to_s,
      desc: "Container's rootfs dataset",
      uidmap: map_mode == 'zfs' ? uid_map.map(&:to_a) : nil,
      gidmap: map_mode == 'zfs' ? gid_map.map(&:to_a) : nil,
      properties: if map_mode == 'native'
                    {
                      'uidmap' => 'none',
                      'gidmap' => 'none'
                    }
                  end,
      user: map_mode == 'zfs' ? root_host_uid : 0,
      group: map_mode == 'zfs' ? root_host_gid : 0,
      mode: 0o770,
      validate_if: mounted?
    )

    # Directories and files
    add.directory(
      rootfs,
      desc: "Container's rootfs",
      user: map_mode == 'zfs' ? root_host_uid : 0,
      group: map_mode == 'zfs' ? root_host_gid : 0,
      mode_bit_and: 0o111, # has all executable bits set
      validate_if: mounted?
    )

    add.directory(
      user_hook_script_dir,
      desc: 'User supplied script hooks',
      user: 0,
      group: 0,
      mode: 0o700
    )
    add.directory(
      lxc_dir,
      desc: 'LXC configuration',
      user: 0,
      group: user.ugid,
      mode: 0o750
    )

    lxc_config.assets(add)

    add.file(
      File.join(lxc_dir, '.bashrc'),
      desc: 'Shell configuration file for osctl ct su',
      user: 0,
      group: 0,
      mode: 0o644
    )

    add.file(
      config_path,
      desc: 'Container config for osctld',
      user: 0,
      group: 0,
      mode: 0o400
    )
    add.file(
      log_path,
      desc: 'LXC log file',
      user: 0,
      group: user.ugid,
      mode: 0o660
    )

    run_conf.assets(add) if run_conf

    devices.assets(add)
  end
end

#base_cgroup_pathObject



463
464
465
# File 'lib/osctld/container.rb', line 463

def base_cgroup_path
  inclusively { File.join(group.full_cgroup_path(user), "ct.#{id}") }
end

#can_dist_configure_network?Boolean

Returns:

  • (Boolean)


398
399
400
401
402
403
404
# File 'lib/osctld/container.rb', line 398

def can_dist_configure_network?
  inclusively do
    next false if netifs.detect { |netif| !netif.can_run_distconfig? }

    true
  end
end

#can_start?Boolean

Returns:

  • (Boolean)


369
370
371
# File 'lib/osctld/container.rb', line 369

def can_start?
  inclusively { state != :staged && state != :error && pool.active? }
end

#cgroup_pathObject



467
468
469
# File 'lib/osctld/container.rb', line 467

def cgroup_path
  File.join(base_cgroup_path, 'user-owned')
end

#chgrp(grp, missing_devices: nil) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/osctld/container.rb', line 305

def chgrp(grp, missing_devices: nil)
  self.group = grp

  case missing_devices
  when 'provide'
    devices.ensure_all
    devices.init

  when 'remove'
    devices.remove_missing
    devices.init

  when 'check'
    devices.check_all_available!(group: grp)

  else
    raise "unsupported action for missing devices: '#{missing_devices}'"
  end

  save_config
  lxc_config.configure
  configure_bashrc
end

#chown(user) ⇒ Object



298
299
300
301
302
303
# File 'lib/osctld/container.rb', line 298

def chown(user)
  self.user = user
  save_config
  lxc_config.configure
  configure_bashrc
end

#clear_start_menuObject



651
652
653
654
# File 'lib/osctld/container.rb', line 651

def clear_start_menu
  menu = start_menu
  menu.unlink if menu
end

#clone_from(_ct, id, opts = {}) ⇒ Object (protected)

Change the container so that it becomes a clone of ‘ct` with a different id

Parameters:

  • ct (Container)

    the source container

  • id (String)

    new container id

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :pool (Pool)

    target pool, optional

  • :user (User)

    target user, optional

  • :group (Group)

    target group, optional

  • :dataset (String)

    target dataset, optional

  • :network_interfaces (Boolean)


992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/osctld/container.rb', line 992

def clone_from(_ct, id, opts = {})
  init_lock
  init_manipulable

  @id = id
  @pool = opts[:pool] if opts[:pool]
  @user = opts[:user] if opts[:user]
  @group = opts[:group] if opts[:group]
  @state = :staged
  @send_log = nil

  @dataset = if opts[:dataset]
               OsCtl::Lib::Zfs::Dataset.new(
                 opts[:dataset],
                 base: opts[:dataset]
               )
             else
               Container.default_dataset(@pool, @id)
             end

  @apparmor = @apparmor.dup(self)
  @autostart &&= @autostart.dup(self)
  @cgparams = cgparams.dup(self)
  @prlimits = prlimits.dup(self)
  @mounts = mounts.dup(self)
  @start_menu &&= @start_menu.dup(self)
  @impermanence &&= @impermanence.dup
  @lxc_config = lxc_config.dup(self)
  @raw_configs = raw_configs.dup
  @attrs = attrs.dup
  @run_conf = nil
  @next_run_conf = nil
  @past_run_conf = nil

  @devices = devices.dup(self)
  devices.init

  if opts[:network_interfaces]
    @netifs = netifs.dup(self)
    netifs.each(&:setup)
  else
    @netifs = NetInterface::Manager.new(self)
  end

  @hints = hints.dup(self)
end

#close_send_log(save: true) ⇒ Object



700
701
702
703
704
705
706
# File 'lib/osctld/container.rb', line 700

def close_send_log(save: true)
  exclusively do
    send_log.close
    self.send_log = nil
    save_config if save
  end
end

#config_pathObject



426
427
428
# File 'lib/osctld/container.rb', line 426

def config_path
  inclusively { File.join(pool.conf_path, 'ct', "#{id}.yml") }
end

#configure(distribution, version, arch) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/osctld/container.rb', line 101

def configure(distribution, version, arch)
  exclusively do
    @distribution = distribution
    @version = version
    @arch = arch
    @netifs = NetInterface::Manager.new(self)
    @nesting = false
    @seccomp_profile = default_seccomp_profile
    @cgparams = CGroup::ContainerParams.new(self)
    @devices = Devices::Manager.new_for(self)
    @prlimits = PrLimits::Manager.default(self)
    @mounts = Mount::Manager.new(self)
    @run_conf ||= new_run_conf
    devices.init
    save_config
  end
end

#configure_bashrcObject



679
680
681
682
683
684
685
686
687
688
689
690
691
# File 'lib/osctld/container.rb', line 679

def configure_bashrc
  ErbTemplate.render_to('ct/bashrc', {
    ct: self,
    override: %w[
      attach cgroup console device execute freeze info ls monitor stop top
      unfreeze wait
    ],
    disable: %w[
      autostart checkpoint clone copy create destroy snapshot
      start-ephemeral unshare
    ]
  }, File.join(lxc_dir, '.bashrc'))
end

#current_stateSymbol

Fetch current container state by forking into it

Returns:

  • (Symbol)


349
350
351
352
353
# File 'lib/osctld/container.rb', line 349

def current_state
  self.state = ContainerControl::Commands::State.run!(self).state
rescue ContainerControl::Error
  self.state = :error
end

#datasetsArray<OsCtl::Lib::Zfs::Dataset>

Return a list of all container datasets

Returns:

  • (Array<OsCtl::Lib::Zfs::Dataset>)


452
453
454
455
# File 'lib/osctld/container.rb', line 452

def datasets
  ds = inclusively { dataset }
  [ds] + ds.descendants
end

#default_init_cmdObject (protected)



1043
1044
1045
# File 'lib/osctld/container.rb', line 1043

def default_init_cmd
  ['/sbin/init']
end

#default_seccomp_profileObject (protected)



1039
1040
1041
# File 'lib/osctld/container.rb', line 1039

def default_seccomp_profile
  '/etc/lxc/config/common.seccomp'
end

#dirObject



406
407
408
# File 'lib/osctld/container.rb', line 406

def dir
  dataset.mountpoint
end

#dump_configObject

Dump to config



765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/osctld/container.rb', line 765

def dump_config
  inclusively do
    data = {
      'user' => user.name,
      'group' => group.name,
      'dataset' => dataset.name,
      'map_mode' => map_mode,
      'distribution' => distribution,
      'version' => version,
      'arch' => arch,
      'vendor' => vendor,
      'variant' => variant,
      'net_interfaces' => netifs.dump,
      'cgparams' => cgparams.dump,
      'devices' => devices.dump,
      'prlimits' => prlimits.dump,
      'mounts' => mounts.dump,
      'autostart' => autostart && autostart.dump,
      'ephemeral' => ephemeral,
      'hostname' => hostname && hostname.to_s,
      'dns_resolvers' => dns_resolvers,
      'nesting' => nesting,
      'seccomp_profile' => if seccomp_profile == default_seccomp_profile
                             nil
                           else
                             seccomp_profile
                           end,
      'cpu_package' => cpu_package,
      'init_cmd' => init_cmd,
      'start_menu' => start_menu && start_menu.dump,
      'impermanence' => impermanence && impermanence.dump,
      'raw' => raw_configs.dump,
      'attrs' => attrs.dump,
      'hints' => hints.dump
    }

    data['state'] = 'staged' if state == :staged
    data['send_log'] = send_log.dump if send_log

    data
  end
end

#dup(id, opts = {}) ⇒ Object

Duplicate the container with a different ID

The returned container has ‘state` set to `:staged` and its assets will not exist, so the caller has to build the container and call `ct.state = :complete` for the container to become usable.

Parameters:

  • id (String)

    new container id

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :pool (Pool)

    target pool, optional

  • :user (User)

    target user, optional

  • :group (Group)

    target group, optional

  • :dataset (String)

    target dataset, optional



207
208
209
210
211
# File 'lib/osctld/container.rb', line 207

def dup(id, opts = {})
  ct = clone
  ct.send(:clone_from, self, id, opts)
  ct
end

#each_dataset {|ds| ... } ⇒ Object

Iterate over all container datasets

Yield Parameters:

  • ds (OsCtl::Lib::Zfs::Dataset)


459
460
461
# File 'lib/osctld/container.rb', line 459

def each_dataset(&)
  datasets.each(&)
end

#ensure_run_confContainer::RunConfiguration

Call #init_run_conf unless #run_conf is already set



256
257
258
259
260
261
# File 'lib/osctld/container.rb', line 256

def ensure_run_conf
  exclusively do
    init_run_conf if @run_conf.nil?
    run_conf
  end
end

#entry_cgroup_pathObject



475
476
477
# File 'lib/osctld/container.rb', line 475

def entry_cgroup_path
  File.join(cgroup_path, "lxc.monitor.#{id}")
end

#exportObject

Export to clients



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# File 'lib/osctld/container.rb', line 716

def export
  inclusively do
    {
      pool: pool.name,
      id:,
      user: user.name,
      group: group.name,
      uid_map: user.uid_map.map(&:to_h),
      gid_map: user.gid_map.map(&:to_h),
      map_mode: map_mode,
      dataset: dataset.name,
      rootfs:,
      boot_dataset: run_conf ? run_conf.dataset.name : dataset.name,
      boot_rootfs: run_conf ? run_conf.rootfs : rootfs,
      lxc_path: lxc_home,
      lxc_dir:,
      group_path: cgroup_path,
      distribution: run_conf ? run_conf.distribution : distribution,
      version: run_conf ? run_conf.version : version,
      arch: run_conf ? run_conf.arch : arch,
      vendor: run_conf ? run_conf.vendor : vendor,
      variant: run_conf ? run_conf.variant : variant,
      state:,
      init_pid:,
      autostart: autostart ? true : false,
      autostart_priority: autostart && autostart.priority,
      autostart_delay: autostart && autostart.delay,
      ephemeral:,
      hostname:,
      dns_resolvers:,
      nesting:,
      seccomp_profile:,
      init_cmd: format_user_init_cmd,
      cpu_package_inuse: run_conf ? run_conf.cpu_package : nil,
      cpu_package_set: cpu_package,
      cpu_limit: find_cpu_limit(parents: false),
      memory_limit: find_memory_limit(parents: false),
      swap_limit: find_swap_limit(parents: false),
      start_menu: start_menu ? true : false,
      start_menu_timeout: start_menu && start_menu.timeout,
      impermanence: impermanence ? true : false,
      impermanence_zfs_properties: impermanence&.zfs_properties,
      raw_lxc: raw_configs.lxc,
      log_file: log_path
    }.merge!(attrs.export)
  end
end

#find_cpu_limit(parents: true) ⇒ Integer?

Returns CPU limit in percent (100 % for one CPU).

Returns:

  • (Integer, nil)

    CPU limit in percent (100 % for one CPU)



514
515
516
517
518
519
520
521
522
523
524
# File 'lib/osctld/container.rb', line 514

def find_cpu_limit(parents: true)
  limit = cgparams.find_cpu_limit

  if limit
    return limit
  elsif !parents
    return
  end

  group.find_cpu_limit(parents:)
end

#find_memory_limit(parents: true) ⇒ Integer?

Returns memory limit in bytes.

Returns:

  • (Integer, nil)

    memory limit in bytes



488
489
490
491
492
493
494
495
496
497
498
# File 'lib/osctld/container.rb', line 488

def find_memory_limit(parents: true)
  limit = cgparams.find_memory_limit

  if limit
    return limit
  elsif !parents
    return
  end

  group.find_memory_limit(parents:)
end

#find_swap_limit(parents: true) ⇒ Integer?

Returns swap limit in bytes.

Returns:

  • (Integer, nil)

    swap limit in bytes



501
502
503
504
505
506
507
508
509
510
511
# File 'lib/osctld/container.rb', line 501

def find_swap_limit(parents: true)
  limit = cgparams.find_swap_limit

  if limit
    return limit
  elsif !parents
    return
  end

  group.find_swap_limit(parents:)
end

#forget_past_run_confObject



228
229
230
# File 'lib/osctld/container.rb', line 228

def forget_past_run_conf
  exclusively { @past_run_conf = nil }
end

#format_exec_init_cmdObject



843
844
845
846
847
848
849
850
851
852
# File 'lib/osctld/container.rb', line 843

def format_exec_init_cmd
  cmd = init_cmd || default_init_cmd
  menu = start_menu

  if menu
    menu.init_cmd(cmd)
  else
    cmd
  end.join(' ')
end

#format_user_init_cmdObject



839
840
841
# File 'lib/osctld/container.rb', line 839

def format_user_init_cmd
  (init_cmd || default_init_cmd).join(' ')
end

#fresh_stateSymbol

Fetch current state if the state is not known, otherwise return the known state

Returns:

  • (Symbol)


357
358
359
360
361
362
363
# File 'lib/osctld/container.rb', line 357

def fresh_state
  if state == :unknown
    current_state
  else
    state
  end
end

#get_past_run_confContainer::RunConfiguration?

Returns:



224
225
226
# File 'lib/osctld/container.rb', line 224

def get_past_run_conf
  inclusively { @past_run_conf }
end

#get_run_confContainer::RunConfiguration



219
220
221
# File 'lib/osctld/container.rb', line 219

def get_run_conf
  run_conf || new_run_conf
end

#gid_mapObject



438
439
440
# File 'lib/osctld/container.rb', line 438

def gid_map
  user.gid_map
end

#identObject



97
98
99
# File 'lib/osctld/container.rb', line 97

def ident
  inclusively { "#{pool.name}:#{id}" }
end

#init_pidObject



373
374
375
376
377
# File 'lib/osctld/container.rb', line 373

def init_pid
  inclusively do
    @run_conf ? run_conf.init_pid : nil
  end
end

#init_run_confObject

This must be called on container start



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/osctld/container.rb', line 238

def init_run_conf
  exclusively do
    if @next_run_conf
      @run_conf = @next_run_conf
      @next_run_conf = nil
    else
      @run_conf = new_run_conf
    end

    @run_conf.save
  end

  # Generate LXC configs for current time namespace offsets
  reconfigure
end

#load_config_file(path = nil) ⇒ Object (protected)



890
891
892
893
894
895
896
# File 'lib/osctld/container.rb', line 890

def load_config_file(path = nil, **)
  cfg = parse_yaml do
    OsCtl::Lib::ConfigFile.load_yaml_file(path || config_path)
  end

  load_config_hash(cfg, **)
end

#load_config_hash(cfg, init_devices: true, dataset_cache: nil) ⇒ Object (protected)



909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
# File 'lib/osctld/container.rb', line 909

def load_config_hash(cfg, init_devices: true, dataset_cache: nil)
  cfg = Container::Adaptor.adapt(self, cfg)

  exclusively do
    @state = cfg['state'].to_sym if cfg['state']
    @user ||= DB::Users.find(cfg['user'], pool) || (raise ConfigError, "container #{id}: user '#{cfg['user']}' not found")
    @group ||= DB::Groups.find(cfg['group'], pool) || (raise ConfigError, "container #{id}: group '#{cfg['group']}' not found")

    @dataset ||= if cfg['dataset']
                   OsCtl::Lib::Zfs::Dataset.new(
                     cfg['dataset'],
                     base: cfg['dataset'],
                     cache: dataset_cache
                   )
                 else
                   Container.default_dataset(
                     pool,
                     id,
                     dataset_cache:
                   )
                 end

    @map_mode ||= cfg.fetch('map_mode', 'zfs')
    @distribution = cfg['distribution']
    @version = cfg['version']
    @arch = cfg['arch']
    @vendor = cfg.fetch('vendor', 'default')
    @variant = cfg.fetch('variant', 'default')
    @autostart = cfg['autostart'] && AutoStart::Config.load(self, cfg['autostart'])
    @ephemeral = cfg['ephemeral']
    @hostname = cfg['hostname'] && OsCtl::Lib::Hostname.new(cfg['hostname'])
    @dns_resolvers = cfg['dns_resolvers']
    @nesting = cfg['nesting'] || false
    @cpu_package = cfg.fetch('cpu_package', 'auto')
    @seccomp_profile = cfg['seccomp_profile'] || default_seccomp_profile
    @init_cmd = cfg['init_cmd']

    @start_menu =
      if !cfg.has_key?('start_menu') || cfg['start_menu']
        Container::StartMenu.load(self, cfg['start_menu'] || {})
      end

    @impermanence =
      if cfg['impermanence']
        Container::Impermanence.load(cfg['impermanence'])
      end

    @run_conf = Container::RunConfiguration.load(self)

    if cfg['send_log']
      @send_log = SendReceive::Log.load(cfg['send_log'])
      SendReceive::Tokens.register(@send_log.token)
    end

    @cgparams = CGroup::ContainerParams.load(self, cfg['cgparams'])
    @prlimits = PrLimits::Manager.load(self, cfg['prlimits'] || {})
    @raw_configs = Container::RawConfigs.new(cfg['raw'] || {})
    @attrs = Attributes.load(cfg['attrs'] || {})

    # It's necessary to load devices _before_ netifs. The device manager needs
    # to create cgroups first, in order for echo a > devices.deny to work.
    # If the container has a veth interface, the setup code switches to the
    # container's user, which creates cgroups in all subsystems. Devices then
    # can't be initialized properly.
    @devices = Devices::Manager.load(self, cfg['devices'] || [])
    @devices.init if init_devices

    @netifs = NetInterface::Manager.load(self, cfg['net_interfaces'] || [])
    @mounts = Mount::Manager.load(self, cfg['mounts'] || [])

    @hints = Container::Hints.load(self, cfg['hints'] || {})
  end
end

#load_config_string(str) ⇒ Object (protected)



898
899
900
901
# File 'lib/osctld/container.rb', line 898

def load_config_string(str, **)
  cfg = parse_yaml { OsCtl::Lib::ConfigFile.load_yaml(str) }
  load_config_hash(cfg, **)
end

#log_pathObject



869
870
871
# File 'lib/osctld/container.rb', line 869

def log_path
  inclusively { File.join(pool.log_path, 'ct', "#{id}.log") }
end

#log_typeObject



873
874
875
# File 'lib/osctld/container.rb', line 873

def log_type
  inclusively { "ct=#{pool.name}:#{id}" }
end

#lxc_dir(user: nil, group: nil) ⇒ Object



414
415
416
# File 'lib/osctld/container.rb', line 414

def lxc_dir(user: nil, group: nil)
  inclusively { File.join(lxc_home(user:, group:), id) }
end

#lxc_home(user: nil, group: nil) ⇒ Object



410
411
412
# File 'lib/osctld/container.rb', line 410

def lxc_home(user: nil, group: nil)
  inclusively { (group || self.group).userdir(user || self.user) }
end

#manipulation_resourceObject



877
878
879
# File 'lib/osctld/container.rb', line 877

def manipulation_resource
  ['container', ident]
end

#mount(force: false) ⇒ Object

Mount the container’s dataset

Parameters:

  • force (Boolean) (defaults to: false)

    ensure the datasets are mounted even if osctld already mounted them



266
267
268
269
270
271
# File 'lib/osctld/container.rb', line 266

def mount(force: false)
  return if !force && mounted

  dataset.mount(recursive: true)
  self.mounted = true
end

#mounted?(force: false) ⇒ Boolean

Check if the container’s dataset is mounted

Parameters:

  • force (Boolean) (defaults to: false)

    check if the dataset is mounted even if osctld already mounted it

Returns:

  • (Boolean)


284
285
286
287
288
289
290
# File 'lib/osctld/container.rb', line 284

def mounted?(force: false)
  if force || mounted.nil?
    self.mounted = dataset.mounted?(recursive: true)
  else
    mounted
  end
end

#new_run_confContainer::RunConfiguration



214
215
216
# File 'lib/osctld/container.rb', line 214

def new_run_conf
  Container::RunConfiguration.new(self, load_conf: false)
end

#open_send_log(role, token, opts = {}) ⇒ Object



693
694
695
696
697
698
# File 'lib/osctld/container.rb', line 693

def open_send_log(role, token, opts = {})
  exclusively do
    self.send_log = SendReceive::Log.new(role:, token:, opts:)
    save_config
  end
end

#parse_yamlObject (protected)



903
904
905
906
907
# File 'lib/osctld/container.rb', line 903

def parse_yaml
  yield
rescue Psych::Exception => e
  raise ConfigError.new("Unable to load config of container #{id}", e)
end

#patch_config(new_config) ⇒ Object

Update keys/values from ‘new_config` in the container’s config

Parameters:

  • new_config (Hash)


830
831
832
833
834
835
836
837
# File 'lib/osctld/container.rb', line 830

def patch_config(new_config)
  exclusively do
    tmp = dump_config
    tmp.update(new_config)
    load_config_hash(tmp)
    save_config
  end
end

#read_hostnameString?

Read hostname from a running container

Returns:

  • (String, nil)


658
659
660
661
662
663
664
665
666
667
# File 'lib/osctld/container.rb', line 658

def read_hostname
  return nil unless running?

  begin
    ContainerControl::Commands::GetHostname.run!(self)
  rescue ContainerControl::Error => e
    log(:warn, "Unable to read container hostname: #{e.message}")
    nil
  end
end

#reconfigureObject

Regenerate LXC config



675
676
677
# File 'lib/osctld/container.rb', line 675

def reconfigure
  lxc_config.configure
end

#reload_configObject



818
819
820
# File 'lib/osctld/container.rb', line 818

def reload_config
  load_config_file
end

#replace_config(config) ⇒ Object

Parameters:

  • config (String)


823
824
825
826
# File 'lib/osctld/container.rb', line 823

def replace_config(config)
  load_config_string(config)
  save_config
end

#root_host_gidObject



446
447
448
# File 'lib/osctld/container.rb', line 446

def root_host_gid
  user.gid_map.ns_to_host(0)
end

#root_host_uidObject



442
443
444
# File 'lib/osctld/container.rb', line 442

def root_host_uid
  user.uid_map.ns_to_host(0)
end

#rootfsObject



418
419
420
421
422
423
424
# File 'lib/osctld/container.rb', line 418

def rootfs
  File.join(dir, 'private')
rescue SystemCommandFailed
  # Dataset for staged containers does not have to exist yet, relevant
  # primarily for ct show/list
  nil
end

#running?Boolean

Returns:

  • (Boolean)


365
366
367
# File 'lib/osctld/container.rb', line 365

def running?
  state == :running
end

#save_configObject



808
809
810
811
812
813
814
815
816
# File 'lib/osctld/container.rb', line 808

def save_config
  data = dump_config

  regenerate_file(config_path, 0o400) do |f|
    f.write(OsCtl::Lib::ConfigFile.dump_yaml(data))
  end

  File.chown(0, 0, config_path)
end

#set(opts) ⇒ Object



526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# File 'lib/osctld/container.rb', line 526

def set(opts)
  opts.each do |k, v|
    case k
    when :autostart
      self.autostart = AutoStart::Config.new(self, v[:priority], v[:delay])

    when :ephemeral
      self.ephemeral = true

    when :hostname
      original = nil

      exclusively do
        original = @hostname
        @hostname = OsCtl::Lib::Hostname.new(v)
      end

      DistConfig.run(get_run_conf, :set_hostname, original:)

    when :dns_resolvers
      self.dns_resolvers = v
      DistConfig.run(get_run_conf, :dns_resolvers)

    when :nesting
      self.nesting = true

    when :distribution
      exclusively do
        @distribution = v[:name]
        @version = v[:version]
        @arch = v[:arch] if v[:arch]
        @vendor = v[:vendor]
        @variant = v[:variant]
      end

      if (rc = run_conf)
        rc.set_distribution(
          distribution:,
          version:,
          arch:,
          vendor:,
          variant:
        )
      end

    when :cpu_package
      self.cpu_package = v

    when :seccomp_profile
      self.seccomp_profile = v

    when :init_cmd
      self.init_cmd = v

    when :start_menu
      self.start_menu = Container::StartMenu.new(self, v[:timeout])

    when :impermanence
      self.impermanence = Container::Impermanence.new(v[:zfs_properties].transform_keys(&:to_s))

    when :raw_lxc
      raw_configs.lxc = v

    when :attrs
      attrs.update(v)
    end
  end

  save_config
  lxc_config.configure_base
end

#set_next_run_conf(next_run_conf) ⇒ Object

Parameters:



233
234
235
# File 'lib/osctld/container.rb', line 233

def set_next_run_conf(next_run_conf)
  exclusively { @next_run_conf = next_run_conf }
end

#setup_start_menuObject



646
647
648
649
# File 'lib/osctld/container.rb', line 646

def setup_start_menu
  menu = start_menu
  menu.deploy if menu
end

#startingObject



379
380
381
382
383
384
385
386
# File 'lib/osctld/container.rb', line 379

def starting
  exclusively do
    # Normally {#init_run_conf} is called from {Commands::Container::Start},
    # but in case the lxc-start was invoked manually outside of osctld,
    # initiate the run conf if needed.
    ensure_run_conf
  end
end

#stoppedObject



388
389
390
391
392
393
394
395
396
# File 'lib/osctld/container.rb', line 388

def stopped
  exclusively do
    if run_conf
      run_conf.destroy
      @past_run_conf = @run_conf
      @run_conf = nil
    end
  end
end

#syslogns_tagObject



854
855
856
857
858
859
860
861
862
863
864
865
866
867
# File 'lib/osctld/container.rb', line 854

def syslogns_tag
  max_size = OsCtl::Lib::Sys::SYSLOGNS_MAX_TAG_BYTESIZE

  tag =
    if id.bytesize >= max_size - 1 # -1 for colon used as a separator
      id[0..(max_size - 1)]
    else
      v = ident
      v = v[1..] while v.bytesize > max_size
      v
    end

  tag.rjust(max_size)
end

#uid_mapObject



434
435
436
# File 'lib/osctld/container.rb', line 434

def uid_map
  user.uid_map
end

#unmount(force: false) ⇒ Object

Unmount the container’s dataset



274
275
276
277
278
279
# File 'lib/osctld/container.rb', line 274

def unmount(force: false)
  return if !force && !mounted

  dataset.unmount(recursive: true)
  self.mounted = false
end

#unregisterObject

Unregister the container from internal uses in osctld, e.g. on pool export



709
710
711
712
713
# File 'lib/osctld/container.rb', line 709

def unregister
  exclusively do
    SendReceive::Tokens.free(send_log.token) if send_log
  end
end

#unset(opts) ⇒ Object



598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/osctld/container.rb', line 598

def unset(opts)
  opts.each do |k, v|
    case k
    when :autostart
      self.autostart = false
      pool.autostart_plan.stop_ct(self)

    when :ephemeral
      self.ephemeral = false

    when :hostname
      self.hostname = nil
      DistConfig.run(get_run_conf, :unset_etc_hosts)

    when :dns_resolvers
      self.dns_resolvers = nil

    when :nesting
      self.nesting = false

    when :cpu_package
      self.cpu_package = 'auto'

    when :seccomp_profile
      self.seccomp_profile = default_seccomp_profile

    when :init_cmd
      self.init_cmd = nil

    when :start_menu
      clear_start_menu
      self.start_menu = nil

    when :impermanence
      self.impermanence = nil

    when :raw_lxc
      raw_configs.lxc = nil

    when :attrs
      v.each { |attr| attrs.unset(attr) }
    end
  end

  save_config
  lxc_config.configure_base
end

#update_hintsObject



669
670
671
672
# File 'lib/osctld/container.rb', line 669

def update_hints
  hints.
  save_config
end

#user_hook_script_dirObject



430
431
432
# File 'lib/osctld/container.rb', line 430

def user_hook_script_dir
  inclusively { File.join(pool.root_user_hook_script_dir, 'ct', id) }
end

#wrapper_cgroup_pathObject



471
472
473
# File 'lib/osctld/container.rb', line 471

def wrapper_cgroup_path
  File.join(base_cgroup_path, 'wrapper')
end