Class: Itamae::Backend::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/itamae/backend.rb

Direct Known Subclasses

Docker, Local, Ssh

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Base

Returns a new instance of Base.



36
37
38
39
# File 'lib/itamae/backend.rb', line 36

def initialize(options)
  @options = options
  @backend = create_specinfra_backend
end

Instance Method Details

#finalizeObject



121
122
123
# File 'lib/itamae/backend.rb', line 121

def finalize
  # pass
end

#get_command(*args) ⇒ Object



105
106
107
# File 'lib/itamae/backend.rb', line 105

def get_command(*args)
  @backend.command.get(*args)
end

#host_inventoryObject



117
118
119
# File 'lib/itamae/backend.rb', line 117

def host_inventory
  @backend.host_inventory
end

#run_command(commands, options = {}) ⇒ Object



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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/itamae/backend.rb', line 41

def run_command(commands, options = {})
  options = {error: true}.merge(options)

  if commands.is_a?(Array)
    command = commands.map do |cmd|
      Shellwords.escape(cmd)
    end.join(' ')
  else
    command = commands
  end

  cwd = options[:cwd]
  if cwd
    command = "cd #{Shellwords.escape(cwd)} && #{command}"
  end

  user = options[:user]
  if user
    command = "sudo -u #{Shellwords.escape(user)} -- /bin/sh -c #{Shellwords.escape(command)}"
  end

  Logger.debug "Executing `#{command}`..."

  result = @backend.run_command(command)
  exit_status = result.exit_status

  Logger.formatter.with_indent do
    if exit_status == 0 || !options[:error]
      method = :debug
      message = "exited with #{exit_status}"
    else
      method = :error
      message = "Command `#{command}` failed. (exit status: #{exit_status})"
    end

    Logger.public_send(method, message)

    {"stdout" => result.stdout, "stderr" => result.stderr}.each_pair do |name, value|
      next unless value && value != ''

      if value.bytesize > 1024 * 1024
        Logger.public_send(method, "#{name} is suppressed because it's too large")
        next
      end

      value.each_line do |line|
        # remove control chars
        case line.encoding
        when Encoding::UTF_8
          line = line.tr("\u0000-\u001f\u007f\u2028",'')
        end

        Logger.public_send(method, "#{name} | #{line}")
      end
    end
  end

  if options[:error] && exit_status != 0
    raise CommandExecutionError
  end

  result
end

#send_directory(*args) ⇒ Object



113
114
115
# File 'lib/itamae/backend.rb', line 113

def send_directory(*args)
  @backend.send_directory(*args)
end

#send_file(*args) ⇒ Object



109
110
111
# File 'lib/itamae/backend.rb', line 109

def send_file(*args)
  @backend.send_file(*args)
end