Class: OsCtld::NetConfig
- Inherits:
-
Object
- Object
- OsCtld::NetConfig
- Defined in:
- lib/osctld/net_config.rb
Overview
Generate network configuration for a container and apply using netlink
NetConfig has to be created before switching to container user and attaching to the container. Call NetConfig.create while running as root and #setup while attached into a container.
Defined Under Namespace
Class Method Summary collapse
Instance Method Summary collapse
- #add_netif(netif) ⇒ Object
-
#initialize ⇒ NetConfig
constructor
A new instance of NetConfig.
-
#setup ⇒ Object
Apply configuration using netlink.
Constructor Details
#initialize ⇒ NetConfig
Returns a new instance of NetConfig.
24 25 26 |
# File 'lib/osctld/net_config.rb', line 24 def initialize @netifs = [] end |
Class Method Details
.create(ct) ⇒ Object
18 19 20 21 22 |
# File 'lib/osctld/net_config.rb', line 18 def self.create(ct) cfg = new ct.netifs.each { |netif| cfg.add_netif(netif) } cfg end |
Instance Method Details
#add_netif(netif) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/osctld/net_config.rb', line 29 def add_netif(netif) n = NetIf.new(netif.name, [], []) [4, 6].each do |ip_v| if netif.respond_to?(:ips) netif.ips(ip_v).each do |ip| n.ips << Addr.new(ip_v, ip.to_s, ip.prefix.to_i) end end case netif.type when :bridge if netif.has_gateway?(ip_v) n.routes << Route.new(ip_v, '0.0.0.0', 0, netif.gateway(ip_v)) end when :routed begin via = netif.default_via(ip_v).to_s n.routes << Route.new(ip_v, via, ip_v == 4 ? 32 : 128, nil) n.routes << Route.new(ip_v, '0.0.0.0', 0, via) rescue RuntimeError # IPv6 is routed via link-local address on the host interface, which # is not known when the container is stopped. next if ip_v == 6 end end end @netifs << n end |
#setup ⇒ Object
Apply configuration using netlink
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 |
# File 'lib/osctld/net_config.rb', line 63 def setup nl = Linux::Netlink::Route::Socket.new @netifs.each do |netif| netif.ips.each do |ip| begin nl.addr.add(index: netif.name, local: ip.address, prefixlen: ip.prefix) rescue Errno::EEXIST next end end netif.routes.each do |route| begin nl.route.add( oif: netif.name, dst: route.address, dst_len: route.prefix, gateway: route.via, ) rescue Errno::EEXIST next end end end end |