#!/bin/bash
Copyright (c) 2024, 2028, Ziheng Zong.
Author Ziheng Zong.
E-mail 321727043@qq.com.
if [ "$DB_USER" = "" ]; then
DB_USER="/ as SYSDBA"
fi
if [ "$1" = "awr7" ]; then
sqlplus -s /NOLOG << ! | egrep -v "Session altered|Connected|rows selected"
connect $DB_USER
CREATE OR REPLACE DIRECTORY tmpdir AS '/tmp/';
DECLARE
back_days NUMBER := 7;
peak_id NUMBER;
my_dbid NUMBER;
today VARCHAR2(30);
awr_dir VARCHAR2(40) := 'TMPDIR';
awr_file UTL_FILE.FILE_TYPE;
awr_file_name VARCHAR2(60);
BEGIN
SELECT snap_id
INTO peak_id
FROM (SELECT snap_id, average, end_time
FROM dba_hist_sysmetric_summary
WHERE average = (SELECT MAX(average)
FROM dba_hist_sysmetric_summary
WHERE metric_name = 'Average Active Sessions'
AND end_time > SYSDATE - back_days))
WHERE ROWNUM = 1;
SELECT dbid INTO my_dbid FROM v\$database;
SELECT TO_CHAR(SYSDATE, 'YYYY_MON_DD_HH24_MI') INTO today FROM dual;
FOR instance_rec IN (SELECT instance_number, instance_name
FROM gv\$instance) LOOP
awr_file_name := 'awr_' || today || '_' || instance_rec.instance_name ||
'.html';
awr_file := UTL_FILE.FOPEN(awr_dir, awr_file_name, 'w');
FOR curr_awr IN (SELECT output
FROM TABLE(dbms_workload_repository.awr_report_html(my_dbid,
instance_rec.instance_number,
peak_id - 1,
peak_id,
0))) LOOP
UTL_FILE.PUT_LINE(awr_file, curr_awr.output);
END LOOP;
UTL_FILE.FCLOSE(awr_file);
END LOOP;
EXCEPTION
WHEN OTHERS THEN
IF UTL_FILE.IS_OPEN(awr_file) THEN
UTL_FILE.FCLOSE(awr_file);
END IF;
RAISE;
END;
/
!
echo "Generate AWR reports save path is /tmp !";
exit 0
fi