获取Oracle临时表空间的使用率

我们在日常Oracle维护中,可能某个SQL语句很慢,有大量的排序操作,这时需要确认下临时文件的使用情况,今天就讲如何直观的在前端显示该结果

注意:该功能自动查找临时表空间名称并计算使用率,无需输入temp表空间名称

开发环境

操作系统:CentOS 7.3

Python版本 :2.7

Django版本: 1.10.5

操作系统用户:oracle

建立页面的步骤

我们还是通过这张图的步骤来说明如何建立页面

Alt text

urls.py页面

首先是monitor/urls.py,这节不需要修改这个文件

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^oracle_command/$',views.oracle_command, name='oracle_command'),
    url(r'^commandresult/$',views.commandresult, name='commandresult'),
]

oracle_command为执行Oracle命令的页面

commandresult为执行完Oracle命令显示结果的页面

views.py

下面为commandresult对应的函数在views.py里面的写法

    elif command_content=='check_temp_usage':
        try:
            db = cx_Oracle.connect(username+'/'+password+'@'+ipaddress+':'+port+'/'+tnsname ,mode=cx_Oracle.SYSDBA)
        except Exception , e:
            content= (ipaddress+' is Unreachable,The reason is '+ str(e)).strip()
            return HttpResponse(content)
        else:
            cursor = db.cursor()
            row=gettempusage(cursor)
            cursor.close()
            db.close()
            title=ipaddress+'-'+tnsname+' 数据库临时表空间使用率为: '
            dic ={'title':title,'row':row}
            return render_to_response('oracle_command_result_1.html',dic)
  1. 首先获取到表单中的数据,如 ipaddress,tnsname以及执行的命令

  2. 然后通过ipaddress,tnsname从oraclelist数据库中查找获得用户名密码用于连接

  3. 再判断命令内容,如果是check_temp_usage

  4. 则执行函数gettempusage获取临时表空间的使用率,详情看具体代码

  5. 最后把页面的标题以及数据放到dic变量中传到 oracle_command_result_1.html模板文件中

gettempusage函数

这里的ggettempusage函数通临时表空间的使用率,详情看具体代码

monitor/command/getoraclecommandresult.py

def gettempusage(cursor):
    fp=open('/home/oracle/mysite/monitor/command/oracle_command/gettempusage.sql','r')
    fp1=fp.read()
    s=cursor.execute(fp1)
    fp.close()
    row=s.fetchone()
    return row[0]

gettempusage.sql

这个SQL是查询Oralce数据库的temp表空间使用率

select round ((s.tot_used_blocks/f.total_blocks)*100, 2) as "percent used"
  from ( select sum (used_blocks) tot_used_blocks
          from v$sort_segment
         where tablespace_name =
               ( select tablespace_name
                  from dba_tablespaces
                 where contents = 'TEMPORARY')) s,
       ( select sum (blocks) total_blocks
          from dba_temp_files
         where tablespace_name =
               ( select tablespace_name
                  from dba_tablespaces
                 where contents = 'TEMPORARY')) f

template文件

这里我们使用oracle_command_result_1.html文件来显示

oracle_command_result_1.html

<div id='newadd'>
<h3>{{title}}{{row}}</h3>
</div>

该模板就是一行文字,通过将传过来的变量显示在前端页面

实际效果

http://10.65.202.218:8081/monitor/oracle_command/

Alt text

源码地址

源码请查看我的GitHub主页

https://github.com/bsbforever/wechat_monitor

下期将介绍如何如何通过Django获取Oracle的硬解析状况