Class: Homeseed::Connection

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/homeseed/connection.rb

Direct Known Subclasses

Homeshick

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

configure_logger_for, global_level=, #logger, logger_for

Constructor Details

#initialize(params = {}) ⇒ Connection

Returns a new instance of Connection.

Raises:



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/homeseed/connection.rb', line 6

def initialize(params={})
  raise ConnectionError, 'servers and/or user not specified' unless params[:servers] and params[:user]
  @servers = params[:servers].split(',')
  @user = params[:user]
  @commands = []
  @logger = params[:logger] || logger

  if params[:has_password]
    cli = HighLine.new
    @password = cli.ask("Enter password: ") { |q| q.echo = false }
  else
    @password = params[:password] || ''
  end

  push_commands(params)
end

Instance Attribute Details

#has_passwordObject (readonly)

Returns the value of attribute has_password.



4
5
6
# File 'lib/homeseed/connection.rb', line 4

def has_password
  @has_password
end

#serversObject (readonly)

Returns the value of attribute servers.



4
5
6
# File 'lib/homeseed/connection.rb', line 4

def servers
  @servers
end

#userObject (readonly)

Returns the value of attribute user.



4
5
6
# File 'lib/homeseed/connection.rb', line 4

def user
  @user
end

Instance Method Details

#config_file_path(file) ⇒ Object



38
39
40
# File 'lib/homeseed/connection.rb', line 38

def config_file_path(file)
  File.expand_path("../../../config/#{file}", __FILE__)
end

#exec(params = {}) ⇒ Object



85
86
87
88
89
90
91
# File 'lib/homeseed/connection.rb', line 85

def exec(params={})
  if @servers.include?('localhost')
    local_exec
  else
    ssh_exec
  end
end

#local_execObject



93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/homeseed/connection.rb', line 93

def local_exec
  commands = @commands.join('; ') + ';'
  @logger.info "localhost exec: #{commands}"

  Open3.popen2e('/bin/bash') do |stdin, stdout_err, wait_thr|
    @commands.each do |command|
      stdin.puts(command)
    end
    stdin.close
    while line = stdout_err.gets
      log_exec(line)
    end
  end
end

#log_exec(data) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/homeseed/connection.rb', line 145

def log_exec(data)
  data_lines = data.split(/[\r,\n]/)
  data_lines.each do |data_line|
    unless data_line == ''
      if data_line.match(/error|failed|fatal/i)
        @logger.error data_line
      else
        @logger.info data_line
      end
    end
  end
end

#process_hash(commands, current_key, obj) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/homeseed/connection.rb', line 68

def process_hash(commands, current_key, obj)
  if obj.is_a?(Hash)
    obj.each do |new_key, value|
      combined_key = [current_key, new_key].delete_if { |k| k == '' }.join(" ")
      process_hash(commands, combined_key, value)
    end
  elsif obj.is_a?(Array)
    obj.each do |value|
      combined_key = [current_key, value].delete_if { |k| k == '' }.join(" ")
      commands << combined_key
    end
  else
    combined_key = [current_key, obj].delete_if { |k| k == '' }.join(" ")
    commands << combined_key
  end
end

#push_bash_file(file) ⇒ Object



49
50
51
52
53
# File 'lib/homeseed/connection.rb', line 49

def push_bash_file(file)
  @file = file
  yml_commands = YAML.load_file(file)
  push_yml_commands(yml_commands)
end

#push_bash_files(files) ⇒ Object



42
43
44
45
46
47
# File 'lib/homeseed/connection.rb', line 42

def push_bash_files(files)
  @files = files
  @files.each do |file|
    push_bash_file(file)
  end
end

#push_commands(params = {}) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/homeseed/connection.rb', line 23

def push_commands(params={})
  if params[:command]
    @commands.push(*params[:command])
  elsif params[:files]
    push_bash_files(params[:files])
  elsif params[:file]
    push_bash_file(params[:file])
  elsif params[:url]
    push_url_commands(params[:url])
  elsif params[:upload_files]
    @remote_path = params[:remote_path] || '/tmp/'
    @upload_files = params[:upload_files].split(',')
  end
end

#push_url_commands(url) ⇒ Object

Raises:



55
56
57
58
59
60
# File 'lib/homeseed/connection.rb', line 55

def push_url_commands(url)
  response =  HTTParty.get(url)
  raise HTTPartyError unless response.code == 200
  yml_commands = YAML.load(response.body)
  push_yml_commands(yml_commands)
end

#push_yml_commands(yml_commands) ⇒ Object



62
63
64
65
66
# File 'lib/homeseed/connection.rb', line 62

def push_yml_commands(yml_commands)
  commands = []
  self.process_hash(commands, '', yml_commands)
  @commands.push(*commands)
end

#scp_uploadObject

Raises:



158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/homeseed/connection.rb', line 158

def scp_upload
  raise ConnectionError, 'cannot scp to localhost' if @servers.include?('localhost')
  @servers.each do |server|
    @upload_files.each do |upload_file|
      @logger.info "starting scp #{upload_file} #{@user}@#{server}:#{@remote_path}"
      begin
        Net::SCP.start(server, @user) { |scp| scp.upload!(upload_file, @remote_path) }
        @logger.info "finished scp #{upload_file} #{@user}@#{server}:#{@remote_path}"
      rescue => err
        @logger.error "scp FAILED #{err}"
      end
    end
  end
end

#ssh_execObject



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
# File 'lib/homeseed/connection.rb', line 108

def ssh_exec
  Hash[@servers.map do |server|
    commands = @commands.join('; ') + ';'
    @logger.info "ssh #{@user}@#{server} exec: #{commands}"

    exit_status = nil
    exit_signal = nil

    Net::SSH.start(server, @user, password: @password) do |ssh|
      ssh.open_channel do |channel|
        channel.exec("bash -l") do |ch,success|
          ch.send_data "#{commands}\n"

          ch.on_data do |c,data|
            log_exec(data)
          end

          ch.on_extended_data do |c,type,data|
            log_exec(data)
          end

          ch.on_request("exit-status") do |c,data|
            exit_status = data.read_long
          end

          ch.on_request("exit-signal") do |c,data|
            exit_signal = data.read_long
          end

          ch.send_data "exit\n"
        end
      end
    end
    [server, { exit_status: exit_status, exit_signal: exit_signal }]
  end]
end