Class: OsCtl::ExportFS::Operations::Server::Exec

Inherits:
Base
  • Object
show all
Defined in:
lib/osctl/exportfs/operations/server/exec.rb

Overview

Attach to the server's namespaces and run an arbitrary code block

A new process is forked and attached to namespaces of the server's init process. The code block is run in the forked process.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

run

Constructor Details

#initialize(server, &block) ⇒ Exec

Returns a new instance of Exec.

Parameters:



10
11
12
13
14
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 10

def initialize(server, &block)
  @server = server
  @block = block
  @cgroup = Operations::Server::CGroup.new(server)
end

Instance Attribute Details

#blockObject (readonly, protected)

Returns the value of attribute block.



51
52
53
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 51

def block
  @block
end

#cgroupObject (readonly, protected)

Returns the value of attribute cgroup.



51
52
53
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 51

def cgroup
  @cgroup
end

#serverObject (readonly, protected)

Returns the value of attribute server.



51
52
53
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 51

def server
  @server
end

Instance Method Details

#executeObject



16
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
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 16

def execute
  unless server.running?
    fail 'the server is not running'
  end

  pid = server.read_pid
  namespaces = {
    'mnt' => Sys::CLONE_NEWNS,
    'net' => Sys::CLONE_NEWNET,
    'uts' => Sys::CLONE_NEWUTS,
    'ipc' => Sys::CLONE_NEWIPC,
    'pid' => Sys::CLONE_NEWPID,
  }
  ios = {}

  main = Process.fork do
    cgroup.enter_payload

    namespaces.each do |ns, type|
      ios[ns] = File.open(File.join('/proc', pid.to_s, 'ns', ns), 'r')
    end

    namespaces.each do |ns, type|
      Sys.setns_io(ios[ns], type)
      ios[ns].close
    end

    pid = Process.fork { block.call }
    Process.wait(pid)
  end

  Process.wait(main)
end