Module: Mccloud::Command

Includes:
Util
Defined in:
lib/mccloud/command.rb,
lib/mccloud/command/ip.rb,
lib/mccloud/command/lb.rb,
lib/mccloud/command/up.rb,
lib/mccloud/command/vm.rb,
lib/mccloud/command/ips.rb,
lib/mccloud/command/ssh.rb,
lib/mccloud/command/base.rb,
lib/mccloud/command/halt.rb,
lib/mccloud/command/init.rb,
lib/mccloud/command/image.rb,
lib/mccloud/command/sorry.rb,
lib/mccloud/command/define.rb,
lib/mccloud/command/reload.rb,
lib/mccloud/command/status.rb,
lib/mccloud/command/balance.rb,
lib/mccloud/command/destroy.rb,
lib/mccloud/command/forward.rb,
lib/mccloud/command/helpers.rb,
lib/mccloud/command/keypair.rb,
lib/mccloud/command/package.rb,
lib/mccloud/command/version.rb,
lib/mccloud/command/keystore.rb,
lib/mccloud/command/template.rb,
lib/mccloud/command/undefine.rb,
lib/mccloud/command/bootstrap.rb,
lib/mccloud/command/provision.rb,
lib/mccloud/command/group_base.rb,
lib/mccloud/command/named_base.rb,
lib/mccloud/provider/core/vm/old_halt.rb,
lib/mccloud/provider/core/vm/old_multi.rb,
lib/mccloud/provider/core/vm/old_reload.rb,
lib/mccloud/provider/core/vm/old_server.rb,
lib/mccloud/provider/core/vm/old_wizard.rb,
lib/mccloud/provider/core/vm/old_suspend.rb,
lib/mccloud/provider/aws/provider/old_ips.rb,
lib/mccloud/provider/aws/stack/old_destroy.rb,
lib/mccloud/provider/aws/provider/old_sorry.rb,
lib/mccloud/provider/core/vm/old_ssh_command.rb,
lib/mccloud/provider/aws/provider/old_flavors.rb,
lib/mccloud/provider/aws/provider/old_package.rb,
lib/mccloud/provider/aws/provider/old_deregister.rb,
lib/mccloud/provider/aws/provider/old_loadbalance.rb

Defined Under Namespace

Modules: Helpers Classes: BalanceCommand, Base, BootstrapCommand, DefineCommand, DestroyCommand, ForwardCommand, GroupBase, HaltCommand, ImageCommand, InitCommand, IpCommand, IpsCommand, KeypairCommand, KeystoreCommand, LbCommand, NamedBase, PackageCommand, ProvisionCommand, ReloadCommand, SorryCommand, SshCommand, StatusCommand, TemplateCommand, UnDefineCommand, UpCommand, VersionCommand, VmCommand

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.init(amiId = nil, options = nil) ⇒ Object



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
# File 'lib/mccloud/provider/core/vm/old_wizard.rb', line 10

def self.init(amiId=nil,options=nil)

  trap("INT") { puts
    puts ""; exit }

    init_options=ARGV

    puts "Welcome to the Mccloud configurator: "
    init_options<< "--mcPrefix"
    init_options<< "mccloud"

    init_options<< "--providerId"
    init_options<< "AWS"

    create_fog('AWS')

    template=ERB.new File.new(File.join(File.dirname(__FILE__),"..","templates/Mccloudfile.erb")).read,nil,"%"
    mcPrefix="mccloud"
    providerId="AWS"
    mcEnvironment=select_environment
    mcIdentity=select_identity

    serverName=select_servername

    #strip all 
    serverName.gsub!(/[^[:alnum:]]/, '_') 

    image_selection=select_image
    imageId=image_selection['imageId']
    userName=image_selection['userName']
    imageDescription=image_selection['imageDescription']
    arch=image_selection['arch']

    full_bootstrapScript=image_selection['bootstrap']
    copy_bootstrap(full_bootstrapScript)
    bootstrapScript=File.basename("#{full_bootstrapScript}")

    availabilityZone=select_zone
    flavorId=select_flavor(arch)

    fullIdentity=Array.new
    if !mcPrefix.nil? 
      fullIdentity << mcPrefix 
    end
    if mcEnvironment!="" 
      fullIdentity << mcEnvironment
    end
    if mcIdentity!=""
      fullIdentity << mcIdentity 
    end
    full_identity=fullIdentity.join("-")

    securityGroup=select_security_group(full_identity)

    keypair_selection=select_keypair
    keyName=keypair_selection['keyName']
    privateKeyPath=keypair_selection['privateKeyPath']
    publicKeyPath=keypair_selection['publicKeyPath']

    confirmed=false
    content=template.result(binding)
    if File.exists?("Mccloudfile")
      confirmed=agree("\nDo you want to overwrite your existing config?: ") { |q| q.default="no"}
    else
      confirmed=true
    end
    if confirmed
      puts
      puts "Writing your config file Mccloudfile"
      mccloudfile=File.new("Mccloudfile","w")
      mccloudfile.puts(content)
      mccloudfile.close
    else
      puts "Ok did not overwrite the config,  moving along"
    end  


    #Mccloud::Generators.run_cli Dir.pwd, File.basename(__FILE__), Mccloud::VERSION, init_options
end

Instance Method Details

#command(selection = nil, command = "who am i") ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/mccloud/provider/core/vm/old_ssh_command.rb', line 3

def command(selection=nil,command="who am i")
  unless options.parallel?
    on_selected_machines(selection) do |id,vm|
      server=PROVIDER.servers.get(id)
      server.private_key_path=vm.private_key
      server.username = vm.user
      if server.state == "running"
        result=server.ssh(command)
        puts result[0].stdout
      else
        puts "not running so what's the point"
      end
    end
  else
    invoke :multi , [selection, command]
  end
end

#deregister(imageId = nil, options = nil) ⇒ Object



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
# File 'lib/mccloud/provider/aws/provider/old_deregister.rb', line 5

def deregister(imageId=nil,options=nil)

  if imageId.nil?
    puts "[Error] We need at least need an imageId."
    exit
  end


  #f=Fog::Compute.new({ :region => "eu-west-1", :provider => "AWS"})
  # i=f.create_image("i-c1ac2bb7","name","description")
  # f.images.all({ "Owner" => "self"})
  # f.deregister_image("ami-796d5b0d")

  puts "Looking for imageId: #{imageId}"
  @environment.config.providers.each do |name,provider|
    begin
      image=provider.images.get(imageId)
      if image.nil?
        puts "[#{name}] - ImageId #{imageId} not found"
      else
        puts "[#{name}] - ImageId #{imageId} found"
        puts "[#{name}] - Deregistering #{imageId} now"
        begin
          provider.deregister_image(imageId)
        rescue Fog::Service::Error => fogerror
          puts "[Error] #{fogerror}"
        end
      end
    end
  end


end

#destroy(selection = nil, options = nil) ⇒ Object



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
# File 'lib/mccloud/provider/aws/stack/old_destroy.rb', line 5

def destroy(selection=nil,options=nil)

  on_selected_stacks(selection) do |id,stack|
    stackfilter=@environment.config.mccloud.stackfilter        
    stack_fullname="#{stackfilter}#{stack.name}"

    stack_exists=false
    provider=@environment.config.providers[stack.provider]         
    cf = Fog::AWS::CloudFormation.new(stack.provider_options)

    begin
      cf.get_template("#{stack_fullname}")
      stack_exists=true
    rescue   Exception => e
      #puts "[#{stack.name}] - Error\n #{e}"
    end

    if stack_exists
      begin
        puts "[#{stack.name}] - Deleting stack"
        cf.delete_stack(stack_fullname)
        events=cf.describe_stack_events(stack_fullname).body
        sorted_events=events['StackEvents']
        sorted_events.reverse.each do |event|
          printf "  %-25s %-30s %-30s %-20s %-15s\n", event['Timestamp'],event['ResourceType'],event['LogicalResourceId'], event['ResourceStatus'],event['ResourceStatusReason']
        end
      rescue Excon::Errors::BadRequest => e
        puts "[#{stack.name}] - Error deleting the stacks:\n #{e.response.body}"
      end    
    else
      puts "[#{stack.name}] - Stack does not exist"
    end


  end

end

#flavorsObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/mccloud/provider/aws/provider/old_flavors.rb', line 3

def flavors()  
  puts ""
  puts "Available flavors"
  provider=@provider.config.providers.first[1]
  flavors=provider.flavors
  formatting="%-12s %-35s %-6s %-6s %-6s %-6s\n"
  printf formatting,"id","name","bits","cores","disk", "ram"
  80.times { |i| printf "=" } ; puts

  flavors.each  do |flavor|
    printf formatting,flavor.id,flavor.name[0..34],flavor.bits,flavor.cores,flavor.disk, flavor.ram
  end

end

#halt(selection = nil, options = nil) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/mccloud/provider/core/vm/old_halt.rb', line 6

def halt(selection=nil,options=nil)
  on_selected_machines(selection) do |id,vm|
    unless vm.instance.state == "stopping" || vm.instance.state =="stopped"
      puts "Halting machine #{vm.name}(#{id})"
      vm.instance.stop
      vm.instance.wait_for { printf "."; STDOUT.flush; state=="stopped"}
      puts 
    else
      puts "#{vm.name}(#{id}) is already halted."        
    end
  end
end

#ips(selection, options) ⇒ Object



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
# File 'lib/mccloud/provider/aws/provider/old_ips.rb', line 7

def ips(selection, options)
  filter=@environment.config.mccloud.stackfilter

  on_selected_ips(selection) do |id,ip|
    ip_instance=ip.instance
    unless ip_instance.nil?
      vm=@environment.config.vms[ip.vmname]
      puts "[#{ip.name}] Associating #{ip.address} with #{ip.vmname}"
      ip_instance.server=vm.instance
    else
      puts "[#{ip.name}] Ipaddress does not (yet) exist"
    end
    #        ipaddress=ip.instance

    #        .each do |member|
    #          [email protected][member]
    #          server_instance=vm.instance
    #          unless server_instance.nil?
    #            lb_instance=lb.instance
    #            unless lb_instance.nil?
    #              puts "[#{lb.name}] Registering #{vm.name} - #{server_instance.id} with loadbalancer "
    #              lb_instance.register_instances(server_instance.id)
    #            else
    #              puts "[#{lb.name} Loadbalancer does not (yet) exist"
    #            end
    #          else
    #            puts "[#{lb.name}] Member #{member} is not yet created. "
    #          end
    #        end
    #      end

  end
end

#loadbalance(selection, options) ⇒ Object



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
# File 'lib/mccloud/provider/aws/provider/old_loadbalance.rb', line 7

def loadbalance(selection, options)
  filter=@environment.config.mccloud.stackfilter

  puts
  on_selected_lbs(selection) do |id,lb|

    member_ids=Array.new
    lb_instance=lb.instance
    #Adding new member first
    lb.members.each do |member|
      vm=@environment.config.vms[member]
      server_instance=vm.instance
      unless server_instance.nil?
        unless lb_instance.nil?
          puts "[#{lb.name}] Registering #{vm.name} - #{server_instance.id} with loadbalancer "
          lb_instance.register_instances(server_instance.id)
          member_ids << server_instance.id
        else
          puts "[#{lb.name} Loadbalancer does not (yet) exist"
        end
      else
        puts "[#{lb.name}] Member #{member} is not yet created. "
      end
    end

    #Removing old members
    lb_instance.instances.each do |instance_id|
      unless member_ids.include?(instance_id)
        lb_instance=lb.instance
        lb_instance.deregister_instances(instance_id)
        puts "[#{lb.name}] De-registering member #{instance_id} with loadbalancer "

      end
    end
  end

end

#multi(selection = nil, command = "who am i", options = nil) ⇒ Object



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
# File 'lib/mccloud/provider/core/vm/old_multi.rb', line 7

def multi(selection=nil,command="who am i",options=nil)
  trap("INT") { puts "we hit CTRL_C"; exit }


  Net::SSH::Multi.start do |environment|
    # Connect to remote machines
    ip2name=Hash.new
    on_selected_machines(selection) do |id,vm|
      instance=vm.instance
      if instance.state == "running"
        ip2name[instance.public_ip_address]=vm.name
        environment.use "#{instance.public_ip_address}", { :user => vm.user , :keys => [ vm.private_key ], :paranoid => false, :keys_only => true}
      end
    end

    unless options["sudo"].nil?
      #check vm.sudo
      sudo_cmd="sudo"
      command="#{sudo_cmd} #{command}"
    end

    puts "Executing #{command}"
    begin
      environment.exec("#{command}") do |ch, stream, data|
        #exit code
        #http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/a806b0f5dae4e1e2

        ch.on_request("exit-status") do |ch, data|
          exit_code = data.read_long
          @status=exit_code
          if exit_code > 0
            puts "ERROR: exit code #{exit_code}"
          else
            puts "Successfully executed"
          end
        end
        if (ip2name.count > 1) || options.verbose?
          puts "[#{ip2name[ch[:host]]}] #{data}"
        else
          print "#{data}"              
        end
        # puts "[#{ch[:host]} : #{stream}] #{data}"

      end
    rescue Errno::ECONNREFUSED
      puts "oops - no connection"
    end
    # Tell Net::SSH to wait for output from the SSH server
    environment.loop  
  end

end

#package(selection = nil, options = nil) ⇒ Object



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
# File 'lib/mccloud/provider/aws/provider/old_package.rb', line 5

def package(selection=nil,options=nil)

  if selection.nil?
    puts "[Error] We need at least a name of a machine."
    exit
  end


  #f=Fog::Compute.new({ :region => "eu-west-1", :provider => "AWS"})
  # i=f.create_image("i-c1ac2bb7","name","description")
  # f.images.all({ "Owner" => "self"})
  # f.deregister_image("ami-796d5b0d")

  on_selected_machines(selection) do |id,vm|

    time=Time.new
    strtime=time.strftime("%Y-%m-%d-%H-%M-%S")
    name=""

    if options["name"].nil?
      name="#{vm.name}-#{strtime}"
    else
      name=options["name"]
    end

    description=""
    if options["description"].nil?
      description="Autogenerated snapshot from machine #{vm.name}"
    else
      description=options["description"]
    end

    filter=@environment.config.mccloud.filter
    fullname="#{@environment.config.mccloud.filter}#{name}"

    provider= @environment.config.providers[vm.provider]
    begin
      result=provider.create_image(id,name,description)
      imageId=result.body["imageId"]
      puts "[#{vm.name}] image #{imageId} with #{description} being created"

      unless options["dontwait"]
        sleep 3
        counter=0
        max_tries=5
        #Pending
        state="pending"
        until state!="pending" do
          print "."
          sleep 2
          image=provider.images.get(imageId)

          if image.nil?
            sleep 3
            print "."
          else
            state=image.state
          end
        end
        puts ""
        puts "[#{vm.name}] creation done!"
      end
    rescue Fog::Service::Error => fogerror
      puts "[Error] #{fogerror}"

    end
    #      vm.instance.start
  end
end

#reload(selection = nil?) ) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/mccloud/provider/core/vm/old_reload.rb', line 3

def reload(selection=nil?)
  load_config
  on_selected_machines(selection) do |id,vm|
    puts "rebooting #{id}"
    vm.instance.reboot
  end
end

#server(selection = nil, options = nil) ⇒ Object



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
# File 'lib/mccloud/provider/core/vm/old_server.rb', line 5

def server(selection=nil,options=nil)

  puts "Starting server mode"
  trap("INT") { puts "You've hit CTRL-C . Stopping server now"; exit }
  threads = []
  on_selected_machines(selection) do |id,vm|
    threads << Thread.new(id,vm) do |id,vm|
      public_ip_address=vm.instance.public_ip_address
      private_ip_address=vm.instance.private_ip_address
      unless public_ip_address.nil? || private_ip_address.nil?
        ssh_options={ :keys => [ vm.private_key ], :paranoid => false, :keys_only => true}
        Net::SSH.start(public_ip_address, vm.user, ssh_options) do |ssh|
          vm.forwardings.each do |forwarding|
            begin
              puts "Forwarding remote port #{forwarding.remote} from #{vm.name} to local port #{forwarding.local}"
              ssh.forward.local(forwarding.local, private_ip_address,forwarding.remote)
            rescue Errno::EACCES
              puts "  Error - Access denied to forward remote port #{forwarding.remote} from #{vm.name} to local port #{forwarding.local}"
            end
          end
          ssh.loop { true }
        end
      end
    end
  end
  threads.each {|thr| thr.join}
  #puts "and we continue here"
  #sleep 30
end

#sorry(selection, options) ⇒ Object



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
# File 'lib/mccloud/provider/aws/provider/old_sorry.rb', line 7

def sorry(selection, options)
  filter=@environment.config.mccloud.stackfilter

  puts
  on_selected_lbs(selection) do |id,lb|

    if lb.sorry_members.nil?
      puts "[#{lb.name}] has no sorry_members defined, skipping"
    else
      member_ids=Array.new
      lb_instance=lb.instance
      #Adding new member first
      lb.sorry_members.each do |member|
        vm=@environment.config.vms[member]
        server_instance=vm.instance
        unless server_instance.nil?
          unless lb_instance.nil?
            puts "[#{lb.name}] Registering #{vm.name} - #{server_instance.id} with loadbalancer "
            lb_instance.register_instances(server_instance.id)
            member_ids << server_instance.id
          else
            puts "[#{lb.name} Loadbalancer does not (yet) exist"
          end
        else
          puts "[#{lb.name}] Member #{member} is not yet created. "
        end
      end

      #Removing old members
      lb_instance.instances.each do |instance_id|
        unless member_ids.include?(instance_id)
          lb_instance=lb.instance
          lb_instance.deregister_instances(instance_id)
          puts "[#{lb.name}] De-registering member #{instance_id} with loadbalancer "

        end
      end
    end

  end

end

#suspendObject



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/mccloud/provider/core/vm/old_suspend.rb', line 3

def suspend
  load_config
  on_selected_machines(selection) do |id,vm|
    puts "Halting machine #{vm.name} with Id: #{id}"
    PROVIDER.servers.get(id).stop

    vm.instance.wait_for { printf ".";STDOUT.flush;  state=="stopped"}          
    puts

  end
end