There are many online documents describing RAC Configuration requirements and this post is no way different. As I have started working on RAC, I am making a note for myself in case I need to refresh and hence is this posting.
#!/bin/ksh
# Set the Oracle environment variables (customize these as needed)
export ORACLE_HOME=/path/to/oracle_home
export ORACLE_SID=your_oracle_sid
export PATH=$ORACLE_HOME/bin:$PATH
# Define Oracle username and password (preferably use secure method for credentials)
USER="your_username"
PASSWORD="your_password"
# Run SQL commands via sqlplus
sqlplus -s $USER/$PASSWORD@$ORACLE_SID <<EOF
-- Grant EXECUTE permissions on the specified DBMS packages to PUBLIC
GRANT EXECUTE ON SYS.DBMS_RANDOM TO PUBLIC;
GRANT EXECUTE ON SYS.DBMS_UTILITY TO PUBLIC;
GRANT EXECUTE ON SYS.DBMS_JOB TO PUBLIC;
-- Exit SQL*Plus
EXIT;
EOF
echo "Grants executed successfully!"
function yes_no() {
# Initial prompt
read -p "$1 {y/n}? " ans
# Loop until user provides an answer
while [[ -z $ans ]]; do
echo "You have NOT provided an answer."
read -p "Please answer {y/n}: " ans
done
# Handle responses using case statement
case $ans in
y|Y|yes|Yes|YES)
echo "Alright, I am proceeding."
;;
n|N|no|No|NO)
echo "Roger that! Exiting..."
exit 1 # Exit the script or return if you want just the function to exit
;;
*)
echo "Invalid input. Quitting..."
exit 1
;;
esac
}
Creating an effective questionnaire for developers requires clarity, logical grouping of questions, and a visually appealing layout to ensure the information is easy to fill out and review. Below is a template that is structured, professional, and comprehensive. This template is designed to be used in a Microsoft Word or Excel document for easy distribution and filling out.
Database and Application Information Questionnaire[Project Name / Application Name]
Prepared by: [Your Name]
Date: [Date]
Version: [Version Number]
1. Data Volume and Growth
Question | Response | Comments |
---|---|---|
What is the yearly volume of data? | [Enter data size in MB/GB/TB] | |
What is the expected yearly growth rate of data? | [Enter percentage, e.g., 20%] | |
Please provide monthly projections for data volume growth. | (Table: Month |
2. Data Access Patterns
Question | Response | Comments |
---|---|---|
What is the daily access pattern (CRUD operations)? | ||
- Read Operations | [Enter daily count] | |
- Insert Operations | [Enter daily count] | |
- Update Operations | [Enter daily count] | |
- Delete Operations | [Enter daily count] | |
What is the peak concurrency factor (99th percentile) for CRUD operations? | Define peak for each operation type. | |
- Peak Read Concurrency | [Enter count] | |
- Peak Insert Concurrency | [Enter count] | |
- Peak Update Concurrency | [Enter count] | |
- Peak Delete Concurrency | [Enter count] | |
What is the workload type for this application? | [Real-time / Batch] |
3. Data Retention and Archiving
Question | Response | Comments |
---|---|---|
What is the data retention period for the application data? | [Enter number of years or specific period] | |
Will data be archived after the retention period? | [Yes / No] | |
- If Yes, how will data be archived? | [e.g., to external system, compressed, etc.] | |
What is the size of archived data per year? | [Enter GB/TB] |
4. Response Time and Performance
Question | Response | Comments |
---|---|---|
What is the expected average response time for database queries? | [Enter target time in seconds, e.g., 1 sec] | |
Are there any performance SLAs? | [Yes / No] | Define SLAs (e.g., query response time during peak load) |
5. Query and Data Access
Question | Response | Comments |
---|---|---|
How far back in time are queries expected to go? | [Enter time frame, e.g., last 3 months, 1 year] | |
Does this differ by query type (e.g., operational vs. reporting)? | [Yes / No] | Specify differences if applicable |
What is the expected data retrieval frequency for the last N months/years of data? | [e.g., last 3 months, frequently accessed] |
6. Data Migration and Integration
Question | Response | Comments |
---|---|---|
Are there plans to migrate data from an existing data store to this new database? | [Yes / No] | |
What is the total size of data to be migrated? | [Enter size in GB/TB] | |
Will data need to be synchronized during migration? | [Yes / No] | Specify type of synchronization (e.g., delta, real-time) |
7. Database Transactions and Load
Question | Response | Comments |
---|---|---|
What is the average number of read requests per day? | [Enter number] | |
- Average read requests per second | [Enter number] | |
What is the average number of write requests per day? | [Enter number] | |
- Average write requests per second | [Enter number] | |
What is the peak number of read requests per day? | [Enter peak load number] | |
- Peak read requests per second | [Enter number] | |
What is the peak number of write requests per day? | [Enter peak load number] | |
- Peak write requests per second | [Enter number] |
8. Current Technology and Architecture
Question | Response | Comments |
---|---|---|
What is the current data store technology and version? | [Enter DB type and version, e.g., MySQL 5.7] | |
What is the overall technology stack for the application? | [Enter DB platform, application framework, etc.] | |
How many application instances will connect to the Oracle database? | [Enter number of instances] |
9. Application Criticality and Availability
Question | Response | Comments |
---|---|---|
What is the impact on end users if the application is unavailable? | [Enter details] | |
Is this a Tier-1 application? | [Yes / No] | Define criticality and uptime requirements |
What is the expected uptime SLA for this application? | [Enter percentage, e.g., 99.9%] |
10. Security and Compliance
Question | Response | Comments |
---|---|---|
Please provide the data classification details (e.g., sensitive, confidential, public)? | [Enter classification] | |
Are there any encryption requirements for data at rest or in transit? | [Yes / No] | Specify requirements (e.g., TDE, SSL/TLS) |
Are there any non-English characters stored in the database? | [Yes / No] | E.g., multi-lingual or special characters |
11. Future Growth and Scalability
Question | Response | Comments |
---|---|---|
What is the anticipated growth in users or transactions in the next 1-3 years? | [Enter details] | |
What are the scalability plans for the application? | [Horizontal / Vertical scaling] | Specify plans for scaling |
Additional Considerations
Database Failover and High Availability:
Question | Response | Comments |
---|---|---|
Are there any high availability (HA) or disaster recovery (DR) requirements? | [Yes / No] | Specify requirements (e.g., Oracle RAC, Data Guard) |
Backup and Recovery Requirements:
Question | Response | Comments |
---|---|---|
What are the backup window and recovery objectives (e.g., RTO, RPO)? | [Enter details] |
Compliance and Auditing:
Question | Response | Comments |
---|---|---|
Are there any auditing requirements for compliance purposes? | [Yes / No] | Specify (e.g., user access logs, query auditing) |
Instructions for Completion:
- Please fill in all applicable fields.
- Provide additional comments if necessary.
- If any question is not relevant, mark it as “N/A.”
- For data-related questions, provide estimations or ranges where possible.
Format Options:
- Microsoft Word Template: This is a great option for clear, readable sections and allows for easy comments or attachments.
- Excel Template: If you prefer a more structured format with calculations or tabular data (like for volume projections), Excel might be better.
- Google Forms / Survey: If you want to collect responses digitally, a survey format could be an efficient option.
Let me know if you'd like to adjust the template, add anything specific, or if you need a more detailed explanation for any section!
Capacity planning questionnaire
1. Data Volume and Growth
What is the yearly volume of data?
- Provide the volume in terms of MB/GB/TB per year.
What is the expected yearly growth rate of data?
- Provide percentage growth (e.g., 20% per year).
Please provide this information in a tabular format for monthly projections.
2. Data Access Patterns
What is the daily access pattern (CRUD operations)?
- Provide the details in terms of:
- Read Operations
- Insert Operations
- Update Operations
- Delete Operations
- Please provide counts for each operation type on a daily basis.
- Provide the details in terms of:
What is the peak concurrency factor (99th percentile) for CRUD operations?
- Define the peak number of concurrent transactions for each operation (e.g., peak inserts, updates, reads, deletes).
What is the workload type for this application?
- Real-time or Batch processing?
3. Data Retention and Archiving
What is the data retention period for the application data?
- How long will the data be retained in the database (e.g., 1 year, 5 years, permanent)?
Will data be archived after the retention period?
- If so, how will data be archived (e.g., to an external system, compressed, etc.)?
What is the size of the archived data per year (in GB/TB)?
4. Response Time and Performance
What is the expected average response time for database queries?
- Provide the target response time for typical queries (e.g., 1 second, 2 seconds).
Are there any performance SLAs?
- For example, query response time under peak load or during business-critical hours.
5. Query and Data Access
How far back in time are queries expected to go?
- Most queries retrieve data for how many months, days, or years?
- Does this differ by type of query (e.g., operational vs. reporting queries)?
What is the expected data retrieval frequency for the last N months/years of data?
- E.g., queries frequently access data from the last 3 months, or 1 year.
6. Data Migration and Integration
Are there any plans to migrate data from an existing data store to this new Oracle database?
- If yes, please provide volumetric details for the data migration.
What is the total size of data to be migrated?
- Please provide data size details in GB or TB, including any associated metadata.
Will data need to be synchronized during the migration (e.g., delta migration, real-time synchronization)?
7. Database Transactions and Load
What is the average number of read requests per day?
- Also, provide the average read requests per second.
What is the average number of write requests per day?
- Also, provide the average write requests per second.
What is the peak number of read requests per day (peak load)?
- Also, provide the peak read requests per second during high usage times.
What is the peak number of write requests per day (peak load)?
- Also, provide the peak write requests per second during high usage times.
8. Current Technology and Architecture
What is the current data store technology and version?
- Provide details of the existing database (e.g., MySQL, MSSQL, etc.).
What is the overall technology stack for the application?
- Database platform, application framework, middleware, etc.
How many application instances will connect to the Oracle database?
- This includes web servers, app servers, batch processes, etc.
9. Application Criticality and Availability
What is the impact on end users if the application is unavailable?
- Does the application impact business operations, customer experience, etc.?
Is this a Tier-1 application?
- Define if the application is business-critical (e.g., 24/7 uptime requirement, high availability).
What is the expected uptime SLA for this application?
- E.g., 99.9%, 99.99% uptime.
10. Security and Compliance
Please provide the data classification details (e.g., sensitive, confidential, public).
- Does the application handle sensitive information (e.g., PII, PCI, HIPAA)?
Are there any encryption requirements for data at rest or in transit?
- For example, TDE (Transparent Data Encryption) or SSL/TLS encryption.
Are there any non-english characters stored in the database?
- E.g., multi-lingual data storage, special characters, or non-ASCII text.
11. Future Growth and Scalability
What is the anticipated growth in users or transactions in the next 1-3 years?
- What is the expected user base or transaction volume increase?
What are the scalability plans for the application?
- Will the application scale horizontally (e.g., adding more app servers, Oracle RAC) or vertically (e.g., larger instance size, more CPU/RAM)?
Additional Considerations
Database Failover and High Availability:
- Are there any high availability (HA) or disaster recovery (DR) requirements, such as Oracle RAC, Data Guard, or backup solutions?
Backup and Recovery Requirements:
- What are the backup window and recovery objectives (e.g., RTO, RPO)?
Compliance and Auditing:
- Are there any auditing requirements (e.g., user access logs, query auditing) for compliance purposes?
== App
1. Application Overview
- What is this application about?
- Description: Provide a brief overview of the application, its purpose, and the business function it supports.
- Expected Output Sample:
"This application is a customer relationship management (CRM) system for tracking interactions and sales data across multiple customer channels. It integrates with multiple external data sources, performs real-time analytics, and generates personalized reports for sales teams."
2. Transaction Types and Characteristics
- What type of transactions does the application handle?
- Description: Provide a detailed description of the types of transactions (e.g., financial, e-commerce, real-time data processing, batch processing) handled by the application.
- Expected Output Sample:
"The application processes transactions related to customer order placements, payment processing, inventory updates, and order shipment tracking. It also generates daily summary reports for management. Transactions are both real-time and batch-oriented, with some overnight data aggregation tasks."
3. Limiting Impact on EXADATA
- How will the application limit its impact on the EXADATA environment?
- Description: Provide the strategies in place to minimize resource consumption, such as optimizing queries, load balancing, or using features like Oracle Real Application Clusters (RAC), database partitioning, or other performance-enhancing technologies.
- Expected Output Sample:
"The application will implement connection pooling to reduce the number of direct connections to EXADATA, ensuring that the database handles fewer, more efficient connections. Additionally, SQL queries will be optimized for performance, with indexing on critical tables and partitioning of large datasets (e.g., sales data). We will also use Oracle RAC to distribute load evenly across multiple nodes."
4. Use of Connection Pooling
- Are you going to use connection pooling?
- Description: Specify if connection pooling will be implemented and how it will be managed (e.g., using an external connection pool, built-in Oracle connection pooling, etc.).
- Expected Output Sample:
"Yes, connection pooling will be implemented using Oracle's built-in connection pool (Universal Connection Pool - UCP) to ensure efficient management of database connections. This approach will reduce connection overhead and minimize resource contention on the EXADATA system. Additionally, we will configure pool sizes based on expected peak load times."
5. Determination of Capacity
- How did you determine the capacity requirements (CPU, RAM, and storage)?
- Description: Explain the process and methodology used to estimate the required resources for CPU, RAM, and storage. Were any load tests or benchmarks conducted? Were historical data or application profiling used?
- Expected Output Sample:
"The capacity requirements were determined based on the expected transaction volume and performance SLAs. We conducted load testing with the application’s expected user load and transaction rates to simulate peak loads. CPU and RAM requirements were derived based on historical performance data from the legacy system, while storage requirements were estimated based on expected data growth (e.g., 5GB/day). We also accounted for a 20% buffer for future growth and overhead."
6. CPU, RAM, and Storage Requirements Sources
- Where did the CPU, RAM, and storage requirements come from?
- Description: Provide a detailed explanation of where the specific requirements for CPU, RAM, and storage were sourced from (e.g., application profiling, performance monitoring, vendor recommendations, testing results).
- Expected Output Sample:
"CPU and RAM requirements were derived from performance benchmarks and simulations using test workloads based on historical data from the existing system. For storage, the calculation was based on an estimated data growth rate of 5GB/day, plus an additional 10TB for transactional logs and backups over the next three years. The storage requirements were validated by consulting with Oracle support for best practices and reviewing similar deployment scenarios."
7. Peak Resource Usage
- What are the expected peak CPU, RAM, and storage usage values?
- Description: Provide peak values for CPU, RAM, and storage, particularly during high usage periods (e.g., end of month, high traffic periods, heavy reporting times).
- Expected Output Sample:
"Peak CPU usage is expected to reach 80% during month-end reporting, with up to 16 cores utilized. RAM usage could peak at 256GB during heavy real-time analytics processing. Storage usage is projected to peak at 100TB due to high-frequency transactional data and backups."
8. Growth Projections and Resource Expansion
- What is the expected rate of growth for CPU, RAM, and storage over the next 1-3 years?
- Description: Provide estimates for resource growth over the next 1 to 3 years based on expected business expansion, transaction volume growth, or application enhancements.
- Expected Output Sample:
"We expect CPU usage to grow by 20% annually as the number of concurrent users increases. RAM usage is anticipated to grow by 15% per year, mainly due to the increasing complexity of queries and reporting workloads. Storage is projected to grow by 25% annually, driven by a combination of transaction data, backup growth, and new features added to the application."
9. Performance and Load Testing
- Have you conducted any performance/load testing to determine the infrastructure requirements?
- Description: Provide details on any testing done to validate the estimated capacity needs, including testing methodologies (e.g., load testing, stress testing) and results.
- Expected Output Sample:
"Yes, we conducted performance testing using load simulation tools to replicate the expected user load and transaction volumes. The tests were designed to stress the system with peak transaction rates and concurrent users. We also conducted stress testing to identify potential bottlenecks, which helped us size the CPU, RAM, and storage requirements appropriately."
10. Oracle Database Features and Impact on EXADATA
- Are you using any Oracle-specific features (e.g., Oracle RAC, Exadata storage optimizations, Oracle Data Guard, etc.) to optimize database performance?
- Description: Identify any Oracle features that are expected to impact the database infrastructure, particularly in terms of resource usage on EXADATA.
- Expected Output Sample:
"Yes, we are using Oracle Real Application Clusters (RAC) for high availability and load balancing, which will distribute the workload across multiple EXADATA nodes. We are also leveraging Exadata storage optimizations such as Hybrid Columnar Compression (HCC) to reduce the storage footprint and improve query performance. Additionally, we will implement Oracle Data Guard for disaster recovery."
11. Impact on EXADATA
- How will you mitigate the impact of the application on EXADATA's resources (CPU, memory, and storage)?
- Description: Provide details on how the application is designed to limit excessive resource consumption on EXADATA, such as through query optimization, load balancing, and using Exadata-specific features.
- Expected Output Sample:
"To mitigate impact, we will ensure that all queries are optimized, particularly complex joins and subqueries. Additionally, we will utilize partitioning to improve query performance on large tables. Connection pooling will limit the number of concurrent database connections, reducing memory overhead. We will also leverage Exadata's Flash Cache for faster access to frequently queried data, ensuring minimal impact on storage performance."
Summary of Output Samples
Question | Expected Output |
---|---|
What is this application about? | CRM system for sales and customer data tracking. |
What type of transactions? | Order placement, payment processing, inventory updates, report generation. |
How will you limit impact on EXADATA? | Connection pooling, SQL query optimization, use of Oracle RAC, data partitioning. |
Will you use connection pooling? | Yes, using Oracle's UCP to manage connections efficiently. |
How did you determine capacity? | Load testing, transaction volume simulation, historical data analysis. |
Where did the CPU, RAM, and storage come from? | Benchmarks, performance data from legacy system, storage growth rate estimates. |
Peak CPU usage? | 80% during month-end, using 16 cores. |
Growth projections? | CPU: 20% growth, RAM: 15%, Storage: 25% annually. |
Did you conduct load testing? | Yes, using simulation tools to stress-test with peak users and transaction rates. |
Oracle features impacting EXADATA? | RAC for load balancing, Exadata optimizations (HCC, Flash Cache). |
collect_files.sh
#!/bin/bash
# Define the output file
output_file="file_structure.txt"
# Clear the previous output (if any)
> "$output_file"
# Function to check if a file is a text file (not binary)
is_text_file() {
# Use the 'file' command to check file type
file_type=$(file --mime-type -b "$1")
if [[ "$file_type" == text/* ]]; then
return 0 # It's a text file
else
return 1 # It's a binary file
fi
}
# Function to resolve absolute path in a portable way
get_absolute_path() {
# If the system is macOS, resolve the absolute path manually
if [[ "$(uname)" == "Darwin" ]]; then
# Resolve path manually for macOS
dir_name=$(dirname "$1")
base_name=$(basename "$1")
full_path=$(cd "$dir_name" && pwd)/"$base_name"
echo "$full_path"
else
# For Linux or other systems, use realpath or readlink
realpath "$1" 2>/dev/null || readlink -f "$1"
fi
}
# Function to traverse directories and collect file info
collect_files() {
for file in "$1"/*; do
if [ -d "$file" ]; then
# It's a directory, recursively call the function
collect_files "$file"
elif [ -f "$file" ]; then
# It's a file, check if it's a text file
if is_text_file "$file"; then
# It's a text file, collect its details
file_name=$(basename "$file")
# Resolve absolute path in a portable way
file_path=$(get_absolute_path "$file")
file_content=$(cat "$file")
echo "File: $file_name" >> "$output_file"
echo "Path: $file_path" >> "$output_file"
echo "Content:" >> "$output_file"
echo "$file_content" >> "$output_file"
echo "----------------------" >> "$output_file"
else
echo "Skipping binary file: $file" >> "$output_file"
fi
fi
done
}
# Start from the current directory
collect_files "."
echo "File structure saved to $output_file."
Script 2: rebuild_files.sh
#!/bin/bash
# Define the input file (file structure)
input_file="file_structure.txt"
# Check if the input file exists
if [ ! -f "$input_file" ]; then
echo "Error: File structure file not found!"
exit 1
fi
# Function to rebuild the file structure
rebuild_files() {
while IFS= read -r line; do
if [[ "$line" =~ ^File:\ (.*) ]]; then
file_name="${BASH_REMATCH[1]}"
elif [[ "$line" =~ ^Path:\ (.*) ]]; then
file_path="${BASH_REMATCH[1]}"
elif [[ "$line" =~ ^Content:$ ]]; then
# Start reading file content
content=""
while IFS= read -r content_line && [[ ! "$content_line" =~ ^---------------------- ]]; do
content="$content$content_line"$'\n'
done
# Create directory if it doesn't exist
dir_name=$(dirname "$file_path")
mkdir -p "$dir_name"
# Create the file and write content
echo -n "$content" > "$file_path"
echo "Recreated file: $file_path"
fi
done < "$input_file"
}
# Rebuild files and directories
rebuild_files
echo "File structure rebuilt from $input_file."
===
Below are the steps to create a test schema with tables, and a script to insert unique rows into the table every minute.
Step 1: Create a Test Schema and Tables
First, connect to your Oracle database using SQL*Plus or any other database client and execute the following SQL commands to create a schema and tables:
Step 2: Create a Script to Insert Unique Rows
Next, create a shell script that will insert unique rows into the tables every minute. Save the following script as insert_rows.sh
:
Step 3: Make the Script Executable
Make the script executable by running the following command:
Step 4: Run the Script in Background
You can run the script in the background using nohup
so that it continues to run even after you log out:
Step 5: Verify the Inserts
You can verify that the rows are being inserted by querying the tables:
This setup will ensure that unique rows are inserted into the tables every minute. Adjust the script and SQL commands as needed for your specific environment and requirements.
Two servers have been identified for configuring replication. The necessary binaries have been set up, and Oracle GoldenGate is configured and installed. Local storage with sufficient capacity for testing purposes has been identified and should be used.
Before setting up the extract and replicate processes, create a test schema in both Database 1 and Database 2, and include a few tables in each schema.
Once the replication setup is complete, verify that any data inserted into the tables in Database 1 is successfully replicated to the corresponding schemas in Database 2.
select round (used.bytes /1024/1024, 2) used_mb ,
round (free.bytes / 1024/1024 , 2) free_mb ,
round (tot.bytes / 1024/1024 ,2) total_mb
from (select sum (bytes) bytes from v$sgastat
where name != 'free memory') used
, (select sum (bytes) bytes from v$sgastat where name = 'free memory') free
, (select sum (bytes) bytes from v$sgastat) tot ;
#duplicate services#
Testing
Sure, let's break down the SQL queries in the provided PL/SQL code into smaller parts for testing. We'll focus on the collectSGAStatsNoDelta
function and the collectCustomStats
function separately.
Breakdown for collectSGAStatsNoDelta
Test the
v$sgainfo
table selection:- This will help you verify that the
v$sgainfo
table contains the expected data and theWHERE
clause is filtering correctly.
- This will help you verify that the
Test the
v$pgastat
table selection:- This will help you verify that the
v$pgastat
table contains the expected data.
- This will help you verify that the
Test the
v$sgastat
table selection:- This will help you verify that the
v$sgastat
table contains the expected data and theWHERE
clause is filtering correctly.
- This will help you verify that the
Test the inner query combining
v$sgainfo
,v$pgastat
, andv$sgastat
:- This will help you verify that the combined query is working correctly.
Test the outer query that calculates additional statistics:
- This will help you verify that the calculations are correct.
Test the final
sga_stats
CTE:- This will help you verify that the
sga_stats
CTE is working correctly.
- This will help you verify that the
Breakdown for collectCustomStats
Test the
x$kghlu
table selection:- This will help you verify that the
x$kghlu
table contains the expected data.
- This will help you verify that the
Test the
v$dlm_misc
table selection:- This will help you verify that the
v$dlm_misc
table contains the expected data and theWHERE
clause is filtering correctly.
- This will help you verify that the
Test the
v$system_event
table selection:- This will help you verify that the
v$system_event
table contains the expected data and theWHERE
clause is filtering correctly.
- This will help you verify that the
Test the
custom_stats
CTE:- This will help you verify that the
custom_stats
CTE is working correctly.
- This will help you verify that the
By breaking down the queries into smaller parts, you can test each component individually to ensure that each part works correctly before combining them into the final query.
Endoftest
Certainly! Let's integrate the collectCustomStats
and collectSGAStatsNoDelta
functions into the shell script. The shell script will call these PL/SQL functions, collect the statistics, and take appropriate actions based on the collected data.
Step 1: Create the PL/SQL Functions
First, ensure that the collectCustomStats
and collectSGAStatsNoDelta
functions are created in your Oracle database. You can create them as follows:
Step 2: Create the Shell Script
Next, create a shell script that calls these PL/SQL functions, collects the statistics, and takes appropriate actions based on the collected data.
Step 3: Schedule the Shell Script Using Cron
To run the script at regular intervals, add a cron job. Edit the crontab file using crontab -e
and add an entry like this to run the script every 5 minutes:
Explanation
Oracle Environment Variables:
- Set the
ORACLE_HOME
andORACLE_SID
environment variables to point to your Oracle installation and database SID.
- Set the
Email Address:
- Define the email address to send alerts to.
Thresholds:
- Define the thresholds for shared pool flushes and ORA-04031 errors.
PL/SQL Function Call:
- The script calls the
collectCustomStats
function usingsqlplus
and captures the output in/tmp/custom_stats.txt
.
- The script calls the
Parse the Output:
- The script parses the output to extract the shared pool flush count and ORA-04031 error count.
Check Thresholds:
- The script checks if the statistics exceed the defined thresholds. If they do, it sends an alert email and takes necessary actions (e.g., flushing the shared pool).
Schedule with Cron:
- The script is scheduled to run every 5 minutes using a cron job.
This script will monitor the custom statistics collected by the collectCustomStats
function, check if the statistics exceed the defined thresholds, and take appropriate actions such as sending an alert email and flushing the shared pool to avoid ORA-04031 errors. You can customize the thresholds and actions as needed to suit your environment.
#!/bin/bash
==== GG CHECK
#!/bin/bash
3## raj
alter session disable parallel query;
spool $detaillog append
col module for a60
col username format a32
col profile format a30
col module format a30
col number_of_sessions format 999,999
set lines 200 feedback off
select /*+ noparallel */ username, profile, connection_limit, number_of_sessions, pct_soft
from (
select a.username, a.profile, least(b.value, c.limits) connection_limit, number_of_sessions,
round(100 * number_of_sessions / connection_limit) pct_soft
from (
select username, profile, count(*) number_of_sessions
from v$session
where username is not null
group by username, profile
) a,
(select to_number(value) value from v$parameter where name = 'processes') b,
(select username, profile, to_number(decode(limit, 'UNLIMITED', 65535, limit)) limits
from dba_users u, dba_profiles p
where limit != 'DEFAULT' and u.profile = p.profile and resource_name = 'SESSIONS_PER_USER' and account_status = 'OPEN'
order by username
) c
where a.username = c.username
) final
order by pct_soft desc;
spool off;
# Define environment variables
ORACLE_HOME=/path/to/oracle/home
ORACLE_SID=your_database_sid
export ORACLE_HOME ORACLE_SID PATH=$ORACLE_HOME/bin:$PATH
# Output log file
LOG_FILE="high_session_details_$(date +%Y%m%d_%H%M%S).log"
# SQL script to get session details
SQL_SCRIPT=$(cat <<EOF
SET ECHO OFF
SET FEEDBACK OFF
SET LINESIZE 200
SET PAGESIZE 100
COLUMN username FORMAT A20
COLUMN profile FORMAT A20
COLUMN status FORMAT A10
COLUMN program FORMAT A30
COLUMN machine FORMAT A30
COLUMN osuser FORMAT A20
COLUMN count FORMAT 999,999
-- Check session counts and high utilization
SPOOL $LOG_FILE
PROMPT High Session Utilization Summary:
SELECT username, COUNT(*) AS count
FROM v\$session
WHERE username IS NOT NULL
GROUP BY username
ORDER BY count DESC;
PROMPT
PROMPT High Resource Usage by Sessions:
SELECT s.username, s.osuser, s.machine, s.program, s.status, COUNT(*) AS count
FROM v\$session s
WHERE s.username IS NOT NULL
GROUP BY s.username, s.osuser, s.machine, s.program, s.status
ORDER BY count DESC;
PROMPT
PROMPT Session Limits and Profiles:
SELECT u.username, u.profile, p.resource_name, p.limit
FROM dba_users u, dba_profiles p
WHERE u.profile = p.profile
AND p.resource_name = 'SESSIONS_PER_USER'
ORDER BY u.username;
PROMPT
PROMPT Active Sessions:
SELECT s.sid, s.serial#, s.username, s.status, s.osuser, s.machine, s.program
FROM v\$session s
WHERE s.status = 'ACTIVE'
ORDER BY s.username;
SPOOL OFF
EOF
)
# Execute SQL script
echo "Connecting to Oracle and fetching high session details..."
sqlplus -s "/ as sysdba" <<EOF
$SQL_SCRIPT
EXIT;
EOF
# Output log location
echo "Session details logged to: $LOG_FILE"
# Check if the log file indicates high session usage and notify if needed
HIGH_SESSION_COUNT=$(grep -E "^[ ]*[0-9]+," $LOG_FILE | awk '{sum += $2} END {print sum}')
THRESHOLD=100 # Define a threshold for high sessions
if [[ $HIGH_SESSION_COUNT -gt $THRESHOLD ]]; then
echo "High session count detected: $HIGH_SESSION_COUNT sessions."
echo "Please review the log file: $LOG_FILE"
else
echo "Session count is within normal limits."
fi