Module: Utilities

Defined in:
lib/utilities.rb

Constant Summary collapse

EXIT_CODE_FAILURE =
'Exit_Code_Failure'
Windows =
(RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/)

Instance Method Summary collapse

Instance Method Details

#display_result(cmd_result) ⇒ Object

Takes the command result from run command and build a pretty display

Attributes

  • cmd_result - the command result hash

Returns

  • formatted text



175
176
177
178
179
180
# File 'lib/utilities.rb', line 175

def display_result(cmd_result)
  result = "Process: #{cmd_result["pid"]}\nSTDOUT:\n#{cmd_result["stdout"]}\n"
  result = "STDERR:\n #{cmd_result["stderr"]}\n#{result}" if cmd_result["stderr"].length > 2
  result += "#{EXIT_CODE_FAILURE} Command returned: #{cmd_result["status"]}" if cmd_result["status"] != 0
  result
end

#dos_path(source_path, drive_letter = "C") ⇒ Object

Returns the dos path from a standard path

Attributes

  • source_path - path in standard “/” format

  • drive_letter - base drive letter if not included in path (defaults to C)

Returns

  • dos compatible path



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/utilities.rb', line 17

def dos_path(source_path, drive_letter = "C")
  path = ""
  return source_path.gsub("/", "\\") if source_path.include?(":\\")
  path_array = source_path.split("/")
  if path_array[1].length == 1 # drive letter
    path = "#{path_array[1]}:\\"
    path += path_array[2..-1].join("\\")
  else
    path = "#{drive_letter}:\\"
    path += path_array[1..-1].join("\\")
  end
  path
end

#execute_shell(command, sensitive_data = nil) ⇒ Object

Executes a command via shell

Attributes

  • command - command to execute on command line

Returns

  • command_run hash => <results>, stderr => any errors, pid => process id, status => exit_code



39
40
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
# File 'lib/utilities.rb', line 39

def execute_shell(command, sensitive_data = nil)
  escaped_command = command.gsub("\\", "\\\\")

  loggable_command = BrpmAuto.privatize(escaped_command, sensitive_data)
  BrpmAuto.log "Executing '#{loggable_command}'..."

  cmd_result = {"stdout" => "","stderr" => "", "pid" => "", "status" => 1}

  output_dir = File.join(BrpmAuto.params.output_dir,"#{precision_timestamp}")
  errfile = "#{output_dir}_stderr.txt"
  complete_command = "#{escaped_command} 2>#{errfile}" unless Windows
  fil = File.open(errfile, "w+")
  fil.close

  begin
    cmd_result["stdout"] = `#{complete_command}`
    status = $?
    cmd_result["pid"] = status.pid
    cmd_result["status"] = status.to_i

    fil = File.open(errfile)
    stderr = fil.read
    fil.close

    if stderr.length > 2
      BrpmAuto.log "Command generated an error: #{stderr}"
      cmd_result["stderr"] = stderr
    end
  rescue Exception => e
    BrpmAuto.log "Command generated an error: #{e.message}"
    BrpmAuto.log "Back trace:\n#{e.backtrace}"

    cmd_result["status"] = -1
    cmd_result["stderr"] = "ERROR\n#{e.message}"
  end

  File.delete(errfile)

  cmd_result
end

#first_defined(first, second) ⇒ Object



287
288
289
290
291
292
293
# File 'lib/utilities.rb', line 287

def first_defined(first, second)
  if first and ! first.empty?
    return first
  else
    return second
  end
end

#get_keyword_items(script_content = nil) ⇒ Object

DEPRECATED - use substitute_tokens instead (token has the format rpmMY_TOKEN instead of $$MY_TOKEN to avid interference with shell variables)



243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/utilities.rb', line 243

def get_keyword_items(script_content = nil)
  result = {}
  content = script_content unless script_content.nil?
  content = File.open(BrpmAuto.all_params["SS_script_file"]).read if script_content.nil?
  KEYWORD_SWITCHES.each do |keyword|
    reg = /\$\$\{#{keyword}\=.*\}\$\$/
    items = content.scan(reg)
    items.each do |item|
      result[keyword] = item.gsub("$${#{keyword}=","").gsub("}$$","").chomp("\"").gsub(/^\"/,"")
    end
  end
  result
end

#get_option(options, key, default_value = "") ⇒ Object

Provides a simple failsafe for working with hash options returns “” if the option doesn’t exist or is blank

Attributes

  • options - the hash

  • key - key to find in options

  • default_value - if entered will be returned if the option doesn’t exist or is blank



97
98
99
100
101
# File 'lib/utilities.rb', line 97

def get_option(options, key, default_value = "")
  result = options.has_key?(key) ? options[key] : nil
  result = default_value if result.nil? || result == ""
  result
end

#get_staging_dir(version, force = false) ⇒ Object

Checks/Creates a staging directory

Attributes

  • force - forces creation of the path if it doesnt exist

Returns

staging path or ERROR_ if force is false and path does not exist



225
226
227
228
229
230
231
232
233
234
235
# File 'lib/utilities.rb', line 225

def get_staging_dir(version, force = false)
  staging_path = defined?(RPM_STAGING_PATH) ? RPM_STAGING_PATH : File.join(BrpmAuto.all_params["SS_automation_results_dir"],"staging")
  pattern = File.join(staging_path, "#{Time.now.year.to_s}", path_safe(get_param("SS_application")), path_safe(get_param("SS_component")), path_safe(version))
  if force
    FileUtils.mkdir_p(pattern)
  else
    return pattern if File.exist?(pattern) # Cannot stage the same files twice
    return "ERROR_#{pattern}"
  end
  pattern
end

#path_safe(txt) ⇒ Object

Returns a version of the string safe for a filname or path



238
239
240
# File 'lib/utilities.rb', line 238

def path_safe(txt)
  txt.gsub(" ", "_").gsub(/\,|\[|\]/,"")
end

#precision_timestampObject

Returns a timestamp to the thousanth of a second

Returns

string timestamp 20140921153010456



86
87
88
# File 'lib/utilities.rb', line 86

def precision_timestamp
  Time.now.strftime("%Y%m%d%H%M%S%L")
end

#privatize(expression, sensitive_data = BrpmAuto.params.private_params.values) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
# File 'lib/utilities.rb', line 261

def privatize(expression, sensitive_data = BrpmAuto.params.private_params.values)
  unless sensitive_data.nil? or sensitive_data.empty?
    sensitive_data = [sensitive_data] if sensitive_data.kind_of?(String)

    sensitive_data.each do |sensitive_string|
      expression = expression.gsub(sensitive_string, "********")
    end
  end

  expression
end

#read_shebang(os_platform, action_txt) ⇒ Object

Reads the Shebang in a shell script Supports deep format which can include wrapper information

Attributes

  • os_platform - windows or linux

  • action_txt - the body of the shell script (action)

Returns

shebang hash e.g. => “.bat”, “cmd” => “cmd /c”, “shebang” => “#![.bat]cmd /c ”



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/utilities.rb', line 142

def read_shebang(os_platform, action_txt)
  if os_platform.downcase =~ /win/
    result = {"ext" => ".bat", "cmd" => "cmd /c", "shebang" => ""}
  else
    result = {"ext" => ".sh", "cmd" => "/bin/bash ", "shebang" => ""}
  end
  if action_txt.include?("#![") # Custom shebang
    shebang = action_txt.scan(/\#\!.*/).first
    result["shebang"] = shebang
    items = shebang.scan(/\#\!\[.*\]/)
    if items.size > 0
      ext = items[0].gsub("#![","").gsub("]","")
      result["ext"] = ext if ext.start_with?(".")
      result["cmd"] = shebang.gsub(items[0],"").strip
    else
      result["cmd"] = shebang
    end
  elsif action_txt.include?("#!/") # Basic shebang
    result["shebang"] = "standard"
  else # no shebang
    result["shebang"] = "none"
  end
  result
end

#required_option(options, key) ⇒ Object

Throws an error if an option is missing

great for checking if properties exist

Attributes

  • options - the options hash

  • key - key to find

Raises:

  • (ArgumentError)


110
111
112
113
114
# File 'lib/utilities.rb', line 110

def required_option(options, key)
  result = get_option(options, key)
  raise ArgumentError, "Missing required option: #{key}" if result == ""
  result
end

#split_nsh_path(path) ⇒ Object

Splits the server and path from an nsh path returns same path if no server prepended

Attributes

  • path - nsh path

Returns

array [server, path] server is blank if not present



125
126
127
128
129
130
# File 'lib/utilities.rb', line 125

def split_nsh_path(path)
  result = ["",path]
  result[0] = path.split("/")[2] if path.start_with?("//")
  result[1] = "/#{path.split("/")[3..-1].join("/")}" if path.start_with?("//")
  result
end

#substitute_tokens(expression, params = nil) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/utilities.rb', line 273

def substitute_tokens(expression, params = nil)
  return expression if expression.nil? || !expression.kind_of?(String)

  searchable_params = params || @all_params

  found_token = expression.match('rpm{[^{}]*}')
  while ! found_token.nil? do
    raise "Property #{found_token[0][4..-2]} doesn't exist" if searchable_params[found_token[0][4..-2]].nil?
    expression = expression.sub(found_token[0],searchable_params[found_token[0][4..-2]])
    found_token = expression.match('rpm{[^{}]*}')
  end
  return expression
end

#verify_success_terms(results, success_terms, fail_now = false, quiet = false) ⇒ Object

Looks for terms in the results and builds an exit message returns status message with “Command_Failed if the status fails”

Attributes

  • results - the text to analyze for success

  • success_terms - the term or terms (use | or & for and and or with multiple terms)

  • fail_now - if set to true will throw an error if a term is not found

Returns

  • text - summary of success terms



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/utilities.rb', line 191

def verify_success_terms(results, success_terms, fail_now = false, quiet = false)
  results.split("\n").each{|line| exit_status = line if line.start_with?("EXIT_CODE:") }
  if success_terms != ""
    exit_status = []
    c_type = success_terms.include?("|") ? "or" : "and"
    success = [success_terms] if !success_terms.include?("|") || !success_terms.include?("&")
    success = success_terms.split("|") if success_terms.include?("|")
    success = success_terms.split("&") if success_terms.include?("&")
    success.each do |term|
      if results.include?(term)
        exit_status << "Success - found term: #{term}"
      else
        exit_status << "Command_Failed: term not found: #{term}"
      end
    end
    status = exit_status.join(", ")
    status.gsub!("Command_Failed:", "") if status.include?("Success") if c_type == "or"
  else
    status = "Success (because nothing was tested)"
  end
  log status unless quiet
  raise "ERROR: success term not found" if fail_now && status.include?("Command_Failed")
  status
end

#windows?Boolean

Returns:

  • (Boolean)


257
258
259
# File 'lib/utilities.rb', line 257

def windows?
  Windows
end