不起眼的小孩 2017-03-14
在部署了数据库镜像之后,我们需要监控参与镜像的主数据库和镜像数据库的状态,如果状态异常,发送告警邮件。那么这个脚本需要在主和镜像服务器上都运行。
目录视图sys.database_mirroring对SQL Server实例上的每个数据库都包含一行(包括系统数据库和未配置镜像的数据库),当然也包含所有镜像数据库的状态信息。我们可以查询该目录视图,对于每个异常状态的镜像数据库触发告警邮件。笔者的环境配置的是异步镜像,依赖于手动故障转移。
前提条件:
1. 配置好数据库邮件,有正确的Profile。
2. 有权限发送邮件的有效Login,需要是msdb数据库中DatabaseMailUserRole角色成员。
3. 一对用于监控的镜像数据库。
DECLARE
@state VARCHAR(30)
DECLARE
@DbMirrored INT
DECLARE
@DbId INT
DECLARE
@String VARCHAR(100)
DECLARE
@databases TABLE (DBid INT, mirroring_state_desc VARCHAR(30))
-- get status for mirrored databases
INSERT
@databases
SELECT
database_id, mirroring_state_desc
FROM
sys.database_mirroring
WHERE
mirroring_role_desc IN ('PRINCIPAL','MIRROR')
AND
mirroring_state_desc NOT IN ('SYNCHRONIZED','SYNCHRONIZING')
-- iterate through mirrored databases and send email alert
WHILE
EXISTS (SELECT TOP 1 DBid FROM @databases WHERE mirroring_state_desc IS NOT NULL)
BEGIN
SELECT TOP 1 @DbId = DBid, @State = mirroring_state_desc
FROM @databases
SET @string = 'Host: '+@@servername+'.'+CAST(DB_NAME(@DbId) AS VARCHAR)+ ' - DB Mirroring is '+@state +' - notify DBA'
EXEC msdb.dbo.sp_send_dbmail 'valid_mail_profile', '[email protected]', @body = @string, @subject = @string
DELETE FROM @databases WHERE DBid = @DbId
END
--also alert if there is no mirroring just in case there should be mirroring :)
SELECT
@DbMirrored = COUNT(*)
FROM
sys.database_mirroring
WHERE
mirroring_state IS NOT NULL
IF
@DbMirrored = 0
BEGIN
SET @string = 'Host: '+@@servername+' - No databases are mirrored on this server - notify DBA'
EXEC msdb.dbo.sp_send_dbmail 'valid_mail_profile', '[email protected]', @body = @string, @subject = @string
END
依赖于手动故障转移。将以上脚本放到主服务器和镜像服务器上的作业里,每5分钟执行一次。