Module: Grifork::Executable

Includes:
Loggable
Included in:
Grifork::Executor::Grifork, Grifork::Executor::Task
Defined in:
lib/grifork/mixin/executable.rb

Defined Under Namespace

Classes: CommandFailure, SSHCommandFailure

Instance Method Summary collapse

Methods included from Loggable

#logger

Instance Method Details

#rsync(from, to = nil) ⇒ Object



46
47
48
49
# File 'lib/grifork/mixin/executable.rb', line 46

def rsync(from, to = nil)
  to ||= from
  sh :rsync, [*rsync_opts, from, "#{dst}:#{to}"]
end

#rsync_optsObject



56
57
58
# File 'lib/grifork/mixin/executable.rb', line 56

def rsync_opts
  %w(-avzc --delete)
end

#rsync_remote(from, to = nil, user: nil) ⇒ Object



51
52
53
54
# File 'lib/grifork/mixin/executable.rb', line 51

def rsync_remote(from, to = nil, user: nil)
  to ||= from
  ssh src, :rsync, [*rsync_opts, from, "#{dst}:#{to}"], user: user
end

#sh(cmd, args = []) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/grifork/mixin/executable.rb', line 7

def sh(cmd, args = [])
  logger.info("#sh start - #{cmd} #{args}")
  stat = Open3.popen3(cmd.to_s, *args) do |stdin, stdout, stderr, wait_thr|
    stdin.close
    stdout.each { |l| logger.info("#sh [out] #{l.chomp}") }
    stderr.each { |l| logger.warn("#sh [err] #{l.chomp}") }
    wait_thr.value
  end

  unless stat.success?
    raise CommandFailure, "Failed to exec command! #{cmd} #{args}"
  end
end

#ssh(host, cmd, args = [], user: nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/grifork/mixin/executable.rb', line 21

def ssh(host, cmd, args = [], user: nil)
  command = "#{cmd} #{args.shelljoin}"
  logger.info("#ssh start - to: #{host}, command: #{cmd} #{args}")
  ssh_args = [host]
  ssh_args << user if user
  Net::SSH.start(*ssh_args) do |ssh|
    channel = ssh.open_channel do |ch|
      ch.exec(command) do |ch, success|
        unless success
          raise SSHCommandFailure, "Failed to exec ssh command! on: #{host} command: #{cmd} #{args}"
        end

        ch.on_data do |c, d|
          d.each_line { |l| logger.info("#ssh @#{host} [out] #{l.chomp}") }
        end
        ch.on_extended_data do |c, t, d|
          d.each_line { |l| logger.warn("#ssh @#{host} [err] #{l.chomp}") }
        end
        ch.on_close { logger.debug("#ssh @#{host} end.") }
      end
    end
    channel.wait
  end
end