Class: Kanmon::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/kanmon/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, port, ip = nil) ⇒ Server

Returns a new instance of Server.



11
12
13
14
15
16
17
18
# File 'lib/kanmon/server.rb', line 11

def initialize(id, port, ip = nil)
  @id = id
  @port = port || 22
  @ip = ip || Kanmon::MyIP.get
  @tenant_id = Yao.current_tenant_id
  @server = Yao::Server.get(id)
  @user_name = ENV['OS_USERNAME']
end

Instance Attribute Details

#ipObject (readonly)

Returns the value of attribute ip.



8
9
10
# File 'lib/kanmon/server.rb', line 8

def ip
  @ip
end

#user_nameObject

Returns the value of attribute user_name.



9
10
11
# File 'lib/kanmon/server.rb', line 9

def user_name
  @user_name
end

Instance Method Details

#add_sgObject



33
34
35
36
# File 'lib/kanmon/server.rb', line 33

def add_sg
  puts "Add security group  #{sg_name} to server #{@server.name}"
  Yao::Server.add_security_group(@id, sg_name)
end

#closeObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/kanmon/server.rb', line 66

def close
  begin
    results = Yao::SecurityGroup.find_by_name(sg_name)
    results.each do |result|
      @sg = result
      begin
        remove_sg
      rescue Yao::ItemNotFound
        puts "instance not found"
      end
      delete_sg
    end
  rescue => e
    p e
  end
end

#create_sgObject



20
21
22
23
24
25
26
# File 'lib/kanmon/server.rb', line 20

def create_sg
  puts "Create security group allow to access server '#{@server.name}'."
  param = {name: sg_name, description: "create by kanmon and #{ENV['OS_USERNAME']}"}
  @sg = Yao::SecurityGroup.create(param)
  result = Yao::SecurityGroupRule.create(rule)
  puts "Create rule to #{@sg.name} allow ssh from #{@ip}/32: #{result.id}"
end

#delete_sgObject



28
29
30
31
# File 'lib/kanmon/server.rb', line 28

def delete_sg
  puts "Delete security group #{sg_name}"
  Yao::SecurityGroup.destroy(@sg.id)
end

#openObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/kanmon/server.rb', line 51

def open
  validate_sg_already_exists
  create_sg
  add_sg

  if block_given?
    begin
      yield
    ensure
      remove_sg
      delete_sg
    end
  end
end

#remove_sgObject



46
47
48
49
# File 'lib/kanmon/server.rb', line 46

def remove_sg
  puts "Remove security group #{sg_name} from server '#{@server.name}'."
  Yao::Server.remove_security_group(@id, sg_name)
end

#validate_sg_already_existsObject



38
39
40
41
42
43
44
# File 'lib/kanmon/server.rb', line 38

def validate_sg_already_exists
  if Yao::SecurityGroup.list({name: sg_name}).size > 0
    puts "Security Group #{sg_name} already exists."
    puts "Is not it already opened?"
    raise Kanmon::AlreadySecurityExistsError
  end
end