Module: PuppetX::EnterpriseModules::OraInstall::Facts

Includes:
GetHomes, WindowsCore
Defined in:
lib/puppet_x/enterprisemodules/ora_install/facts.rb

Instance Method Summary collapse

Methods included from WindowsCore

#execute_sql, #powershell_script, #sql_script

Methods included from GetHomes

#default_database_sid, #get_homes, #get_orainst_loc, #group_for_file, #installed_patches, #ora_invdir, #oracle_home_for, #oracle_homes, #oratab_content, #oratab_exists?, #oratab_file, #os, #user_for_file

Instance Method Details

#cleanup_opatch_residue(home) ⇒ Object



122
123
124
125
126
127
128
129
130
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 122

def cleanup_opatch_residue(home)
  # Some older versions of Opatch leave files and directories arround
  # When running opatch often, this causes some issues. This is to make
  # sure all files created by running Opatch as part of the fact, are remopved
  basename = Time.now.strftime('%Y-%m-%d_%H-%M-*%p')
  Puppet.debug `rm -rf /tmp/OraInstall*`
  Puppet.debug `rm -rf /tmp/opatch`
  FileUtils.rm_f("#{home}/cfgtoollogs/opatch/lsinv/lsinventory#{basename}.txt")
end

#first_non_root_file(dir) ⇒ Object



118
119
120
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 118

def first_non_root_file(dir)
  Dir.new(dir).each { |file| break file if File.stat("#{dir}/#{file}").uid.nonzero? }
end

#get_database_user(home) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 15

def get_database_user(home)
  database_user = Facter.value('override_database_user')
  return database_user unless database_user.nil?

  # puts "database user is oracle"
  if File.directory?("#{home}/bin")
    Facter::Util::Resolution.exec("/bin/stat --format=%U #{home}/bin/oracle")
  else
    'oracle'
  end
end

#get_defined_sids(home) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 132

def get_defined_sids(home)
  if os == 'windows'
    home_name = get_home_name(home)
    begin
      # When the home is an Oracle client home, the registry key will not exist. This will raise an error.
      regkey = Win32::Registry::HKEY_LOCAL_MACHINE.open("SOFTWARE\\Oracle\\KEY_#{home_name}")
      regkey.reject { |k, _v1, _v| k.scan(/ORA_(.*)_AUTOSTART/) == [] }.flatten.collect { |k| k.to_s.scan(/ORA_(.*)_AUTOSTART/) }.flatten.uniq
    rescue => e
      # We don't care about the error, we just return an empty array.
      Puppet.debug "Troubles getting defined sids for #{home}: #{e}. Some of the registry keys might be missing. Infering no defined sids"
      []
    end
  else
    quoted_home = Regexp.quote(home)
    oratab_content.scan(/^([+-_A-Za-z].*):#{quoted_home}:[YN].*$/).flatten.uniq
    []
  end
end

#get_home_name(home) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 72

def get_home_name(home)
  inventory_loc = get_orainst_loc
  return 'Invalid' unless File.exist?("#{inventory_loc}/ContentsXML/inventory.xml")

  file = File.read("#{inventory_loc}/ContentsXML/inventory.xml")
  doc = REXML::Document.new(file)
  doc.elements.each('/INVENTORY/HOME_LIST/HOME') do |element|
    return element.attributes['NAME'] if element.attributes['LOC'] == home
  end
end

#get_installed_patches(oracle_home) ⇒ Object



88
89
90
91
92
93
94
95
96
97
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 88

def get_installed_patches(oracle_home)
  if File.directory?(oracle_home)
    ora_user = user_for_file(oracle_home)
    installed_patches = patches_in_home(oracle_home, ora_user).flatten.sort
  else
    installed_patches = ['Invalid']
  end
  cleanup_opatch_residue(oracle_home) if Facter.value(:kernel) == 'Linux'
  installed_patches
end

#get_mode_role(sid, home) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 259

def get_mode_role(sid, home)
  if os == 'windows'
    service_state = `sc query OracleService#{sid}`.scan(/STATE *:.*(RUNNING)/).flatten.first
    if service_state == 'RUNNING'
      sql = %(select replace(open_mode, chr(32), chr(95)) as open_mode
                   , replace(database_role, chr(32), chr(95)) as database_role
                from v$database)
      execute_sql(sid, sql)
    else
      'Invalid Invalid'
    end
  else
    command     = %(sqlplus -S /nolog << EOF
      connect / as sysdba
      set heading off
      select replace(open_mode, chr(32), chr(95)) as open_mode
           , replace(database_role, chr(32), chr(95)) as database_role
        from v\\$database;
EOF)
    `su #{user_for_file(home)} -c 'export ORACLE_HOME="#{home}"; \
                                  export PATH="#{home}/bin:$PATH"; \
                                  export ORACLE_SID="#{sid}"; \
                                  unset TNS_ADMIN; \
                                  unset TWO_TASK; \
                                  export LD_LIBRARY_PATH="#{home}/lib"; \
                                  #{command}'`
  end
end

#get_opatch_version(home) ⇒ Object



37
38
39
40
41
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 37

def get_opatch_version(home)
  version = lsinventory(home).scan(/OPatch [V|v]ersion\s*:\s*(.*)/).flatten.first
  Puppet.debug "ora_install opatch version #{home}/OPatch/opatch: #{version}"
  version.nil? ? 'Invalid' : version
end

#get_product_version(oracle_home) ⇒ Object



288
289
290
291
292
293
294
295
296
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 288

def get_product_version(oracle_home)
  product_version = {
    'name' => get_home_name(oracle_home),
    'os_user' => user_for_file(oracle_home),
    'version' => get_version(oracle_home)
  }
  cleanup_opatch_residue(oracle_home) if Facter.value(:kernel) == 'Linux'
  product_version
end

#get_running_connmgrs(home) ⇒ Object



249
250
251
252
253
254
255
256
257
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 249

def get_running_connmgrs(home)
  command = %(ps -eo pid,cmd | grep "#{home}/bin/cmadmin" | grep -v grep | awk '{print $3}')
  raw_info = if os == 'windows'
               ''
             else
               Facter::Util::Resolution.exec(command)
             end
  raw_info.split("\n").compact
end

#get_running_listeners(home) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 205

def get_running_listeners(home)
  if os == 'windows'
    listener_services = `for /f "tokens=3" %i in ('tasklist /svc /fi "imagename eq tnslsnr.exe" ^| findstr "tnslsnr.exe"') do @echo %i`.split("\n")
    listeners = listener_services.map do |svc|
      svc_home_name, lsnr_name = svc.scan(/Oracle(.*)TNSListener(.*)/).flatten
      if svc_home_name == get_home_name(home)
        if lsnr_name.empty?
          'LISTENER'
        else
          lsnr_name
        end
      end
    end
    listeners.compact
  else
    command = %(ps -eo pid,cmd | grep "#{home}/bin/tns[l]snr" | grep -v cman | sed 's/-inherit//' | sed 's/-no_crs_notify//' | sed 's/-mode proxy//' |
                while read pid command listener; do
                    printf "%-9s %-80s\n" $listener  $(ls -l /proc/$pid/exe | awk '{ print $NF }' | sort | uniq)
                done)
    raw_info = Facter::Util::Resolution.exec(command)
    if $?.success?
      return [] if raw_info.empty?

      raw_info.split("\n").select { |e| e.include?(home) }.collect { |e| e.split.first }.sort
    else
      command = %(ps -eo pid,cmd | grep "#{home}/bin/tns[l]snr" | sed 's/-inherit//' | sed 's/-no_crs_notify//' |
                  while read pid command listener; do
                      printf "%-9s %-80s\n" $listener  $(ls -l /proc/$pid/exe | awk '{ print $NF }' | sort | uniq)
                  done)
      raw_info = Facter::Util::Resolution.exec(command)
      if $?.success?
        return [] if raw_info.empty?

        raw_info.split("\n").select { |e| e.include?(home) }.collect { |e| e.split.first }.sort
      else
        puts 'Fetching running listeners, needs access to /proc/pid/exe file system.'
        puts 'Probably using docker in non-privileged mode.'
        puts 'Run docker in privileged mode to fix the issue.'
        nil
      end
    end
  end
end

#get_running_processes(home) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 151

def get_running_processes(home)
  begin
    # When we run this fact on a (Windows) system that is NOT installed by our modules,
    # we might run into errors. We catch those and return an empty hash.
    {
      'sids' => get_running_sids(home),
      'listeners' => get_running_listeners(home),
      'conn_mgrs' => get_running_connmgrs(home)
    }
  rescue => e
    Puppet.debug "Troubles getting running processes for #{home}: #{e}. Infering no running processes"
    {}
  end
end

#get_running_sids(home) ⇒ Object



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
200
201
202
203
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 166

def get_running_sids(home)
  if os == 'windows'
    raw_array = []
    services = `for /f "tokens=3" %i in ('tasklist /svc /fi "imagename eq oracle.exe" ^| findstr "oracle.exe"') do @echo %i`
    services.split("\n").each do |service|
      db = service.gsub('OracleService', '')
      regkey = Win32::Registry::HKEY_LOCAL_MACHINE.open("SYSTEM\\CurrentControlSet\\Services\\#{service}")
      oracle_home = regkey['ImagePath'].gsub("\\bin\\ORACLE.EXE #{db}", '')
      raw_array << "#{db} ,#{oracle_home}"
    end
    raw_info = raw_array.join("\n")
  else
    command = %(ps aux | egrep "(ora|asm)_pmon" | awk '{gsub("(ora|asm)_pmon_", ""); print $2, $NF}' |
                 while read pid sid; do
                     printf "%-20s,%-80s\n" $sid  $(ls -l /proc/$pid/exe | awk '{ print $NF }' | sed 's/\\/bin\\/oracle$//' | sort | uniq)
                 done)
    raw_info = Facter::Util::Resolution.exec(command)
    unless $?.success?
      puts 'Fetching running SIDS, needs access to /proc/pid/exe file system.'
      puts 'Probably using docker in non-privileged mode.'
      puts 'Run docker in privileged mode to fix the issue.'
      nil
    end
  end
  return {} if raw_info.empty?

  databases = raw_info.split("\n").select { |e| e.downcase.include?(home.downcase) }.collect { |e| e.split(',').first.strip }.sort
  db_hash = databases.collect do |db|
    db_mode_role = db =~ /ASM/ ? ['n/a', 'n/a'] : get_mode_role(db, home).split
    {
      db => {
        'open_mode' => db_mode_role[0],
        'database_role' => db_mode_role[1]
      }
    }
  end
  Hash[*db_hash.collect { |h| h.to_a }.flatten]
end

#get_su_commandObject



27
28
29
30
31
32
33
34
35
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 27

def get_su_command
  if os == 'Linux'
    return 'su -l '
  elsif os == 'SunOS'
    return 'su - '
  end

  'su -l '
end

#get_version(home) ⇒ Object



83
84
85
86
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 83

def get_version(home)
  version = opatch_installed?(home) ? lsinventory(home).scan(/^(?:Oracle Database|Oracle Client|Oracle Grid Infrastructure|Oracle GoldenGate)\s.+?\s+(.*)$/).flatten.first : 'Invalid'
  version.nil? ? 'Invalid' : version
end

#jdk_clause(home) ⇒ Object



43
44
45
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 43

def jdk_clause(home)
  Dir.exist?("#{home}/jdk") ? "-jdk #{home}/jdk" : ''
end

#lsinventory(home) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 47

def lsinventory(home)
  @lsinventory ||= {}
  if os == 'windows'
    @lsinventory[home] ||= `#{home}\\OPatch\\opatch.bat lsinventory -jdk #{home}\\jdk`
  elsif supports_nolog?(home)
    @lsinventory[home] ||= Facter::Util::Resolution.exec("su #{user_for_file(home)} -c 'ORACLE_HOME=#{home} #{home}/OPatch/opatch lsinventory -jdk #{home}/jdk -customLogDir /tmp'")
    # We remove the created directory here, because it sometimes creates a dir with an other owner, which causes troubles for the next oracle home
    Puppet.debug `rm -rf /tmp/opatch`
    @lsinventory[home]
  elsif supports_nolog?(home)
    @lsinventory[home] ||= Facter::Util::Resolution.exec("su #{user_for_file(home)} -c 'ORACLE_HOME=#{home} #{home}/OPatch/opatch lsinventory #{jdk_clause(home)} -customLogDir /tmp'")
    # We remove the created directory here, because it sometimes creates a dir with an other owner, which causes troubles for the next oracle home
    Puppet.debug `rm -rf /tmp/opatch`
    @lsinventory[home]
  else
    @lsinventory[home] ||= Facter::Util::Resolution.exec("su #{user_for_file(home)} -c 'ORACLE_HOME=#{home} #{home}/OPatch/opatch lsinventory #{jdk_clause(home)}'")
  end
end

#opatch_installed?(oracle_home) ⇒ Boolean

Returns:

  • (Boolean)


110
111
112
113
114
115
116
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 110

def opatch_installed?(oracle_home)
  if os == 'windows'
    File.exist?("#{oracle_home}\\OPatch\\opatch.bat")
  else
    File.exist?("#{oracle_home}/OPatch/opatch")
  end
end

#patches_in_home(oracle_product_home_dir, _os_user) ⇒ Object



99
100
101
102
103
104
105
106
107
108
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 99

def patches_in_home(oracle_product_home_dir, _os_user)
  if opatch_installed?(oracle_product_home_dir)
    lsinventory(oracle_product_home_dir).scan(/Patch\s.(\d+)\s.*:\sapplied on/).flatten
  else
    #
    # When Opatch is not installed, we don't report any patches
    #
    ['Invalid']
  end
end

#supports_nolog?(home) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
69
70
# File 'lib/puppet_x/enterprisemodules/ora_install/facts.rb', line 66

def supports_nolog?(home)
  @lsinventory_help ||= {}
  @lsinventory_help[home] ||= Facter::Util::Resolution.exec("su #{user_for_file(home)} -c 'ORACLE_HOME=#{home} #{home}/OPatch/opatch lsinventory #{jdk_clause(home)} -help'")
  @lsinventory_help[home] =~ /customLogDir/
end