Sha256: 5879527fefe4446ce78ed6b7a58556040dcb1cdbb89d6d4667c967b9e62387e7

Contents?: true

Size: 1.86 KB

Versions: 5

Compression:

Stored size: 1.86 KB

Contents

require 'phut/null_logger'
require 'phut/shell_runner'

module Phut
  # Network virtual link.
  class VirtualLink
    # Creates a valid network device name.
    class NetworkDeviceName
      attr_reader :name
      attr_writer :port_number

      def initialize(name)
        @name = name
      end

      def to_s
        @name.tr('.', '_') + port_number_string
      end

      def inspect
        to_s
      end

      private

      def port_number_string
        @port_number ? '_' + @port_number.to_s : ''
      end
    end

    include ShellRunner

    attr_reader :name_a
    attr_reader :name_b
    attr_reader :device_a
    attr_reader :device_b

    def initialize(name_a, name_b, logger = NullLogger.new)
      fail if name_a == name_b
      @name_a = name_a
      @name_b = name_b
      @device_a = NetworkDeviceName.new(name_a)
      @device_b = NetworkDeviceName.new(name_b)
      @logger = logger
    end

    def run
      stop if up?
      add
      up
    end

    def stop
      sh "sudo ip link delete #{@device_a}"
    rescue
      raise "link #{@name_a} #{@name_b} does not exist!"
    end

    def maybe_stop
      return unless up?
      stop
    end

    def up?
      /^#{@device_a}\s+Link encap:Ethernet/ =~ `LANG=C ifconfig -a` || false
    end

    def connect_to?(vswitch)
      find_network_device(vswitch) || false
    end

    def find_network_device(vswitch_or_vhost)
      [@device_a, @device_b].detect do |each|
        each.name == vswitch_or_vhost.name
      end
    end

    private

    def add
      sh "sudo ip link add name #{@device_a} type veth peer name #{@device_b}"
      sh "sudo /sbin/sysctl -q -w net.ipv6.conf.#{@device_a}.disable_ipv6=1"
      sh "sudo /sbin/sysctl -q -w net.ipv6.conf.#{@device_b}.disable_ipv6=1"
    end

    def up
      sh "sudo /sbin/ifconfig #{@device_a} up"
      sh "sudo /sbin/ifconfig #{@device_b} up"
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
phut-0.7.4 lib/phut/virtual_link.rb
phut-0.7.3 lib/phut/virtual_link.rb
phut-0.7.2 lib/phut/virtual_link.rb
phut-0.7.1 lib/phut/virtual_link.rb
phut-0.7.0 lib/phut/virtual_link.rb