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) ⇒ Command

Returns a new instance of Command.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/raykit/command.rb', line 35

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

  timeout = 0
  success_log_level = nil
  logging_enabled = false
  @@commands = []
  init_defaults
  @success_log_level = success_log_level
  @logging_enabled = logging_enabled
  @command = command
  @timeout = timeout
  #t = Time.now

  @elapsed = 0
  #run if @command.length.positive?

  self
end

Instance Attribute Details

#commandObject

Returns the value of attribute command.



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

def command
  @command
end

#directoryObject

The working directory, defaults the current directory if not specified



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

def directory
  @directory
end

#elapsedObject

The execution time in seconds



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

def elapsed
  @elapsed
end

#errorObject

Returns the value of attribute error.



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

def error
  @error
end

#exitstatusObject

Returns the value of attribute exitstatus.



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

def exitstatus
  @exitstatus
end

#logging_enabledObject

Returns the value of attribute logging_enabled.



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

def logging_enabled
  @logging_enabled
end

#machineObject

Returns the value of attribute machine.



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

def machine
  @machine
end

#outputObject

Returns the value of attribute output.



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

def output
  @output
end

#start_timeObject

The start time



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

def start_time
  @start_time
end

#success_log_levelObject

Returns the value of attribute success_log_level.



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

def success_log_level
  @success_log_level
end

#timeoutObject

The timeout in seconds, defaults to 0 if not specified



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

def timeout
  @timeout
end

#userObject

Returns the value of attribute user.



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

def user
  @user
end

Class Method Details

.get_script_commands(hash) ⇒ Object



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/raykit/command.rb', line 324

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



312
313
314
315
316
# File 'lib/raykit/command.rb', line 312

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

.parse_yaml_commands(yaml) ⇒ Object



318
319
320
321
322
# File 'lib/raykit/command.rb', line 318

def self.parse_yaml_commands(yaml)
  # commands=Array.new()

  data = YAML.safe_load(yaml)
  commands = get_script_commands(data)
end

Instance Method Details

#detailsObject



231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/raykit/command.rb', line 231

def details
  puts "  exit_code: " + @exitstatus.to_s
  if @output.length > 0
    @output.lines.each do |line|
      puts "  " + line
    end
  end
  if @error.length > 0
    @error.lines.each do |line|
      puts "  " + line
    end
  end
  self
end

#details_on_failureObject



224
225
226
227
228
229
# File 'lib/raykit/command.rb', line 224

def details_on_failure
  if @exitstatus != 0
    details
  end
  self
end

#elapsed_strObject



201
202
203
204
205
# File 'lib/raykit/command.rb', line 201

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

#from_hash(hash) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/raykit/command.rb', line 299

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



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

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

#logObject



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/raykit/command.rb', line 163

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.nil? && @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

#log_to_file(filename) ⇒ Object



274
275
276
277
278
279
280
281
# File 'lib/raykit/command.rb', line 274

def log_to_file(filename)
  File.delete(filename) if File.exist?(filename)
  File.open(filename, "w") { |f|
    f.puts output
    f.puts error
  }
  self
end

#runObject



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
104
105
106
107
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
# File 'lib/raykit/command.rb', line 57

def run
  # puts '---running---'

  @start_time = Time.now
  @elapsed = 0
  timer = Timer.new
  if @timeout.zero?
    @output, @error, process_status = Open3.capture3(@command)
    @exitstatus = process_status.exitstatus
  else
    # =================================================

    #puts "@timeout is #{@timeout}"

    Open3.popen3(@command, chdir: @directory) do |_stdin, stdout, stderr, thread|
      tick = 1
      pid = thread.pid
      start = Time.now
      while ((Time.now - start) < @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
          #puts "rescue block entered"

          @exitstatus = thread.value.exitstatus
          until stdout.eof?
            @output << stdout.read_nonblock(BUFFER_SIZE)
          end
          until stderr.eof?
            @error << stderr.read_nonblock(BUFFER_SIZE)
          end
          break
        end

        #begin

        #  @output << stdout.read_nonblock(BUFFER_SIZE)

        #  @error << stderr.read_nonblock(BUFFER_SIZE)

        #rescue IO::WaitReadable

        #rescue EOFError

        #  @exitstatus = thread.value.exitstatus

        #  until stdout.eof?

        #    @output << stdout.read_nonblock(BUFFER_SIZE)

        #  end

        #  until stderr.eof?

        #    @error << stderr.read_nonblock(BUFFER_SIZE)

        #  end

        #  break

        #end

      end
      sleep 1
      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
  self
end

#saveObject



256
257
258
259
260
261
262
263
264
265
# File 'lib/raykit/command.rb', line 256

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

#save_as(filename) ⇒ Object



267
268
269
270
271
272
# File 'lib/raykit/command.rb', line 267

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

#set_timeout(timeout) ⇒ Object



52
53
54
55
# File 'lib/raykit/command.rb', line 52

def set_timeout(timeout)
  @timeout = timeout
  self
end

#summary(show_directory = false) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/raykit/command.rb', line 207

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
  cmd = "#{Rainbow(SECRETS.hide(@command)).yellow}"
  if show_directory
    puts "#{symbol} #{cmd} " + Rainbow("#{elapsed_str}").cyan
    puts Rainbow("  #{@directory}").white + " "
  else
    puts "#{symbol} #{Rainbow(SECRETS.hide(@command)).yellow} " + Rainbow("#{elapsed_str}").cyan
    #puts "#{symbol} #{Rainbow(SECRETS.hide(@command)).yellow} (#{elapsed_str})"

  end
  self
end

#to_hashObject



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/raykit/command.rb', line 283

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



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/raykit/command.rb', line 141

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

#to_markdownObject



246
247
248
249
250
251
252
253
254
# File 'lib/raykit/command.rb', line 246

def to_markdown
  checkmark = "\u2713"
  error = "\u0058"
  symbol = checkmark.encode("utf-8")
  symbol = error.encode("utf-8") if @exitstatus != 0
  cmd = "#{SECRETS.hide(@command)}"
  md = "#{symbol} #{SECRETS.hide(@command)} (#{elapsed_str})"
  md
end