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
-
#display_result(cmd_result) ⇒ Object
Takes the command result from run command and build a pretty display.
-
#dos_path(source_path, drive_letter = "C") ⇒ Object
Returns the dos path from a standard path.
- #execute_command(*commands) ⇒ Object
-
#execute_shell(command, sensitive_data = nil) ⇒ Object
Executes a command via shell.
- #first_defined(first, second) ⇒ Object
-
#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).
-
#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.
-
#get_staging_dir(version, force = false) ⇒ Object
Checks/Creates a staging directory.
-
#path_safe(txt) ⇒ Object
Returns a version of the string safe for a filname or path.
-
#precision_timestamp ⇒ Object
Returns a timestamp to the thousanth of a second.
- #privatize(expression, sensitive_data = BrpmAuto.params.private_params.values) ⇒ Object
-
#read_shebang(os_platform, action_txt) ⇒ Object
Reads the Shebang in a shell script Supports deep format which can include wrapper information ==== Attributes.
- #replace_in_file(file_path, pattern, replacement) ⇒ Object
-
#required_option(options, key) ⇒ Object
Throws an error if an option is missing great for checking if properties exist.
-
#split_nsh_path(path) ⇒ Object
Splits the server and path from an nsh path returns same path if no server prepended ==== Attributes.
- #substitute_tokens(expression, params = nil) ⇒ Object
-
#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. - #windows? ⇒ Boolean
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
201 202 203 204 205 206 |
# File 'lib/utilities.rb', line 201 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
18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/utilities.rb', line 18 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_command(*commands) ⇒ Object
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/utilities.rb', line 81 def execute_command(*commands) Open3.popen3(*commands) do |stdin, stdout, stderr, thread| logs = {:out => "", :err => ""} if block_given? { :out => stdout, :err => stderr }.each do |key, stream| Thread.new do while line = stream.gets privatized_line = BrpmAuto.privatize(line) logs[key] += privatized_line yield privatized_line end end if block_given? end thread.join else logs[:out] = stdout.read logs[:err] = stderr.read end return logs[:out], logs[:err], thread.pid, thread.value end 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
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 79 |
# File 'lib/utilities.rb', line 40 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
313 314 315 316 317 318 319 |
# File 'lib/utilities.rb', line 313 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)
269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/utilities.rb', line 269 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
123 124 125 126 127 |
# File 'lib/utilities.rb', line 123 def get_option(, key, default_value = "") result = .has_key?(key) ? [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
251 252 253 254 255 256 257 258 259 260 261 |
# File 'lib/utilities.rb', line 251 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
264 265 266 |
# File 'lib/utilities.rb', line 264 def path_safe(txt) txt.gsub(" ", "_").gsub(/\,|\[|\]/,"") end |
#precision_timestamp ⇒ Object
Returns a timestamp to the thousanth of a second
Returns
string timestamp 20140921153010456
112 113 114 |
# File 'lib/utilities.rb', line 112 def Time.now.strftime("%Y%m%d%H%M%S%L") end |
#privatize(expression, sensitive_data = BrpmAuto.params.private_params.values) ⇒ Object
287 288 289 290 291 292 293 294 295 296 297 |
# File 'lib/utilities.rb', line 287 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 ”
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/utilities.rb', line 168 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 |
#replace_in_file(file_path, pattern, replacement) ⇒ Object
321 322 323 324 325 326 327 |
# File 'lib/utilities.rb', line 321 def replace_in_file(file_path, pattern, replacement) file_content = File.read(file_path) File.open(file_path, "w") do |file| file << file_content.gsub(pattern, replacement) end 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
136 137 138 139 140 |
# File 'lib/utilities.rb', line 136 def required_option(, key) result = get_option(, 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
151 152 153 154 155 156 |
# File 'lib/utilities.rb', line 151 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
299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/utilities.rb', line 299 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
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/utilities.rb', line 217 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
283 284 285 |
# File 'lib/utilities.rb', line 283 def windows? Windows end |