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



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/raykit/command.rb', line 265

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



253
254
255
256
257
# File 'lib/raykit/command.rb', line 253

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

.parse_yaml_commands(yaml) ⇒ Object



259
260
261
262
263
# File 'lib/raykit/command.rb', line 259

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

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

Instance Method Details

#detailsObject



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/raykit/command.rb', line 196

def details
  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
  # summary

  #puts @output

  #puts @error

  #puts

end

#elapsed_strObject



176
177
178
179
180
# File 'lib/raykit/command.rb', line 176

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

#from_hash(hash) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/raykit/command.rb', line 240

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



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
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/raykit/command.rb', line 138

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

#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
# 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
          @exitstatus = thread.value.exitstatus
          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



213
214
215
216
217
218
219
220
221
222
# File 'lib/raykit/command.rb', line 213

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

#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 = true) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/raykit/command.rb', line 182

def summary(show_directory = true)
  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} #{Rainbow(SECRETS.hide(@command)).yellow} (#{@directory},#{elapsed_str})"
  else
    puts "#{symbol} #{Rainbow(SECRETS.hide(@command)).yellow} (#{elapsed_str})"
  end
  self
end

#to_hashObject



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/raykit/command.rb', line 224

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



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/raykit/command.rb', line 116

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