1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu SQL Server MVP Deep Dives- P11 pdf

40 439 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Automating SQL Server Management Using SMO
Trường học University of Information Technology
Chuyên ngành Database Management
Thể loại Guide
Năm xuất bản 2023
Thành phố Hanoi
Định dạng
Số trang 40
Dung lượng 888,38 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Server audit objects You can define the properties of an audit, such as Queue Delay or Action on AuditFailure, as well as the output target, such as File, Windows Application Log, orWind

Trang 1

code can then be executed every time your backupstrategy calls for a full database backup of all data-bases on the target server If you remove the fulldatabase backup logic from the code sample thecode can be run every time transaction log backupsare to be run for all databases on the server, improv-ing your recovery interval to minimize the potentialdata loss in the event of a system failure.

In the following script, shown in listing 2, we’llconnect to our target server, and then get thedefault backup directory from the Settings collec-tion We’ll next grab the database collection anditerate through that to do the backups For eachdatabase we’ll get the current date and time and put

it into a string to use in the backup filename We’ll

do the full backup for the database, then we’llcheck to see if the database recovery model is Sim-ple If not, we’ll perform a transaction log backup

on the database as well

#backup.ps1

#Performs a Full backup followed by a transaction log backup on all user

➥databases param ( [string]$srvname='MyServer\MyInstance' )

# Load SMO assembly, and if we're running SQL 2008 DLLs load the

➥SMOExtended and SQLWMIManagement libraries

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer ➥SQLWMIManagement') | out-null

}

$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $srvname

$bkdir = $s.Settings.BackupDirectory

$dbs = $s.Databases foreach ($db in $dbs) {

if ($db.IsSystemObject -eq $False -and $db.IsMirroringEnabled -eq $False)

➥{

Listing 2 Backing up user databases

SqlBackup AddDevice

Trang 2

Restore

$dbname = $db.Name $dt = get-date -format yyyyMMddHHmmss $bk = new-object ('Microsoft.SqlServer.Management.Smo.Backup') $bk.Action = 'Database'

$bk.BackupSetDescription = "Full backup of " + $dbname $bk.BackupSetName = $dbname + " Backup"

$bk.Database = $dbname $bk.MediaDescription = "Disk"

$bk.Devices.AddDevice($bkdir + "\" + $dbname + "_db_" + $dt + ".bak",

➥'File') $bk.SqlBackup($s) # Simple Recovery Model has a Value Property of 3 # SQL Server 2008 doesn't recognize the enumerated value so the code is

➥slightly different # Set a variable to run the transaction log backup, and if Simple, turn

➥it off $trnbck = 1

if ($p2[0] -eq '9') {

if ($db.DatabaseOptions.RecoveryModel -eq 'Simple') { $trnbck =

➥0 } } else {

if ($db.RecoveryModel.value -eq 3) { $trnbck = 0 } }

if ($trnbck -eq 1) { $dt = get-date -format yyyyMMddHHmmss $trn = new-object ('Microsoft.SqlServer.Management.Smo.Backup') $trn.Action = 'Log'

$trn.BackupSetDescription = "Trans Log backup of " + $dbname $trn.BackupSetName = $dbname + " Backup"

$trn.Database = $dbname $trn.MediaDescription = "Disk"

$trn.Devices.AddDevice($bkdir + "\" + $dbname + "_tlog_" + $dt

➥+ ".trn", 'File') $trn.SqlBackup($s) }

} }

Restore

All the backups in the world don’t do a bit of good if they can’t be restored, and thereare scenarios that require restores to be done One is where a server or disk drive failsand the data needs to be recovered for business to continue This is the primary rea-son we perform regular backups For this case, the backup is restored (generally) tothe same location where the original database files existed

In addition to this there may be the case where data is inadvertently modified ordeleted, and some alternate recovery method is required, usually restoring the data-base backup to a new database name, so that the original data can be copied to theproduction database without disturbing other transactional activity occurring

Trang 3

Another use is for development and QualityAssurance (QA) testing, where a copy of theproduction database is restored in the develop-ment or QA environment to examine the effect

of some application update Finally, and this isoften overlooked, database backups should beregularly tested in disaster recovery testing, to

be certain that, should a problem occur, thebackups are in fact usable

A valuable piece of information is available

to us via SMO for the restore process that isn’tavailable through Management Studio orthrough straight T-SQL, and that is the location

of the default data and log file paths (figure 3)

We can use this in our restore scenario, usingthe following objects

When we have this information, we can setthe properties of the SMO Restore object(figure 4) We first connect to the server, then

we create a BackupDeviceItem, specifying thename and path of the backup file we’re going

to use, and add that to the Devices collection

of the Restore object We need to create at leasttwo RelocateFile objects (more if there aremore logical files in the backup file) and addthem to the RelocateFiles collection TheseRelocateFile objects will allow us to specifyboth the LogicalFileName and the Physical-FileName properties of the new database In thePhysicalFileName properties, we’ll use theMasterDBPath and MasterDBLogPath propertiesfrom the server information shown previously

Figure 4 shows the object hierarchy for theRestore object

As shown in listing 3, after we’ve set theproperties, we can invoke the SqlRestoremethod to perform the restore; then therestored database is available for use

MasterDBLogPath MasterDBPath Information

Figure 4 The SMO Restore object

Trang 4

Creating a database

[string]$srvname='MyServer\MyInstance', [string]$dbname='AdWorks',

[string]$bckfile='C:\MSSQL.2\MSSQL\Backup\AdventureWorks_db_20071227175

➥004.bak' )

# Load SMO assembly, and if we're running SQL 2008 DLLs load the

➥SMOExtended and SQLWMIManagement libraries

➥SMOExtended') | out-null [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer

➥SQLWMIManagement') | out-null }

$srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $srvname

$bdi = new-object ('Microsoft.SqlServer.Management.Smo.BackupDeviceItem')

SQL Server requires that a database have a PRIMARY filegroup and that the systemtables (the database metadata) reside in that filegroup (in fact their location cannot

be changed) Best practices recommendations include keeping your application dataout of the PRIMARY filegroup, to help in managing the disk files for the database.When using SSMS, it can be tedious to create a database with the desired size, file loca-tion, and with a separate, default, filegroup to hold the application data This is a rela-tively simple process with SMO

Trang 5

For the example database, we’llcreate a database called MyAppDB,which will have a 5 MB file in the PRI-MARY filegroup to hold the databasemetadata This file should nevergrow beyond 5 MB because it con-tains only database metadata We’lluse the logical name MyAppDB_

SysData for this file and house it inthe default data path for the server

The application data will belocated in a second filegroup calledAppFG, which we’ll set as the defaultfilegroup for the database We’ll cre-ate one file with a logical nameMyAppDB_AppData and house it inthe default data path for the server

as well We’ll set an initial size of 25

MB and allow it to grow by 25 MBeach time it is required, but set amaximum size of 100 MB

Log files in SQL Server do not usefilegroups, so we’ll add a log file tothe LogFiles collection of the data-base with a logical name MyAppDB_

Log and house it in the default logfile path for the server We’ll set itsinitial size to 10 MB and allow it togrow by 10 MB each time it needs to

do so, but we won’t set a maximumsize for the log file

After we’ve created the structuralobjects for the database, we executethe Create method, but SQL Serverautomatically sets the default file-group to PRIMARY when a database

is created, so we have to go back inand set the default filegroup to AppFG using the Alter method at both the filegroupand database levels

Figure 5 is a hierarchical diagram of the objects we’ll use to create the database Now let’s look at the example code in listing 4

Create

Alter

Alter

MaxSize Growth GrowthType FileName Name

MaxSize Growth GrowthType FileName Name IsDefault

Database

MasterDBLogPath MasterDBPath Information

LogFile LogFiles

DataFile Files

FileGroup FileGroups Databases

Server

Figure 5 The SMO Databases collection and

Database object

Trang 6

[int]$datsize=25, [int]$maxsize=100, [int]$logsize=10 )

# Load SMO assembly, and if we're running SQL 2008 DLLs load the

➥SMOExtended and SQLWMIManagement libraries

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer ➥SQLWMIManagement') | out-null

}

$srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $srvname

# Instantiate the database object and add the filegroups

# Create the file for the system tables

$dbdsysfile = new-object ('Microsoft.SqlServer.Management.Smo.DataFile')

# Create the file for the Application tables

$dbdappfile = new-object ('Microsoft.SqlServer.Management.Smo.DataFile')

Trang 7

$dbdappfile.Growth = [double]($datsize * 1024.0)

$dbdappfile.MaxSize = [double]($maxsize * 1024.0)

# Create the file for the log

$dblfile = new-object ('Microsoft.SqlServer.Management.Smo.LogFile') ($db,

Scripting

The scripting of SMO is a vast improvement over thescripting of its predecessor, DMO With SMO you can cre-ate T-SQL scripts from objects even if they don’t yet exist

When you open almost any maintenance dialog box inSQL Server Management Studio, you’ll see a button thatallows you to generate a script from the changes you’vemade in that dialog box You can then save that script forarchival purposes, cancel out of the dialog box, and exe-cute the script as written, or make changes to it beforeyou execute it

Another useful feature of scripting existing objects is

to generate scripts of all database objects for tion or source code control This allows the administra-tors to then rebuild a database in the form it existed atthe time the script was created

At any time while creating or working with objects inSMO, you can script those objects for archival or lateruse Figure 6 shows the Scripter object and the proper-ties we need to set

The Server property allows the Scripter object toconnect to the server The remaining properties thatneed to be set are in the Scripter Options collection

Trang 8

process will send the results to the console, so setting the ToFileOnly to True will

cause the scripter to send the script only to the file specified Setting Indexes to True will cause the clustered index for a table to be included in the script,and setting Indexes to True will cause the nonclustered indexes to be included in thescript The DriAll property, when set to True, will cause all objects with enforceddeclarative referential integrity to be included in the script

The objects to be scripted need to be added to an array of type SqlSmoObject Thisallows you to decide at what point you want the object included in the script After thearray has been populated with all the objects to be scripted you can invoke the Scriptmethod and the script will be created

Now let’s look at the example code in listing 5

#scripting.ps1

#Script all the table objects in the AdventureWorks database param (

[string]$srvname='MyServer\MyInstance', [string]$dbname='AdventureWorks', [string]$scrname='c:\dbscript.sql' )

# Load SMO assembly, and if we're running SQL 2008 DLLs load the

➥SMOExtended and SQLWMIManagement libraries

➥SMOExtended') | out-null [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer

➥SQLWMIManagement') | out-null }

$srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $srvname

$db = $srv.Databases[$dbname]

Listing 5 Scripting all objects in the AdventureWorks database

Trang 9

manage-About the author

Allen White is a SQL Server trainer and consultant who’s beenusing SQL Server since 1992 He has been awarded Microsoft’sMVP Award for his work in the SQL Server community for threeyears

Trang 10

SQL Server 2005 introduced event notifications and data definition language(DDL) triggers as mechanisms for auditing DDL statements, but coverage of eventswasn’t complete There was no support for auditing access to data, and there was

no tool support available in SQL Server Management Studio (SSMS)

Generating audit event s in SQL 2008 is extremely lightweight compared to viously available mechanisms, and is based on the new extended events infrastruc-ture, which is designed to have an extremely low overhead even for large numbers

pre-of events It also allows much finer-grained event filtering

NOTE All of the new audit features described in this chapter require SQLServer 2008 Enterprise or Developer Edition, and aren’t available inlower editions

Overview of audit infrastructure

In SQL Server 2008, all events are now auditable using the new audit objects,including those not available via event notifications in previous versions of SQLServer Configuration is greatly simplified with built-in tool support in SSMS.Figure 1 gives an overview of the various audit objects

Server audit objects

You can define the properties of an audit, such as Queue Delay or Action on AuditFailure, as well as the output target, such as File, Windows Application Log, orWindows Security Log You can create multiple server audits, each of whichdefines its own target

Trang 11

Server audit specification objects

You can define the audit action groups that you want to audit at the instance level,along with the server audit they belong to There can be a maximum of one serveraudit specification per server audit You can create multiple server audit specifica-tions, as long as each one uses a separate server audit

Database audit specification objects

You can define the individual audit actions or action groups that you want to audit atthe database level, including any filters and the server audit they belong to There can

be a maximum of one database audit specification per database per server audit Youcan create multiple database audit specifications for the same database, but they need

to belong to separate server audits

Server audits

The Server Audit object is the first object you create when enabling auditing for aninstance of SQL Server 2008 It defines the output target for audit events generated byaudit specifications You can choose from three possible audit output types for aServer Audit object:

ƒ Windows Application Event Log

ƒ Windows Security Event Log

ƒ File (local or remote)When you specify the Application or Security Log target, the settings listed in table 1are available for configuration

NOTE Writing events to the Windows Security Log isn’t allowed on Windows XP.Figure 1 Overview of audit object relationships

Trang 12

Server audits

Configuring the Windows Security Log target

In order to allow SQL Server to write events to the Windows Security Log, a number ofadditional configuration steps are required The following walkthrough demonstrateshow to enable the Windows Security Log target for Windows Server 2003 For details

of how to configure this target for Windows Server 2008, see the SQL Server mentation (http://msdn.microsoft.com/en-gb/library/cc645889.aspx)

Docu-1 Launch the Local Security Policy MMC snap-in by clicking Start > Run >secpol.msc

2 Select the Audit Policy folder under the Local Policies folder and double-clickAudit Object Access in the right pane

3 Check both the Success and Failure check boxes in the resultant dialog, asshown in figure 2

Table 1 Server Audit configuration settings for Application and Security Log targets

Setting Description

Queue Delay Amount of time in milliseconds that events are buffered before being forced

to be processed To enable synchronous event delivery, you’d set this to 0 Synchronous delivery may have a performance impact The default value is 1000.

Shutdown on Failure Whether the SQL instance will shut down if audit events can’t be written to

the target The default value is CONTINUE.

Audit GUID To support scenarios such as database mirroring, an audit needs a specific

GUID that matches the GUID found in the mirrored database The GUID can’t

be modified after the audit has been created.

Figure 2 Enabling Audit Object Access

Trang 13

4 Click OK to apply the changes.

5 In the same snap-in, select the User Rights Assignment folder under Local cies and double-click on Generate Security Audits in the right pane

Poli-6 Add the SQL Service account as shown in figure 3 and click OK

7 Restart the SQL Server service in order for the changes to take effect

NOTE The required options can be set by Group Policy in a domain ment, in which case local settings will be overwritten You should discussthese settings with the team that manages Group Policy to ensure therequired settings remain in effect for SQL Servers where you need to beable to write events to the Security Log

environ-Creating a server audit using the Windows Security Log target

To create a server audit, you can either use SSMS or T-SQL The following example onstrates how to create a server audit that uses the Windows Security Log using SSMS:Figure 3 Enabling Generate Security Audit for SQL Service account

Trang 14

Figure 4 Creating a new audit using SSMS

Figure 5 Setting server audit properties using SSMS

Trang 15

3 Note that the server audit has been created in a disabled state, as indicatedgraphically by the small downward-pointing red arrow on the server audit icon.

In order to use this server audit, it must first be enabled To enable the serveraudit, right-click on it and select Enable Audit from the context menu, as shown

in figure 6

The code in listing 1 is the equivalent of what we’ve just done via SSMS, but using T-SQL

CREATE SERVER AUDIT [SecurityLog]

TO SECURITY_LOG WITH

( QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE )

GO ALTER SERVER AUDIT [SecurityLog]

WITH(STATE=ON) GO

NOTE Windows Security Log is the most secure destination for auditing eventsfrom system administrator activity It can also be used to integrate withthe ACS (Audit Collection Service) functionality in SCOM 2007 (SystemCenter Operations Manager)

Creating a security audit using the Windows Application Log target

To create a server audit using the Windows Application Log target, use the codeshown in listing 2 As with the previous example, the server audit can be created usingSSMS or T-SQL The same options are available as for the Security Log target described

in table 1 The server audit will be created in a disabled state and must be enabledbefore a server or database audit specification can write audit events to it

Listing 1 Creating a server audit using the Security Log target

Figure 6 Enabling a server audit using SSMS

Trang 16

Server audits

CREATE SERVER AUDIT [ApplicationLog]

TO APPLICATION_LOG WITH

( QUEUE_DELAY = 2000, ON_FAILURE = CONTINUE )

GO ALTER SERVER AUDIT [ApplicationLog]

WITH(STATE=ON) GO

Configuring a server audit using the File target

When you specify the File target, the settings in table 2 are available for configuration

The code in listing 3 demonstrates creating a server audit that uses the File target Inthis example, the audit folder is C:\Audit\Server, the maximum size on any individualfile is 100 MB, the number of rollover files is unlimited, and we aren’t preallocatingdisk space for the audit files The queue delay is set to 2 seconds; therefore, this is anasynchronous audit and it won’t cause the instance to shut down if audit events can’t

be written to the target

CREATE SERVER AUDIT [ServerAuditFile]

TO FILE ( FILEPATH = N'C:\Audit\Server\'

Listing 2 Creating a server audit using the Application Log target

Table 2 Server audit configuration settings for File targets

Setting Description

Queue Delay Amount of time in milliseconds that events are buffered before being forced to be

processed To enable synchronous event delivery, you’d set this to 0 nous delivery may have a performance impact The default value is 1000 Shutdown on Failure Whether the SQL instance will shut down if audit events can’t be written to the

Synchro-target The default value is CONTINUE.

Audit GUID To support scenarios such as database mirroring, an audit needs a specific GUID

that matches the GUID found in the mirrored database The GUID can’t be fied after the audit has been created.

modi-Filepath The folder used to store the audit files The filenames are automatically

gener-ated based on the audit name and GUID.

Maxsize The maximum size of an audit file The default value is UNLIMITED.

Max Rollover Files The maximum number of rollover audit files The default value is 0 (unlimited) Reserve Disk Space Whether to preallocate disk space to the Maxsize value The default value is OFF.

Listing 3 Creating a server audit using the File target

Trang 17

,MAXSIZE = 100 MB ,MAX_ROLLOVER_FILES = 0 ,RESERVE_DISK_SPACE = OFF )

WITH ( QUEUE_DELAY = 2000 ,ON_FAILURE = CONTINUE )

GO ALTER SERVER AUDIT [ServerAuditFile]

WITH(STATE=ON) GO

Server audit specifications

Server audit specifications define the audit action groups that you want to audit at theinstance level, along with the server audit they belong to There can be a maximum ofone server audit specification per server audit You can create multiple server auditspecifications as long as each one uses a separate server audit

At the instance level, you can specify one or more audit action groups (for base audit specifications, you can specify individual audit actions and filters as well).Note that actions that modify the audit itself (such as disabling or altering auditobjects) are automatically audited A large number of audit action groups are avail-able; to find details on all of them, check Books Online (http://msdn.microsoft.com/en-gb/library/cc280663.aspx)

data-Creating server audit specifications

For the first example (demonstrated in listing 4), we’ll create a server audit tion to audit changes to logins using the SERVER_PRINCIPAL_CHANGE_GROUP anduse the ApplicationLog server audit we created earlier If you don’t specify the WITHclause, the server audit specification will be created in a disabled state We’ll also gen-erate some events for the audit to capture

specifica-CREATE SERVER AUDIT SPECIFICATION [AuditLoginChanges]

FOR SERVER AUDIT [ApplicationLog]

ADD (SERVER_PRINCIPAL_CHANGE_GROUP) WITH (STATE = ON)

GO create some events CREATE LOGIN AuditLoginDemo WITH PASSWORD = 'sdkfds*)&(9kdsafk', CHECK_POLICY=OFF

GO ALTER LOGIN AuditLoginDemo WITH DEFAULT_DATABASE = model, DEFAULT_LANGUAGE = British Listing 4 Creating a server audit specification using the Application Log target

Trang 18

Server audit specifications

GO DROP LOGIN AuditLoginDemo GO

In the next example, we’ll create a server audit specification using SSMS that auditsthe SERVER_OPERATION_GROUP and SERVER_STATE_CHANGE_GROUP audit actiongroups and uses the ServerAuditFile server audit To create a new server audit specifi-cation, follow these steps:

1 Expand the Security top-level node

2 Right-click the Server Audit Specifications node and choose New Server AuditSpecification This will open the Create Server Audit Specification dialog box,

SERVER_OPERA-5 Click OK to create the server audit specification

The server audit specification will be created in a disabled state To enable it:

1 Expand the Server Audit Specifications node in Object Explorer

2 Right-click the ServerOperationsAndState audit specification and chooseEnable Server Audit Specification

Figure 7 Creating a server audit specification using SSMS

Trang 19

The T-SQL code in listing 5 generates some events that will be captured by our audit inorder for us to have some activity to view.

EXEC sp_configure 'show advanced options',1 RECONFIGURE

GO EXEC sp_configure 'clr enabled',1 RECONFIGURE

GO

Viewing audit events

To view the audit events that are written to the Application or Security Log, we can useeither Windows Event Viewer or SSMS When viewing events using Event Viewer, it’shelpful to create a filter for only Success and Failure audits, to cut down the number

of records When viewing the audit in SSMS, this is automatically done for you Followthese steps to view the events in SSMS:

1 Expand the Security top-level node in SSMS

2 Expand the Audits node and right-click the ApplicationLog Server Audit

3 Select View Audit Logs, as shown in figure 8

This launches the SSMS LogFile Viewer, which enables you to easily review auditevents written to any of the available server audit targets, as shown in figure 9

To view events from server audits that use the File target, we can use a new built-insystem function called sys.fn_get_audit_file This function allows you to extractthe audit events from one or more audit files in a tabular format that can be queriedwith standard T-SQL or loaded into a table for further analysis Listing 6 demonstrateshow to query the sys.server_file_audits catalog view to obtain the audit folderand pass that to the sys.fn_get_audit_file function in order to view the auditevents in SSMS

DECLARE @folder VARCHAR(255) SELECT @folder = log_file_path + '*' FROM sys.server_file_audits WHERE name = 'ServerAuditFile' SELECT * FROM sys.fn_get_audit_file(@folder,DEFAULT,DEFAULT) ORDER BY event_time DESC

Listing 5 Creating events for the server audit specification

Listing 6 Viewing audit events from T-SQL

Figure 8 Viewing audit logs using SSMS

Trang 20

Server audit specifications

A number of new catalog views expose metadata about server audit specifications Thequery in listing 7 demonstrates some of them and lists all server audit specifications,along with their properties

SELECT sp.name AS ServerAuditSpecification, CASE WHEN sp.is_state_enabled =1 THEN 'Y' ELSE 'N' END AS SpecificationEnabled, d.AuditActions,

a.name AS ServerAudit, a.type_desc AS ServerAuditType, CASE WHEN a.is_state_enabled =1 THEN 'Y' ELSE 'N' END AS AuditEnabled, st.status_desc AS AuditStatus,

a.queue_delay AS QueueDelay, a.on_failure_desc AS OnFailure, st.audit_file_path AS CurrentFile, f.max_file_size AS MaxFileSize, f.max_rollover_files AS MaxRolloverFiles, CASE WHEN f.reserve_disk_space = 0 THEN 'N' WHEN f.reserve_disk_space = 1 THEN 'Y' END AS ReserveSpace FROM sys.server_audit_specifications AS sp

JOIN sys.server_audits a

ON sp.audit_guid = a.audit_guid JOIN sys.dm_server_audit_status st

ON a.audit_id = st.audit_id Listing 7 Viewing details of all server audit specificationsFigure 9 Viewing audit logs in the Log File Viewer

Ngày đăng: 15/12/2013, 13:15

TỪ KHÓA LIÊN QUAN