jenkins-bot has submitted this change and it was merged.

Change subject: Enable customization of Vagrant and virtual machine
......................................................................


Enable customization of Vagrant and virtual machine

Adding an additional port forward or changing the memory allocated to
the virtual machine is an often requested feature for complex roles.
These changes allow several methods for customizing the Vagrant
configuration.

* Roles can use the vagrant::settings define to change things
* User supplied settings can be stored in a .settings.yaml file

The user's .settings.yaml trump defaults and role provided values except in
the case of memory limits and cpu count. These are set to the highest
value specified across all sources.

Also introduces a new custom type that can be used to "shout" messages
to the user. This type differs from the built-in notice type in that it
can be configured to apply only when notified by another resource.

Change-Id: I689f7c129241f071ba5b9f503358811255756f6c
---
M .gitignore
M Vagrantfile
A lib/settings.rb
M puppet/manifests/roles/cirrussearch.pp
A puppet/modules/shout/lib/puppet/type/shout.rb
A puppet/modules/vagrant/files/README
A puppet/modules/vagrant/manifests/init.pp
A puppet/modules/vagrant/manifests/settings.pp
A puppet/modules/vagrant/templates/settings.yaml.erb
M support/Vagrantfile-extra.rb
10 files changed, 339 insertions(+), 21 deletions(-)

Approvals:
  Ori.livneh: Looks good to me, approved
  jenkins-bot: Verified



diff --git a/.gitignore b/.gitignore
index a424efe..83557b5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
 /.vagrant
 /.rbenv-version
+/.settings.yaml
 /no-update
 /Vagrantfile-extra.rb
 /Roles.yaml
@@ -17,3 +18,4 @@
 /apt-cache
 !/apt-cache/partial/.gitignore
 /wikimania_scholarships/
+/vagrant.d/
diff --git a/Vagrantfile b/Vagrantfile
index afec9e4..1672e89 100644
--- a/Vagrantfile
+++ b/Vagrantfile
@@ -17,6 +17,10 @@
 # loaded. In case of conflict, values in the 'extra' file will superceded
 # any values in this file. 'Vagrantfile-extra.rb' is ignored by git.
 #
+# Simple configuration changes can be made by creating a file named
+# ".settings.yaml" in the same directory in this file. See the configuration
+# settings section below for the values that may be specified.
+#
 # Please report bugs in this file on Wikimedia's Bugzilla:
 # https://bugzilla.wikimedia.org/enter_bug.cgi?product=MediaWiki-Vagrant
 #
@@ -25,6 +29,59 @@
 #
 $DIR = File.expand_path('..', __FILE__); $: << File.join($DIR, 'lib')
 require 'mediawiki-vagrant'
+require 'settings'
+
+# Configuration settings
+# ----------------------
+# These can be changed by making a `.settings.yaml` file that contains YAML
+# replacements. Example:
+#   BOX_NAME: "foo"
+#   VAGRANT_RAM: 2048
+#   FORWARD_PORTS:
+#     27017: 31337
+#
+# Some roles may also provide new settings values. When applied these roles
+# will require a `vagrant reload` call for their changes to take effect.
+settings = Settings.new({
+    # The vagrant box to load on the VM
+    'BOX_NAME' => 'precise-cloud',
+
+    # Download URL for vagrant box
+    'BOX_URI' => 
'https://cloud-images.ubuntu.com/vagrant/precise/current/precise-server-cloudimg-amd64-vagrant-disk1.box',
+
+    # Amount of RAM to allocate to virtual machine in MB; must be numeric
+    'VAGRANT_RAM' => 768,
+
+    # Number of virtual CPUs to allocate to virtual machine; must be numeric
+    # If you are on a single-core system, change the following default to 1:
+    'VAGRANT_CORES' => 2,
+
+    # Static IP address for virtual machine
+    'STATIC_IP' => '10.11.12.13',
+
+    # The port on the host that should be forwarded to the guest's HTTP server.
+    # Must be numeric.
+    'HTTP_PORT' => 8080,
+
+    # You may provide a map of vm:host port pairs for Vagrant to forward.
+    # Keys and values must be numeric.
+    'FORWARD_PORTS' => {},
+
+    # Enable puppet debug output?
+    # Must be boolean
+    'PUPPET_DEBUG' => false,
+})
+
+# Load role provided settings
+settings_dir = File.join($DIR, 'vagrant.d')
+if Dir.exists?(settings_dir)
+    Dir.glob("#{settings_dir}/*.yaml").each do |f|
+        settings.load(f)
+    end
+end
+
+# Read local configuration overrides
+settings.load(File.join($DIR, '.settings.yaml'))
 
 Vagrant.configure('2') do |config|
     config.vm.hostname = 'mediawiki-vagrant.dev'
@@ -35,8 +92,8 @@
     # the file using another tool that implements SSL properly, and then
     # point Vagrant to the downloaded file:
     #   $ vagrant box add precise-cloud /path/to/file/precise.box
-    config.vm.box = 'precise-cloud'
-    config.vm.box_url = 
'https://cloud-images.ubuntu.com/vagrant/precise/current/precise-server-cloudimg-amd64-vagrant-disk1.box'
+    config.vm.box = settings['BOX_NAME']
+    config.vm.box_url = settings['BOX_URI']
     if config.vm.respond_to? 'box_download_insecure'  # Vagrant 1.2.6+
         config.vm.box_download_insecure = true
     end
@@ -45,14 +102,19 @@
     # See https://github.com/mitchellh/vagrant/issues/1673
     config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
 
-    config.vm.network :private_network,
-        ip: '10.11.12.13'
-
-    # The port on the host that should be forwarded to the guest's HTTP server.
-    FORWARDED_PORT = 8080
+    config.vm.network :private_network, ip: settings['STATIC_IP']
 
     config.vm.network :forwarded_port,
-        guest: 80, host: FORWARDED_PORT, id: 'http'
+        guest: 80, host: settings['HTTP_PORT'].to_i, id: 'http'
+
+    # Forward additional ports
+    if settings['FORWARD_PORTS']
+        settings['FORWARD_PORTS'].each do |guest_port,host_port|
+            config.vm.network :forwarded_port,
+                :host => host_port.to_i, :guest => guest_port.to_i,
+                auto_correct: true
+        end
+    end
 
     config.vm.synced_folder '.', '/vagrant',
         id: 'vagrant-root',
@@ -68,15 +130,13 @@
 
     config.vm.provider :virtualbox do |vb|
         # See http://www.virtualbox.org/manual/ch08.html for additional 
options.
-        vb.customize ['modifyvm', :id, '--memory', '1024']
+        vb.customize ['modifyvm', :id, '--memory', 
settings['VAGRANT_RAM'].to_i]
+        vb.customize ['modifyvm', :id, '--cpus', 
settings['VAGRANT_CORES'].to_i]
         vb.customize ['modifyvm', :id, '--ostype', 'Ubuntu_64']
         vb.customize ['modifyvm', :id, '--ioapic', 'on']  # Bug 51473
 
         # To boot the VM in graphical mode, uncomment the following line:
         # vb.gui = true
-
-        # If you are on a single-core system, comment out the following line:
-        vb.customize ['modifyvm', :id, '--cpus', '2']
     end
 
     config.vm.provision :puppet do |puppet|
@@ -94,14 +154,16 @@
         ]
 
         # For more output, uncomment the following line:
-        # puppet.options << '--debug'
+        if settings['PUPPET_DEBUG']
+            puppet.options << '--debug'
+        end
 
         # Windows's Command Prompt has poor support for ANSI escape sequences.
         puppet.options << '--color=false' if windows?
 
         puppet.facter = $FACTER = {
             'fqdn'               => config.vm.hostname,
-            'forwarded_port'     => FORWARDED_PORT,
+            'forwarded_port'     => settings['HTTP_PORT'],
             'shared_apt_cache'   => '/vagrant/apt-cache/',
         }
     end
diff --git a/lib/settings.rb b/lib/settings.rb
new file mode 100644
index 0000000..7817868
--- /dev/null
+++ b/lib/settings.rb
@@ -0,0 +1,42 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+#
+# Simple settings management for customizing the Vagrantfile behavior
+
+require 'yaml'
+
+class Settings
+
+    def initialize(defaults)
+        @settings = {}
+        update(defaults)
+    end
+
+    # Get a setting
+    def [](key)
+        @settings.fetch(key, nil)
+    end
+
+    # Load settings from a file
+    def load(file)
+        update(YAML.load_file(file)) if File.exists?(file)
+    end
+
+    # Update current settings with a new hash
+    def update(other_settings)
+        @settings.update(other_settings) do |key, oldval, newval|
+            if key == 'FORWARD_PORTS'
+                # Merge port mappings
+                oldval.update(newval)
+
+            elsif key == 'VAGRANT_RAM' || key == 'VAGRANT_CORES'
+                # Keep the biggest ram and cores
+                [oldval, newval].max
+
+            else
+                # New hotness trumps old busted
+                newval
+            end
+        end
+    end
+end
diff --git a/puppet/manifests/roles/cirrussearch.pp 
b/puppet/manifests/roles/cirrussearch.pp
index da2627f..f1db760 100644
--- a/puppet/manifests/roles/cirrussearch.pp
+++ b/puppet/manifests/roles/cirrussearch.pp
@@ -16,12 +16,15 @@
         require  => Service['elasticsearch'],
     }
 
+    vagrant::settings { 'cirrussearch':
+        ram           => 1024,
+        forward_ports => { 9200 => 9200 },
+    }
+
     exec { 'build CirrusSearch search index':
         command     => 'php ./maintenance/updateSearchIndexConfig.php && php 
./maintenance/forceSearchIndex.php && touch .indexed',
         creates     => '/vagrant/mediawiki/extensions/CirrusSearch/.indexed',
         cwd         => '/vagrant/mediawiki/extensions/CirrusSearch',
         require     =>  Mediawiki::Extension['CirrusSearch'],
     }
-
-    notice('If you want to debug Elasticsearch queries you should forward port 
9200 from the VM.  See supprt/Vagrantfile-extra.rb for instructions.')
 }
diff --git a/puppet/modules/shout/lib/puppet/type/shout.rb 
b/puppet/modules/shout/lib/puppet/type/shout.rb
new file mode 100644
index 0000000..9631dee
--- /dev/null
+++ b/puppet/modules/shout/lib/puppet/type/shout.rb
@@ -0,0 +1,62 @@
+# coding: UTF-8
+# puppet-shout - Shout at the user
+#
+require 'puppet/type'
+
+Puppet::Type.newtype(:shout) do
+    @doc = "Tell the user about something important.
+
+        Example:
+
+            shout {'at the devil':
+                message => 'Mötley Crüe rulz! \m/',
+            }
+    "
+
+    newproperty(:message) do
+        desc "The message to shout."
+
+        def sync
+            banner = '!' * 78
+            pad = ' ' * 4
+            msg = self.should.split("\n").map! {|m| m.strip}
+            msg = msg.join("\n#{pad}")
+            Puppet.send('alert',
+                "\n#{banner}\n#{pad}#{msg}\n#{banner}")
+            return
+        end
+
+        def retrieve
+            :absent
+        end
+
+        def insync?(is)
+            # Shout unless we are only fired on refresh
+            sync unless @resource[:refreshonly] == :true
+
+            # Horrible hack! We always return true from insync? so that puppet
+            # doesn't log a notice of the value change in addition to the
+            # announcement we may make.
+            true
+        end
+
+        defaultto { @resource[:name] }
+    end
+
+    newparam(:refreshonly) do
+        desc "Whether or not to repeatedly call this resource. If true, this
+            resource will only be executed when another resource tells it to
+            do so. If set to false, it will execute at each run."
+        defaultto :true
+        newvalues(:true, :false)
+    end
+
+    newparam(:name) do
+        desc "The name of the shout resource"
+        isnamevar
+    end
+
+    def refresh
+        self.property(:message).sync
+    end
+end
diff --git a/puppet/modules/vagrant/files/README 
b/puppet/modules/vagrant/files/README
new file mode 100644
index 0000000..f2a3e9d
--- /dev/null
+++ b/puppet/modules/vagrant/files/README
@@ -0,0 +1,2 @@
+This directory contains Vagrant configuration files that are managed by Puppet.
+PUPPET WILL DELETE ANY UNMANAGED FILES IN THIS DIRECTORY WITHOUT WARNING.
diff --git a/puppet/modules/vagrant/manifests/init.pp 
b/puppet/modules/vagrant/manifests/init.pp
new file mode 100644
index 0000000..649baac
--- /dev/null
+++ b/puppet/modules/vagrant/manifests/init.pp
@@ -0,0 +1,33 @@
+# vim:set sw=4 ts=4 sts=4 et:
+
+# == Class vagrant
+#
+#
+# === Parameters
+#
+# [*settings_dir*]
+#   Directory to place vagrant settings files in. This must match
+#   configuration in the Vagrantfile itself for the files to be found at
+#   Vagrant runtime. Default is '/vagrant/vagrant.d'.
+#
+class vagrant(
+    $settings_dir = '/vagrant/vagrant.d',
+){
+
+    File {
+        group   => 'www-data',
+        owner   => 'vagrant',
+    }
+
+    file { $settings_dir:
+        ensure  => directory,
+        purge   => true,
+        recurse => true,
+    }
+
+    file { "${settings_dir}/README":
+        ensure  => present,
+        require => File[$settings_dir],
+        source  => 'puppet:///modules/vagrant/README',
+    }
+}
diff --git a/puppet/modules/vagrant/manifests/settings.pp 
b/puppet/modules/vagrant/manifests/settings.pp
new file mode 100644
index 0000000..766c4db
--- /dev/null
+++ b/puppet/modules/vagrant/manifests/settings.pp
@@ -0,0 +1,88 @@
+# vim:set sw=4 ts=4 sts=4 et:
+
+# == Define: vagrant::settings
+#
+# Provision a yaml settings file that will be read by the Vagrantfile managing
+# the VM.
+#
+#
+# === Parameters
+#
+# [*priority*]
+#   This parameter takes a numeric value, which is used to generate a
+#   prefix for the configuration snippet. Settings managed by Puppet will
+#   load in order of priority, with smaller values loading first. The
+#   default is 10. You only need to override the default if you want
+#   these settings to load before or after some other settings.
+#
+# [*box_name*]
+#   Name of the Vagrant box to load on the VM.
+#
+# [*box_uri*]
+#   Download URL for the vagrant box.
+#
+# [*ram*]
+#   Amount of RAM to allocate to the virtual machine in MB.
+#
+# [*cores*]
+#   Number of virtual CPUs to allocate to virtual machine.
+#
+# [*static_ip*]
+#   Static IP address for virtual machine.
+#
+# [*http_port*]
+#   The port on the host machine that should be forwared to the virtual
+#   machine's HTTP server (port 80).
+#
+# [*forward_ports*]
+#   Hash of virtual machine port to host machine port pairs for Vagrant to
+#   forward.
+#
+# [*puppet_debug*]
+#   Run puppet in debug mode.
+#
+# === Example
+#
+# Configure an Ubuntu 14.04 instance with a lot of ram and cpu and
+# port forwarding for Elasticsearch development:
+#
+#   vagrant::settings { 'big trusty instance':
+#     box_name      => 'trusty-cloud',
+#     box_uri       => 
'http://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box',
+#     ram           => 4096,
+#     cores         => 4,
+#     forward_ports => { 9200 => 9200 },
+#   }
+#
+define vagrant::settings(
+    $ensure        = present,
+    $priority      = 10,
+    $box_name      = undef,
+    $box_uri       = undef,
+    $ram           = undef,
+    $cores         = undef,
+    $static_ip     = undef,
+    $http_port     = undef,
+    $forward_ports = undef,
+    $puppet_debug  = undef,
+) {
+    include ::vagrant
+
+    # make a safe filename based on our title
+    $fname = inline_template('<%= @title.gsub(/\W/, "-") %>')
+    $settings_file = sprintf('%s/%.2d-%s.yaml',
+        $::vagrant::settings_dir, $priority, $fname)
+
+    file { $settings_file:
+        ensure  => $ensure,
+        content => template('vagrant/settings.yaml.erb'),
+        group   => 'www-data',
+        owner   => 'vagrant',
+        notify  => Shout[$settings_file],
+    }
+
+    shout { $settings_file:
+      message => 'Vagrant settings have been changed.
+        Run `vagrant reload` to apply the changes.',
+    }
+}
diff --git a/puppet/modules/vagrant/templates/settings.yaml.erb 
b/puppet/modules/vagrant/templates/settings.yaml.erb
new file mode 100644
index 0000000..7db9d86
--- /dev/null
+++ b/puppet/modules/vagrant/templates/settings.yaml.erb
@@ -0,0 +1,29 @@
+# Vagrant settings
+# Managed by puppet. Local changes will be lost on next puppet run.
+<%- if @box_name -%>
+BOX_NAME: "<%= @box_name %>"
+<%- end -%>
+<%- if @box_uri -%>
+BOX_URI: "<%= @box_uri %>"
+<%- end -%>
+<%- if @ram -%>
+VAGRANT_RAM: <%= @ram.to_i %>
+<%- end -%>
+<%- if @cores -%>
+VAGRANT_CORES: <%= @cores.to_i %>
+<%- end -%>
+<%- if @static_ip -%>
+STATIC_IP: "<%= @static_ip %>"
+<%- end -%>
+<%- if @http_port -%>
+HTTP_PORT: <%= @http_port.to_i %>
+<%- end -%>
+<%- if @puppet_debug -%>
+PUPPET_DEBUG: <%= @puppet_debug %>
+<%- end -%>
+<%- if @forward_ports -%>
+FORWARD_PORTS:
+    <%- @forward_ports.keys.sort.each do |k| -%>
+    <%= k.to_i %>: <%= @forward_ports[k].to_i %>
+    <%- end -%>
+<%- end -%>
diff --git a/support/Vagrantfile-extra.rb b/support/Vagrantfile-extra.rb
index 194f906..275cf85 100644
--- a/support/Vagrantfile-extra.rb
+++ b/support/Vagrantfile-extra.rb
@@ -36,9 +36,4 @@
     # Sequel Pro) to manage the database server running on the VM.
     # config.vm.network :forwarded_port,
     #    guest: 3306, host: 3306, id: 'mysql'
-
-    # Forward Elasticsearch port.  This allows you to debug Elasticsearch
-    # queries easilly with something like the Sense Chrome Plugin.
-    # config.vm.network :forwarded_port,
-    #     guest: 9200, host: 9200, id: 'elasticsearch'
 end

-- 
To view, visit https://gerrit.wikimedia.org/r/121425
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: merged
Gerrit-Change-Id: I689f7c129241f071ba5b9f503358811255756f6c
Gerrit-PatchSet: 10
Gerrit-Project: mediawiki/vagrant
Gerrit-Branch: master
Gerrit-Owner: BryanDavis <[email protected]>
Gerrit-Reviewer: BryanDavis <[email protected]>
Gerrit-Reviewer: Manybubbles <[email protected]>
Gerrit-Reviewer: Ori.livneh <[email protected]>
Gerrit-Reviewer: Yuvipanda <[email protected]>
Gerrit-Reviewer: jenkins-bot <>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to