aboutsummaryrefslogtreecommitdiffstats
path: root/boxes/vvp-empty/0.0.0/virtualbox/configure_networks.rb
blob: dc81ea3f7e96a493141e3dcf82d263e9aad9e696 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
# -*- encoding: utf-8 -*- 
# ============LICENSE_START======================================================= 
# org.onap.vvp/engagementmgr
# ===================================================================
# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
# ===================================================================
#
# Unless otherwise specified, all software contained herein is licensed
# under the Apache License, Version 2.0 (the “License”);
# you may not use this software except in compliance with the License.
# You may obtain a copy of the License at
#
#             http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#
# Unless otherwise specified, all documentation contained herein is licensed
# under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
# you may not use this documentation except in compliance with the License.
# You may obtain a copy of the License at
#
#             https://creativecommons.org/licenses/by/4.0/
#
# Unless required by applicable law or agreed to in writing, documentation
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ============LICENSE_END============================================
#
# ECOMP is a trademark and service mark of AT&T Intellectual Property.
# -*- mode: ruby -*-
# # vi: set ft=ruby :

# NOTE: This monkey-patching of the coreos guest plugin is a terrible
# hack that needs to be removed once the upstream plugin works with
# alpha CoreOS images.

require 'tempfile'
require 'ipaddr'
require 'log4r'
require Vagrant.source_root.join("plugins/guests/coreos/cap/configure_networks.rb")

BASE_CLOUD_CONFIG = <<EOF
#cloud-config

write_files:
  - path: /etc/environment
    content: |
      COREOS_PUBLIC_IPV4=%s
      COREOS_PRIVATE_IPV4=%s
coreos:
    units:
EOF

NETWORK_UNIT = <<EOF
      - name: %s
        runtime: no
        content: |
          [Match]
          %s

          [Network]
          Address=%s
EOF

# Borrowed from http://stackoverflow.com/questions/1825928/netmask-to-cidr-in-ruby
IPAddr.class_eval do
  def to_cidr
    self.to_i.to_s(2).count("1")
  end
end

module VagrantPlugins
  module GuestCoreOS
    module Cap
      class ConfigureNetworks
        @@logger = Log4r::Logger.new("vagrant::guest::coreos::configure_networks")

        def self.configure_networks(machine, networks)
          public_ipv4, private_ipv4 = get_environment_ips(machine, "127.0.0.1")
          cfg = BASE_CLOUD_CONFIG % [public_ipv4, private_ipv4]

          # Define network units by mac address if possible.
          match_rules = {}
          if false
            #if machine.provider.capability?(:nic_mac_addresses)
            # untested, required feature hasn't made it into a release yet
            match_rules = match_by_mac(machine)
          else
            match_rules = match_by_name(machine)
          end

          @@logger.debug("Networks: #{networks.inspect}")
          @@logger.debug("Interfaces: #{match_rules.inspect}")

          # Generate any static networks, let DHCP handle the rest
          networks.each do |network|
            next if network[:type].to_sym != :static
            interface = network[:interface].to_i
            unit_name = "50-vagrant%d.network" % [interface]

            match = match_rules[interface]
            if match.nil?
                @@logger.warn("Could not find match rule for network #{network.inspect}")
                next
            end

            cidr = IPAddr.new(network[:netmask]).to_cidr
            address = "%s/%s" % [network[:ip], cidr]
            cfg << NETWORK_UNIT % [unit_name, match, address]
          end

          machine.communicate.tap do |comm|
            temp = Tempfile.new("coreos-vagrant")
            temp.binmode
            temp.write(cfg)
            temp.close

            path = "/var/tmp/networks.yml"
            path_esc = path.gsub("/", "-")[1..-1]
            comm.upload(temp.path, path)
            comm.sudo("systemctl start system-cloudinit@#{path_esc}.service")
          end
        end

        # Find IP addresses to export in /etc/environment. This only works
        # for static addresses defined in the user's Vagrantfile.
        def self.get_environment_ips(machine, default)
          public_ipv4 = nil
          private_ipv4 = nil

          machine.config.vm.networks.each do |type, options|
            next if !options[:ip]
            if type == :public_network
              public_ipv4 = options[:ip]
            elsif type == :private_network
              private_ipv4 = options[:ip]
            end
          end

          # Fall back to localhost if no static networks are configured.
          private_ipv4 ||= default
          public_ipv4 ||= private_ipv4
          return [public_ipv4, private_ipv4]
        end

        def self.match_by_name(machine)
          match = {}
          machine.communicate.tap do |comm|
            comm.sudo("ifconfig -a | grep '^en\\|^eth' | cut -f1 -d:") do |_, result|
              result.split("\n").each_with_index do |name, interface|
                match[interface] = "Name=#{name}"
              end
            end
          end
          match
        end

        def self.match_by_mac(machine)
          match = {}
          macs = machine.provider.capability(:nic_mac_addresses)
          macs.each do |adapter, address|
            # The adapter list from VirtualBox is 1 indexed instead of 0
            interface = adapter.to_i - 1
            match[interface] = "MACAddress=#{address}"
          end
          match
        end
      end
    end
  end
end