Class: Inspec::Resources::Ibmdb2Session

Inherits:
Object
  • Object
show all
Defined in:
lib/inspec/resources/ibmdb2_session.rb

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Ibmdb2Session

Returns a new instance of Ibmdb2Session.



29
30
31
32
33
34
35
36
37
38
# File 'lib/inspec/resources/ibmdb2_session.rb', line 29

def initialize(opts = {})
  @db_name = opts[:db_name]
  if inspec.os.platform?("unix")
    @db2_executable_file_path = opts[:db2_executable_file_path]
    @db_instance = opts[:db_instance]
    raise Inspec::Exceptions::ResourceFailed, "Can't run IBM DB2 queries without db2_executable_file_path, db_instance, db_name options provided." if @db2_executable_file_path.nil? || @db_instance.nil? || @db_name.nil?
  elsif inspec.os.platform?("windows")
    raise Inspec::Exceptions::ResourceFailed, "Can't run IBM DB2 queries without db_name option provided." if @db_name.nil?
  end
end

Instance Method Details

#query(q) ⇒ Object



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
# File 'lib/inspec/resources/ibmdb2_session.rb', line 40

def query(q)
  raise Inspec::Exceptions::ResourceFailed, "#{resource_exception_message}" if resource_failed?

  if inspec.os.platform?("unix")
    # connect to the db and query on the database
    cmd = inspec.command("#{@db2_executable_file_path} attach to #{@db_instance}\; #{@db2_executable_file_path} connect to #{@db_name}\; #{@db2_executable_file_path} #{q}\;")
    out = cmd.stdout + "\n" + cmd.stderr

    # check if following specific error is there. Sourcing the db2profile to resolve the error.
    if cmd.exit_status != 0 && out =~ /SQL10007N Message "-1390" could not be retrieved.  Reason code: "3"/
      cmd = inspec.command(". ~/sqllib/db2profile\; #{@db2_executable_file_path} attach to #{@db_instance}\; #{@db2_executable_file_path} connect to #{@db_name}\; #{@db2_executable_file_path} \"#{q}\"\;")
      out = cmd.stdout + "\n" + cmd.stderr
    end
  elsif inspec.os.platform?("windows")
    # set-item command set the powershell to run the db2 commands.
    cmd = inspec.command("set-item -path env:DB2CLP -value \"**$$**\"\; db2 connect to #{@db_name}\; db2 \"#{q}\"\;")
    out = cmd.stdout + "\n" + cmd.stderr
  end

  if cmd.exit_status != 0 || out =~ /Can't connect to IBM Db2 / || out.downcase =~ /^error:.*/
    raise Inspec::Exceptions::ResourceFailed, "IBM Db2 connection error: #{out}"
  else
    Lines.new(cmd.stdout.strip, "IBM Db2 Query: #{q}", cmd.exit_status)
  end
end

#resource_idObject



66
67
68
69
70
71
72
# File 'lib/inspec/resources/ibmdb2_session.rb', line 66

def resource_id
  if inspec.os.platform?("windows")
    "ibmdb2_session:DatabaseName#{@db_name}"
  else
    "ibmdb2_session:DatabaseInstance:#{@db_instance}:DatabaseName#{@db_name}"
  end
end

#to_sObject



74
75
76
# File 'lib/inspec/resources/ibmdb2_session.rb', line 74

def to_s
  "IBM Db2 Session"
end