summaryrefslogtreecommitdiff
path: root/lib/leap_cli/commands/vagrant.rb
blob: 41dccc9afdd57ef5f1aefaf1805d9982968b54a2 (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
require 'ipaddr'
require 'fileutils'

module LeapCli; module Commands

  desc 'Bring up one or more local virtual machines'
  arg_name '[node-filter]', :optional => true, :multiple => false
  command :'local-up' do |c|
    c.action do |global_options,options,args|
      vagrant_command("up", args)
    end
  end

  desc 'Halt one or more local virtual machines'
  arg_name '[node-filter]', :optional => true, :multiple => false
  command :'local-down' do |c|
    c.action do |global_options,options,args|
      vagrant_command("halt", args)
    end
  end

  desc 'Destroy one or more local virtual machines'
  arg_name '[node-filter]', :optional => true, :multiple => false
  command :'local-reset' do |c|
    c.action do |global_options,options,args|
      vagrant_command("destroy", args)
    end
  end

  public

  def vagrant_ssh_key_file
    file_path = File.expand_path('../../../vendor/vagrant_ssh_keys/vagrant.key', File.dirname(__FILE__))
    Util.assert_files_exist! file_path
    if File.new(file_path).stat.uid == Process.euid
      # if the vagrant.key file is owned by ourselves, we need to make sure that it is not world readable
      FileUtils.cp file_path, '/tmp/vagrant.key'
      FileUtils.chmod 0600, '/tmp/vagrant.key'
      file_path = '/tmp/vagrant.key'
    end
    return file_path
  end

  private

  def vagrant_command(cmd, args)
    assert_config! 'provider.vagrant.network'
    create_vagrant_file
    nodes = manager.filter(args)[:local => true].field(:name)
    if nodes.any?
      execute "cd #{File.dirname(Path.named_path(:vagrantfile))}; vagrant #{cmd} #{nodes.join(' ')}"
    else
      bail! "No nodes found. This command only works on nodes with ip_address in the network #{manager.provider.vagrant.network}"
    end
  end

  def execute(cmd)
    log 2, :run, cmd
    exec cmd
  end

  def create_vagrant_file
    lines = []
    netmask = IPAddr.new('255.255.255.255').mask(manager.provider.vagrant.network.split('/').last).to_s
    lines << %[Vagrant::Config.run do |config|]
    manager.each_node do |node|
      if node.vagrant?
        lines << %[  config.vm.define :#{node.name} do |config|]
        lines << %[    config.vm.box = "minimal-wheezy"]
        lines << %[    config.vm.box_url = "http://cloud.github.com/downloads/leapcode/minimal-debian-vagrant/minimal-wheezy.box"]
        lines << %[    config.vm.network :hostonly, "#{node.ip_address}", :netmask => "#{netmask}"]
        lines << %[  end]
      end
    end
    lines << %[end]
    lines << ""
    write_file! :vagrantfile, lines.join("\n")
  end

end; end