Class: Raykit::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/raykit/command.rb

Overview

Functionality to support executing and logging system commands

Constant Summary collapse

@@commands =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, timeout = 0, success_log_level = Logger::DEBUG, logging_enabled = true) ⇒ Command

Returns a new instance of Command.



36
37
38
39
40
41
42
43
44
45
# File 'lib/raykit/command.rb', line 36

def initialize(command, timeout = 0, success_log_level = Logger::DEBUG, logging_enabled = true)
  @@commands = []
  init_defaults
  @success_log_level = success_log_level
  @logging_enabled = logging_enabled
  @command = command
  @timeout = timeout
  run if @command.length.positive?
  self
end

Instance Attribute Details

#commandObject

Returns the value of attribute command.



23
24
25
# File 'lib/raykit/command.rb', line 23

def command
  @command
end

#directoryObject

The working directory, defaults the current directory if not specified



18
19
20
# File 'lib/raykit/command.rb', line 18

def directory
  @directory
end

#elapsedObject

The execution time in seconds



22
23
24
# File 'lib/raykit/command.rb', line 22

def elapsed
  @elapsed
end

#errorObject

Returns the value of attribute error.



23
24
25
# File 'lib/raykit/command.rb', line 23

def error
  @error
end

#exitstatusObject

Returns the value of attribute exitstatus.



23
24
25
# File 'lib/raykit/command.rb', line 23

def exitstatus
  @exitstatus
end

#logging_enabledObject

Returns the value of attribute logging_enabled.



23
24
25
# File 'lib/raykit/command.rb', line 23

def logging_enabled
  @logging_enabled
end

#machineObject

Returns the value of attribute machine.



23
24
25
# File 'lib/raykit/command.rb', line 23

def machine
  @machine
end

#outputObject

Returns the value of attribute output.



23
24
25
# File 'lib/raykit/command.rb', line 23

def output
  @output
end

#start_timeObject

The start time



20
21
22
# File 'lib/raykit/command.rb', line 20

def start_time
  @start_time
end

#success_log_levelObject

Returns the value of attribute success_log_level.



23
24
25
# File 'lib/raykit/command.rb', line 23

def success_log_level
  @success_log_level
end

#timeoutObject

The timeout in seconds, defaults to 0 if not specified



16
17
18
# File 'lib/raykit/command.rb', line 16

def timeout
  @timeout
end

#userObject

Returns the value of attribute user.



23
24
25
# File 'lib/raykit/command.rb', line 23

def user
  @user
end

Class Method Details

.get_script_commands(hash) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/raykit/command.rb', line 243

def self.get_script_commands(hash)
  commands = []
  if hash.key?('script')
    hash['script'].each do |cmd|
      commands << cmd
    end
  end
  hash.each do |_k, v|
    next unless v.is_a?(Hash)

    subcommands = get_script_commands(v)
    subcommands.each do |c|
      commands << c
    end
  end
  commands
end

.parse(json) ⇒ Object



231
232
233
234
235
# File 'lib/raykit/command.rb', line 231

def self.parse(json)
  cmd = Command.new('')
  cmd.from_hash(JSON.parse(json))
  cmd
end

.parse_yaml_commands(yaml) ⇒ Object



237
238
239
240
241
# File 'lib/raykit/command.rb', line 237

def self.parse_yaml_commands(yaml)
  # commands=Array.new()
  data = YAML.safe_load(yaml)
  commands = get_script_commands(data)
end

Instance Method Details

#detailsObject



184
185
186
187
188
189
# File 'lib/raykit/command.rb', line 184

def details
  # summary
  puts @output
  puts @error
  puts
end

#elapsed_strObject



164
165
166
167
168
# File 'lib/raykit/command.rb', line 164

def elapsed_str
  if elapsed < 1.0
  end
  "#{format('%.0f', elapsed)}s"
end

#from_hash(hash) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/raykit/command.rb', line 218

def from_hash(hash)
  @command = hash['command']
  @directory = hash['directory']
  @timeout = hash['timeout']
  @start_time = hash['start_time']
  @elapsed = hash['elapsed']
  @output = hash['output']
  @error = hash['error']
  @exitstatus = hash['exitstatus']
  @user = hash['user'] if hash.include?('user')
  @machine = hash['machine'] if hash.include?('machine')
end

#init_defaultsObject



25
26
27
28
29
30
31
32
33
34
# File 'lib/raykit/command.rb', line 25

def init_defaults
  @timeout = 0
  @directory = Dir.pwd
  @output = ''
  @error = ''
  @exitstatus = 0
  @user = Environment.user
  @machine = Environment.machine
  @logging_enabled = true
end

#logObject



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/raykit/command.rb', line 126

def log
  # --- Rolling File JSON -----
  log = Logger.new("#{Raykit::Environment.log_dir}/Raykit.Commands.txt", 'daily')
  log.formatter = proc do |_severity, _datetime, _progname, msg|
    "#{msg}\n"
  end
  secrets = Secrets.new
  msg = secrets.hide(@command) # "?"# self.summary(false)
  level = 'Verbose'
  level = 'Warning' if @exitstatus != 0
  event = Raykit::LogEvent.new(level, msg, {
                                 'Timeout' => @timeout,
                                 'Directory' => @directory,
                                 'Output' => @output,
                                 'Error' => @error,
                                 'ExitStatus' => @exitstatus,
                                 'Elapsed' => elapsed_str
                               })
  log.info event.to_json
  # ---------------------------
  begin
    json = JSON.generate(to_hash)
    log_filename = "#{Environment.get_dev_dir('log')}/Raykit.Command/#{SecureRandom.uuid}.json"
    log_dir = File.dirname(log_filename)
    FileUtils.mkdir_p(log_dir) unless Dir.exist?(log_dir)
    File.open(log_filename, 'w') { |f| f.write(json) }
    if @exitstatus.zero?
      LOG.log('Raykit.Command', Logger::Severity::INFO, json)
    else
      LOG.log('Raykit.Command', Logger::Severity::ERROR, json)
    end
  rescue JSON::GeneratorError => e
    puts to_hash.to_s
    puts e.to_s
    json = JSON.generate(to_hash)
  end
end

#runObject



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
# File 'lib/raykit/command.rb', line 47

def run
  # puts '---running---'
  @start_time = Time.now
  timer = Timer.new
  if @timeout.zero?
    @output, @error, process_status = Open3.capture3(@command)
    @exitstatus = process_status.exitstatus
  else
    Open3.popen3(@command, chdir: @directory) do |_stdin, stdout, stderr, thread|
      tick = 2
      pid = thread.pid
      start = Time.now
      elapsed = Time.now - start
      while ((elapsed) < @timeout) && thread.alive?
        Kernel.select([stdout, stderr], nil, nil, tick)
        begin
          @output << stdout.read_nonblock(BUFFER_SIZE)
          @error << stderr.read_nonblock(BUFFER_SIZE)
        rescue IO::WaitReadable
        rescue EOFError
          @exitstatus = thread.value.exitstatus
          break
        end
        elapsed = Time.now - start
      end
      if thread.alive?
        if Gem.win_platform?
          `taskkill /f /pid #{pid}`
        else
          Process.kill('TERM', pid)
        end
        @exitstatus = 5
        @error = 'timed out'
      else
        @exitstatus = thread.value.exitstatus
      end
    end
  end
  @elapsed = timer.elapsed
  if @logging_enabled
    log
    if @exitstatus != 0
      to_log_event.to_seq
    else
      # puts '---logging---'
      unless @success_log_level.nil?
        e = to_log_event
        e['Level'] = 'Verbose' if @success_log_level == 'Verbose'
        e['Level'] = 'Debug' if @success_log_level == Logger::DEBUG
        e['Level'] = 'Information' if @success_log_level == Logger::INFO
        e['Level'] = 'Warning' if @elapsed > 60 * 2
        e.to_seq
      end
    end
  end
end

#saveObject



191
192
193
194
195
196
197
198
199
200
# File 'lib/raykit/command.rb', line 191

def save
  filename = "#{Environment.get_dev_dir('log')}/Commands/#{SecureRandom.uuid}"
  log_dir = File.dirname(filename)
  FileUtils.mkdir_p(log_dir) unless Dir.exist?(log_dir)

  File.open(filename, 'w') do |f|
    f.write(JSON.pretty_generate(to_hash))
  end
  self
end

#summary(show_directory = false) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/raykit/command.rb', line 170

def summary(show_directory = false)
  checkmark = "\u2713"
  # warning="\u26A0"
  error = "\u0058"
  symbol = Rainbow(checkmark.encode('utf-8')).green
  symbol = Rainbow(error.encode('utf-8')).red if @exitstatus != 0
  if show_directory
    puts "#{symbol}  #{elapsed_str.rjust(4)} #{Rainbow(SECRETS.hide(@command)).yellow} (#{@directory})"
  else
    puts "#{symbol}  #{elapsed_str.rjust(4)} #{Rainbow(SECRETS.hide(@command)).yellow}" # + " (#{@directory})"
  end
  # puts symbol + "  " + elapsed_str.rjust(4) + " " + Rainbow(SECRETS.hide(@command)).yellow# + " (#{@directory})"
end

#to_hashObject



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/raykit/command.rb', line 202

def to_hash
  hash = {}
  hash[:command] = @command
  hash[:directory] = @directory
  hash[:timeout] = @timeout
  hash[:start_time] = @start_time
  hash[:elapsed] = @elapsed
  hash[:output] = @output.force_encoding('ISO-8859-1').encode('UTF-8')
  hash[:error] = @error.force_encoding('ISO-8859-1').encode('UTF-8')
  hash[:exitstatus] = @exitstatus
  hash[:user] = @user
  hash[:machine] = @machine
  hash[:context] = 'Raykit.Command'
  hash
end

#to_log_eventObject



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/raykit/command.rb', line 104

def to_log_event
  secrets = Secrets.new
  msg = secrets.hide(@command)
  level = 'Verbose'
  level = 'Warning' if @exitstatus != 0
  output = @output
  error = @error
  output = @output[-1000..-1] if @output.length > 1200
  error = @error[-1000..-1] if @error.length > 1200
  Raykit::LogEvent.new(level, msg, {
                         'SourceContext' => 'Raykit::Command',
                         'Category' => 'Command',
                         'Timeout' => @timeout,
                         'Directory' => @directory,
                         'Output' => output,
                         'Error' => error,
                         'ExitStatus' => @exitstatus,
                         'Elapsed' => elapsed_str,
                         'ElapsedSeconds' => @elapsed
                       })
end