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:



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

def initialize(server, &block)
  super()
  @server = server
  @block = block
  @cgroup = Operations::Server::CGroup.new(server)
  @sys = OsCtl::Lib::Sys.new
end

Instance Attribute Details

#blockObject (readonly, protected)

Returns the value of attribute block.



55
56
57
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 55

def block
  @block
end

#cgroupObject (readonly, protected)

Returns the value of attribute cgroup.



55
56
57
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 55

def cgroup
  @cgroup
end

#serverObject (readonly, protected)

Returns the value of attribute server.



55
56
57
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 55

def server
  @server
end

#sysObject (readonly, protected)

Returns the value of attribute sys.



55
56
57
# File 'lib/osctl/exportfs/operations/server/exec.rb', line 55

def sys
  @sys
end

Instance Method Details

#executeObject



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

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

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

  main = Process.fork do
    cgroup.enter_payload

    namespaces.each_key do |ns|
      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