BC535 Database Administration DB2 UDB on UNIXNT

Reviews
BC535 Database Administration DB2 UDB on UNIX/NT BC535 Release 46D 05.02.2002 BC535 Database Administration DB2 UDB on UNIX/NT ................................................................................... 0-1 Copyright ........................................................................................................................................................... 0-2 SAP Basis Administration Training 4.6 ............................................................................................................. 1-1 SAP„s Knowledge Transfer Model .................................................................................................................... 2-1 Course Overview................................................................................................................................................ 3-1 Course Prerequisites - Audience - Duration ................................................................................................... 3-2 Course Objectives .......................................................................................................................................... 3-3 Course Contents ............................................................................................................................................. 3-4 Course Introduction........................................................................................................................................ 3-5 The Required Administration Knowledge ..................................................................................................... 3-6 DB2 Database Fundamentals ............................................................................................................................. 4-1 DB2 Database Fundamentals Part 1 ............................................................................................................... 4-2 DB2 Database Software Components ............................................................................................................ 4-3 DB2 Instances and R/3 Instances ................................................................................................................... 4-4 R/3 and DB2 Supported Combinations .......................................................................................................... 4-5 DB2 FixPaks .................................................................................................................................................. 4-6 DB2 Database Fundamentals Part 2 ............................................................................................................... 4-7 The DB2 Process Model for Unix Database Servers ..................................................................................... 4-8 The DB2 Process Model for Unix Database Servers ..................................................................................... 4-9 The DB2 Process Model for Unix Database Servers ................................................................................... 4-10 The DB2 Thread Model for NT Database Servers ....................................................................................... 4-11 Startup of DB2 ............................................................................................................................................. 4-12 Shutdown of DB2......................................................................................................................................... 4-13 DB2 TCP/IP Connection Setup .................................................................................................................... 4-14 DB2 IPC Connection Setup ......................................................................................................................... 4-15 SQL Statement Processing (1) ..................................................................................................................... 4-16 SQL Statement Processing (2) ..................................................................................................................... 4-17 Parallel I/O Servers and I/O Writers ............................................................................................................ 4-18 DB2 Database Fundamentals Part 3 ............................................................................................................. 4-19 Database Logging (1) ................................................................................................................................... 4-20 Database Logging (2): Log File Handling ................................................................................................... 4-21 Database Logging (3) ................................................................................................................................... 4-22 Database Logging (4) ................................................................................................................................... 4-23 Creation and Use of DB2 Log Files ............................................................................................................. 4-24 Circular Logging .......................................................................................................................................... 4-25 Log Retention Mode .................................................................................................................................... 4-26 Backup Pending Mode ................................................................................................................................. 4-27 DB2 Database Fundamentals Part 4 ............................................................................................................. 4-28 R/3 & DB2 Structures and Conventions on NT .......................................................................................... 4-29 R/3 & DB2 Structures and Conventions on UNIX ...................................................................................... 4-30 R/3 Naming Conventions: Review ............................................................................................................... 4-31 OS/Database Users and Authorities ............................................................................................................. 4-32 Roles of DB2 Database Administrative Users ............................................................................................. 4-33 Data Security: DB Access Passwords .......................................................................................................... 4-34 Unit Summary .............................................................................................................................................. 4-35 Unit Actions ................................................................................................................................................. 4-36 DB2 UDB Database Fundamentals: Exercises ............................................................................................ 4-37 DB2 UDB Database Fundamentals: Solutions ............................................................................................. 4-38 DB2 Cost-Based Optimizer................................................................................................................................ 5-1 DB2 Cost-Based Optimizer............................................................................................................................ 5-2 Cost-Based Optimizer: Introduction .............................................................................................................. 5-3 Facts Not Observed by the CBO .................................................................................................................... 5-4 DB2 UDB Cost-Based Optimizer .................................................................................................................. 5-5 DB2 UDB: Execution Plan ............................................................................................................................ 5-6 DB2 CBO: SQL Explain ................................................................................................................................ 5-7 Understanding DB2 Explain Output .............................................................................................................. 5-8 Understanding DB2 Details Output ............................................................................................................... 5-9 DB2 CBO: Details (1) .................................................................................................................................. 5-10 DB2 CBO: Details (2) .................................................................................................................................. 5-11 DB2 CBO: Details (3) .................................................................................................................................. 5-12 DB2 CBO: Details (4) .................................................................................................................................. 5-13 SQL Enhancements Affecting Query Execution .......................................................................................... 5-14 SELECT SINGLE Execution Plans ............................................................................................................. 5-15 UP TO ROWS Execution Plans ........................................................................................................... 5-16 DB2 Operators ............................................................................................................................................. 5-17 DB2 JOIN Concepts: MERGE..................................................................................................................... 5-18 DB2 JOIN Concepts: NESTED LOOP ........................................................................................................ 5-19 DB2 JOIN Concepts: HASH ........................................................................................................................ 5-20 DB2 Configuration for CBO ........................................................................................................................ 5-21 R/3 Tools for Updating Statistics: dmdb6srp ............................................................................................... 5-22 Scheduling Object Statistics for All Objects ................................................................................................ 5-23 Scheduling Daily Statistic Updates .............................................................................................................. 5-24 SAP‟s dmdb6srp Stores DB2 REORGCHK Results ................................................................................... 5-25 SAP Two-Phase Strategy ............................................................................................................................. 5-26 Refreshing Daily Object Statistics: Phase I .................................................................................................. 5-27 Refreshing Daily Object Statistics: Phase II ................................................................................................ 5-28 Modifying the Algorithm to Update the Statistics ....................................................................................... 5-29 Summary ...................................................................................................................................................... 5-30 Unit Actions ................................................................................................................................................. 5-31 DB2 UDB Cost-Based Optimizer: Exercises ............................................................................................... 5-32 DB2 UDB Cost-Based Optimizer: Solutions ............................................................................................... 5-33 DB2 UDB Tool Environment ............................................................................................................................ 6-1 DB2 UDB Tool Environment ........................................................................................................................ 6-2 Tool Infrastructure of DB2 UDB Databases .................................................................................................. 6-3 Administration Database: ADM .......................................................................................................... 6-4 Administration Database: Maintenance ......................................................................................................... 6-5 Installing the Admin Database and Server Tools ........................................................................................... 6-6 DB2 Graphical Administration Tools ............................................................................................................ 6-7 Technical Architecture: Background Daemons ............................................................................................. 6-8 Control Center: Installation ............................................................................................................................ 6-9 Control Center: SAP DB2 Admin Extensions ............................................................................................. 6-10 Control Center: Handling ............................................................................................................................. 6-11 Control Center: Cataloging of Databases ..................................................................................................... 6-12 DB2 Command Line Processor .................................................................................................................... 6-13 DB2 CLP: Important Commands ................................................................................................................. 6-14 DB2 CLP: Architecture ................................................................................................................................ 6-15 Data Security: DB Access Passwords .......................................................................................................... 6-16 DB2 Tools to Extract Statistics: db2look ..................................................................................................... 6-17 DB2 Utilities: db2look ................................................................................................................................. 6-18 DB2 Utilities: db2dart .................................................................................................................................. 6-19 Unit Summary .............................................................................................................................................. 6-20 Unit Actions ................................................................................................................................................. 6-21 DB2 Tool Environment: Exercises .............................................................................................................. 6-22 DB2 Tool Environment: Solutions ............................................................................................................... 6-23 Backup and Log File Management .................................................................................................................... 7-1 Backup and Log File Management ................................................................................................................ 7-2 Defining Your Backup Requirements ............................................................................................................ 7-3 Aspects of Data Safety: Separating File Systems .......................................................................................... 7-4 Aspects of Data Safety: Redundancy ............................................................................................................. 7-5 Data Backup Objects ...................................................................................................................................... 7-6 DB2 Backup Architecture .............................................................................................................................. 7-7 DB2 Recovery History File ............................................................................................................................ 7-8 DB2 Backup Types: Offline Backup ............................................................................................................. 7-9 DB2 Backup Types: Online Backup ............................................................................................................ 7-10 Backup Strategies: Tablespace Level Backups ............................................................................................ 7-11 R/3 and DB2 Database Backup Tools .......................................................................................................... 7-12 R/3 and DB2 Database Backup Tools .......................................................................................................... 7-13 R/3 and DB2 Database Backup Tools .......................................................................................................... 7-14 ADM Backup Tools ................................................................................................................... 7-15 Backup Cycle: DB2 Database Backups ....................................................................................................... 7-16 Backup Frequency Considerations ............................................................................................................... 7-17 DB2 Backup Process Architecture ............................................................................................................... 7-18 Using DB2 Backup Parallelism ................................................................................................................... 7-19 DB2 Backup Performance Tips.................................................................................................................... 7-20 Backup Device Configuration Tips .............................................................................................................. 7-21 Block Size Limits of Selected Backup Devices ........................................................................................... 7-22 Tivoli Storage Manger Administration ........................................................................................................ 7-23 Advanced Backup Scenarios: Split Mirror Backup...................................................................................... 7-24 Advanced Backup Scenarios: Standby Database ......................................................................................... 7-25 Importance of Offline Log Files................................................................................................................... 7-26 2-Step Log File Management ....................................................................................................................... 7-27 Native BRARCHIVE Tape Management .................................................................................................... 7-28 Tools for Offline Log File Management ...................................................................................................... 7-29 Tools for Offline Log File Management ...................................................................................................... 7-30 Tools for Offline Log File Management ...................................................................................................... 7-31 Tape Management Recommendations ......................................................................................................... 7-32 Backup Cycle ............................................................................................................................................... 7-33 1-Step Log File Management ....................................................................................................................... 7-34 Data Backup Objects .................................................................................................................................... 7-35 Unit Summary .............................................................................................................................................. 7-36 Unit Actions ................................................................................................................................................. 7-37 Backup and Log File Management: Exercises ............................................................................................. 7-38 Backup and Log File Management: Solutions ............................................................................................. 7-39 Restore and Recovery ........................................................................................................................................ 8-1 Restore and Recovery .................................................................................................................................... 8-2 Roll Forward Vs. Restart Recovery ............................................................................................................... 8-3 Restart Recovery: Background ...................................................................................................................... 8-4 Restart Recovery ............................................................................................................................................ 8-5 Roll Forward Recovery .................................................................................................................................. 8-6 Roll Forward Recovery Scenarios.................................................................................................................. 8-7 Database Recovery: Work Flow .................................................................................................................... 8-8 Restore and Recovery with Logical Failures ................................................................................................. 8-9 Disk Crash: Lost Containers ........................................................................................................................ 8-10 DB2 Restore Performance Tips.................................................................................................................... 8-11 DB2‟s Restore Tools .................................................................................................................................... 8-12 DB2 Restore Tools: DB2 Control Center .................................................................................................... 8-13 DB2 Restore Tools: DB2 Control Center - Tablespaces .............................................................................. 8-14 DB2 Restore Tools: DB2 Control Center - Containers ................................................................................ 8-15 DB2 Restore Tools: DB2 Control Center - Roll Forward ............................................................................ 8-16 DB2 Restore Tools: DB2 Control Center - Options ..................................................................................... 8-17 DB2 Restore Tools: DB2 CLP Commands .................................................................................................. 8-18 Log File Life Cycle for 2-Step Log File Management ................................................................................. 8-19 Log File Management: DB2 Control Center ................................................................................................ 8-20 Log File Management: BRRESTORE ......................................................................................................... 8-21 Restoring the Administration Database ........................................................................................................ 8-22 Why Perform a Redirected Restore? ............................................................................................................ 8-23 SAP Redirected Restore Tool: brdb6brt ....................................................................................................... 8-24 Restarting the DB2 CLP Script .................................................................................................................... 8-25 Reducing Tablespaces With Redirected Restore .......................................................................................... 8-26 Reducing the High Watermark With db2dart............................................................................................... 8-27 Restore: Preventing Backup Errors .............................................................................................................. 8-28 Classification of Database Recoveries ......................................................................................................... 8-29 Database Restoring Tips .............................................................................................................................. 8-30 Unit Summary .............................................................................................................................................. 8-31 Unit Actions ................................................................................................................................................. 8-32 Restore and Recovery: Exercises ................................................................................................................. 8-33 Restore and Recovery: Solutions ................................................................................................................. 8-34 Storage Management .......................................................................................................................................... 9-1 Storage Management ...................................................................................................................................... 9-2 Database Storage Concepts ............................................................................................................................ 9-3 Database Objects: Tables and Indexes ........................................................................................................... 9-4 Table Storage Details ..................................................................................................................................... 9-5 Index Storage Details ..................................................................................................................................... 9-6 Tablespace Details ......................................................................................................................................... 9-7 Data Distribution Using DB2 Containers ....................................................................................................... 9-8 System Managed Vs. Database Managed Space ............................................................................................ 9-9 Temporary Tablespaces: Recommendations ................................................................................................ 9-10 Database Object Growth: Extent Allocation ................................................................................................ 9-11 Database Object Growth: Out of Space Situation ........................................................................................ 9-12 Monitoring Tablespace Growth: History ..................................................................................................... 9-13 Monitoring Tablespace Storage Allocation .................................................................................................. 9-14 Monitoring Container Placement ................................................................................................................. 9-15 Extending Database Storage Using DB2 CLP ............................................................................................. 9-16 Automated Rebalancing DB2 Extents .......................................................................................................... 9-17 Monitoring Rebalancing Progress ................................................................................................................ 9-18 DB2 Rebalancing Strategy ........................................................................................................................... 9-19 DB2 Recovery and Rebalancing: Possible Problems ................................................................................... 9-20 DB2 Redirected Restore: Redefinition of Storage ....................................................................................... 9-21 Table Reorganization Check in CCMS ........................................................................................................ 9-22 Freespace Monitoring of Tables ................................................................................................................... 9-23 Monitoring Fragmentation of Tables in R/3................................................................................................. 9-24 Overflow Records ........................................................................................................................................ 9-25 Index Cluster Properties ............................................................................................................................... 9-26 DB2 Table Reorganization in Same Tablespace .......................................................................................... 9-27 Reorganizing Tables Using Tablespace TEMP............................................................................................ 9-28 Reorganization Tools in CCMS ................................................................................................................... 9-29 Reorganizing Large Tables .......................................................................................................................... 9-30 Online Index Reorganization ....................................................................................................................... 9-31 Creating Additional Tablespaces ................................................................................................................. 9-32 Unit Summary .............................................................................................................................................. 9-33 Unit Actions ................................................................................................................................................. 9-34 Storage Management: Exercises .................................................................................................................. 9-35 Storage Management: Solutions................................................................................................................... 9-36 Performance Monitoring .................................................................................................................................. 10-1 Performance Monitoring .............................................................................................................................. 10-2 Database-Related Performance Issues ......................................................................................................... 10-3 Memory Configuration................................................................................................................................. 10-4 DB2 Memory Configuration 1 ..................................................................................................................... 10-5 Database Memory Configuration 2 .............................................................................................................. 10-6 Memory Configuration 3.............................................................................................................................. 10-7 Memory Configuration 4.............................................................................................................................. 10-8 Buffer Pool Considerations .......................................................................................................................... 10-9 Assessing the Efficiency of the Buffer Pool .............................................................................................. 10-10 Increasing the Size of the Buffer Pool ....................................................................................................... 10-11 Package and Catalog Cache Considerations .............................................................................................. 10-12 Sorting Area Considerations ...................................................................................................................... 10-13 Understanding Overflow Sorts ................................................................................................................... 10-14 Lock List Considerations ........................................................................................................................... 10-15 Inefficient Application Design ................................................................................................................... 10-16 When a Lock Wait Situations Occurs ........................................................................................................ 10-17 Identifying a Lock Wait Situation with R/3 ............................................................................................... 10-18 Reducing Exclusive Lockwaits .................................................................................................................. 10-19 Application Problems: Unnecessary Statements ........................................................................................ 10-20 Identifying Unnecessary SQL Statements .................................................................................................. 10-21 Eliminating Unnecessary SQL Statements................................................................................................. 10-22 Application Problems: Poorly Qualified Statements .................................................................................. 10-23 Analyzing a Poorly Qualified Statement .................................................................................................... 10-24 Performing an Explain Plan: Details .......................................................................................................... 10-25 Identifying Missing Indexes in Database ................................................................................................... 10-26 Dynamic SQL Cache Analysis ................................................................................................................... 10-27 Analyzing the Dynamic SQL Cache .......................................................................................................... 10-28 Analyzing SQL Sorts ................................................................................................................................. 10-29 Understanding DB2's FETCH Statements ................................................................................................. 10-30 Cost-Based Optimizer ................................................................................................................................ 10-31 Refreshing the Object Statistics ................................................................................................................. 10-32 Database Job Monitor (Transaction DB24)................................................................................................ 10-33 Modifying the Algorithm to Update the Statistics ..................................................................................... 10-34 Reasons for Performance Problems ........................................................................................................... 10-35 Physical and Logical Layout ...................................................................................................................... 10-36 Physical I/O Contention ............................................................................................................................. 10-37 Identifying I/O Contention in the Database ............................................................................................... 10-38 Solving I/O Contention .............................................................................................................................. 10-39 Optimize I/O on RAID Devices ................................................................................................................. 10-40 Solving Performance Problems .................................................................................................................. 10-41 Unit Summary ............................................................................................................................................ 10-42 Unit Actions ............................................................................................................................................... 10-43 Performance Monitoring: Exercises ........................................................................................................... 10-44 Performance Monitoring: Solutions ........................................................................................................... 10-45 Troubleshooting ............................................................................................................................................... 11-1 Troubleshooting ........................................................................................................................................... 11-2 Begin Your Daily Work with Monitoring .................................................................................................... 11-3 DB Monitoring: Freespace in Tablespaces .................................................................................................. 11-4 Daily DB Monitoring: Tablespace Growth .................................................................................................. 11-5 DB Monitoring: Last Backup and Archive Results ...................................................................................... 11-6 DB Monitoring: Backup Log ....................................................................................................................... 11-7 DB Monitoring: Freespace in Directory log_dir .......................................................................................... 11-8 Resolving Problems with DB2 Logging User Exit ...................................................................................... 11-9 Solving Problems with DB2 Logging User Exit ........................................................................................ 11-10 Solving Problems with DB2 Logging User Exit ........................................................................................ 11-11 DB Monitoring: Missing Indexes ............................................................................................................... 11-12 DB Monitoring: Runstats Activity ............................................................................................................. 11-13 Database Job Monitor: Runstats Activity ................................................................................................... 11-14 DB Monitoring: Mirroring the Administration Database ........................................................................... 11-15 Review db2diag.log ................................................................................................................................... 11-16 Monitoring Tools: Overview...................................................................................................................... 11-17 SAP System Administration Assistant (SSAA) ......................................................................................... 11-18 DB2 Diagnostic Files ................................................................................................................................. 11-19 Interpreting the db2diag.log file ................................................................................................................. 11-20 Decoding TechTalk in db2diag.log ............................................................................................................ 11-21 Tracing Database Malfunctions ................................................................................................................. 11-22 Preventative Maintenance .......................................................................................................................... 11-23 Database Utilities ....................................................................................................................................... 11-24 Roadmap for Start Problems ...................................................................................................................... 11-25 Roadmap Stop Problems ............................................................................................................................ 11-26 Files Needed for SAP DB2 Database Hotline ............................................................................................ 11-27 Unit Summary ............................................................................................................................................ 11-28 Unit Actions ............................................................................................................................................... 11-29 Troubleshooting: Exercises ........................................................................................................................ 11-30 Troubleshooting: Solutions ........................................................................................................................ 11-31 BC535 Database Administration DB2 UDB on UNIX/NT Database Administration DB2 UDB on UNIX/NT BC535 R/3 Release 4.6B R/3 Release 4.6B  SAP AG 1999 50038148 50038148 Copyright Copyright 2001 SAP AG. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. All rights reserved.  SAP AG 2001 Trademarks:           Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® are registered trademarks of Microsoft Corporation. IBM®, DB2®, OS/2®, DB2/6000®, Parallel Sysplex®, MVS/ESA®, RS/6000®, AIX®, S/390®, AS/400®, OS/390®, and OS/400® are registered trademarks of IBM Corporation. ORACLE® is a registered trademark of ORACLE Corporation. INFORMIX®-OnLine for SAP and INFORMIX® Dynamic ServerTM are registered trademarks of Informix Software Incorporated. UNIX®, X/Open®, OSF/1®, and Motif® are registered trademarks of the Open Group. HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. JAVA® is a registered trademark of Sun Microsystems, Inc. JAVASCRIPT® is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. SAP, SAP Logo, R/2, RIVA, R/3, ABAP, SAP ArchiveLink, SAP Business Workflow, WebFlow, SAP EarlyWatch, BAPI, SAPPHIRE, Management Cockpit, mySAP.com Logo and mySAP.com are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other products mentioned are trademarks or registered trademarks of their respective companies. SAP Basis Administration Training 4.6 Core Competence MBC30 2 days R/3-Technical Implementation and Operation Management BCtcc* Technical Core Competence BC325 5 days BC305 3 days Advanced R/3 System Administration BC315 3 days Expert Competence BC505 3 days Database Administration Oracle BC511 5 days Database Administration Informix BC515 2 days Database Administration SAP DB BC520 3 days Database Administration MS SQL Server BC525 3 days Database Administration DB2/400 BC530 5 days Database Administration DB2/390 BC535 3 days Database Administration DB2 UDB BC555 Corresponding R/3 Basis Knowledge Product and/or SAP Expert Knowledge Book 3 days Software Logistics MY301 2 days Workload Analysis 3 days BC350** Workplace TCC Workplace *Technical Core Competence Versions BC310 BC312 BC314 BC317 BC360 BC361 BC362 BC370 BC390 **BC350 Windows NT / Oracle Windows NT / SAP DB Windows NT MS SQL Server (Windows NT / UNIX) / DB2 UNIX / Oracle UNIX / Informix UNIX / SAP DB IBM AS400 IBM /390 Workplace (combined with MY301) 2 days LiveCache Administration Database Administration Training  SAP AG 1999 (C) SAP AG BC535 1-1 (C) SAP AG BC535 2-1 Course Overview  SAP AG 1999 (C) SAP AG BC535 3-1 Course Prerequisites - Audience - Duration  Prerequisites:    SAP 50 R/3 Basis Technology BC317 Technical Core Competence (DB2 on UNIX/Windows NT) Basic knowledge of the UNIX or Windows NT operating systems  Audience:  Project team members responsible for the administration of SAP R/3 DB2 UDB database servers Technical consultants responsible for the installation, troubleshooting, and performance tuning of DB2 UDB database servers   Duration:  3 days  SAP AG 1999 (C) SAP AG BC535 3-2 Course Objectives This course will enable you to:  Create a safe and secure operating environment for DB2 UDB database servers in your SAP R/3 implementation  Operate the DB2 servers on a daily basis  Analyze and adapt your DB2 server performance to requirements in your SAP R/3 implementation  Use the SAP DB2 Admin Extensions  Maintain the highest possible availability through preventive maintenance  SAP AG 1999 (C) SAP AG BC535 3-3 Course Contents Preface Introduction Unit 1 Unit 2 Unit 3 Unit 4 DB2 UDB Fundamentals DB2 UDB Cost-Based Optimizer DB2 UDB Tool Environment Backup & Log File Management Conclusion Appendix Unit 5 Unit 6 Unit 7 Unit 8 Restore & Recovery Storage Management Performance Monitoring Troubleshooting  SAP AG 1999 (C) SAP AG BC535 3-4 Course Introduction  R/3 on DB2 Universal Database Version 6 enables the use of IBM‟s DB2 UDB database architecture on hardware systems ranging from Intel-based Windows NT servers, small UNIX servers, to high end SMP UNIX systems  This course provides all the information necessary to safely operate the R/3 System on DB2 UDB servers in these environments  This course is geared towards technical staff in R/3 implementation teams who are responsible for DB2 database servers  SAP AG 1999 (C) SAP AG BC535 3-5 The Required Administration Knowledge “Imagine a thunderstorm. Although the dynamics of meteorology are well understood in our times, we still cannot predict when and where the lightning will strike. However, we can safeguard ourselves through proper behavior based on knowledge. Think about your database. Again, though proper knowledge you will be able to decrease risks. Always be prepared!” SAP Technical Core Competence DB2 Center of Expertise  SAP AG 1999 (C) SAP AG BC535 3-6 (C) SAP AG BC535 4-1 DB2 Database Fundamentals Part 1 Contents     DB2 database software components DB2 instances and R/3 instances R/3- and DB2-supported combinations DB2 FixPaks Objectives At the end of this section, you will be able to:  Identify the DB2 database software components  Identify the DB2 instance and database of an R/3 System  Access the current information regarding the supported combinations of R/3 and DB2 UDB versions  Access the relevant information about SAP supported FixPaks  SAP AG 1999 (C) SAP AG BC535 4-2 DB2 Database Software Components Host A R/3 central instance IPC (Local) Host B R/3 instance Network DB2 UDB administration client TCP/IP (Remote) DB Server DB2 UDB EE DBA workstation DB2 UDB administration client DB2 Control Center SAP DB2admin tools  SAP AG 1999   For each R/3 System, there is one database server. The database server has core database software installed: DB2 Universal Database Enterprise Edition. If there is only one application server running, and this application server is installed on the database server, there is no need to install further software on the system. In this case, the communication between database server and application server is based on inter process communication (IPC). For all remote application servers, you must install the remote client access software. In DB2, it is called the DB2 Client Application Enabler. For each of the workstations of the database administrators, the WIN32 version of the DB2 Client Application Enabler must be installed. It contains the DB2 Control Center that hosts the R/3 DB2ADMIN software. The R/3 DB2ADMIN software can be installed by executing program db2ainst.exe on the workstation.   (C) SAP AG BC535 4-3 DB2 Instances and R/3 Instances R/3 System R/3 instance DVEBMGS00 R/3 instance DV00 R/3 Instance DV00 What is a DB2 instance? DB2 instance DB2 R/3 DB Admin DB (R/3 >= 4.0) ADM DB2 administration server Instance DB2DAS00 for NT Instance DB2A for Unix  SAP AG 1999  An R/3 System, identified by , consists of:  One or more R/3 instances  The DB2 database instance DB2, which contains: - The R/3 database - The administration database, called ADM, which is needed for administrative purposes and is replicated in the R/3 database    Each R/3 System has its own DB2 database instance DB2. On UNIX, the DB2 instance is started together with the R/3 System. On Windows NT, the DB2 instance runs as a service. To retrieve configuration parameters for the DB2 instance, use command db2 get dbm cfg. To obtain parameters for database within the instance, use command db2 get db cfg for . In addition to the DB2 instance DB2, a second database instance DB2DAS00 (NT) / DB2AS (Unix) is installed on the database server to allow remote administration of the database server.  (C) SAP AG BC535 4-4 R/3 and DB2 Supported Combinations DB2 versions V5 V6.1 R/3 Releases 3.0D...3.1H 3.1I 4.0A 4.0B 4.5A 4.5B 4.6A 4.6B For further information, refer to http://sapnet.sap-ag.de/dbosplatforms  SAP AG 1999    For current information regarding supported combinations of R/3 and DB2 UDB versions, refer to SAPNet http://sapnet.sap-ag.de/dbosplatforms. Please pay special attention to upgrade restrictions that apply to particular combinations. You may encounter names other than DB2 Universal Database used as synonyms in SAP documentation (such as in the SAP Notes). This is because of the history of frequently changed names of DB2:  DB2/6000  DB2 for AIX  DB2 Common Server (or DB2 CS for short)  DB2 Universal Database (or DB2 UDB for short)  Therefore, the internal abbreviation for the DB2 Universal Database on Unix/NT is DB6. Do not use DB2 when searching for information in SAPNet because this is the abbreviation used for DB2 on OS/390. (C) SAP AG BC535 4-5 DB2 FixPaks  SAP performs special integration tests with IBM supplied FixPaks  SAP Note 101809 supplies information about the supported FixPaks  SAP Note 166481 supplies information about available RDBMS CD-ROMs, including FixPaks STOP  Only use SAP supplied FixPaks  SAP AG 1999     When IBM releases a new DB2 version or FixPak, SAP performs special tests on them to ensure compatibility with R/3. Every FixPak that was successfully tested is documented in SAP Note 101809, and can be installed by customers. For information about how to retrieve the appropriate RDBMS CD-ROM, see SAP Note 166481. Ensure you only use RDBMS software (including FixPaks) that was shipped by SAP. (C) SAP AG BC535 4-6 DB2 Database Fundamentals Part 2 Contents        DB2 process model (Unix database servers) DB2 thread model (Windows NT database servers) Startup of DB2 Shutdown of DB2 DB2 TCP/IP connection setup DB2 IPC connection setup SQL statement processing Objectives At the end of this section, you will be able to:  Identify the differences between DB2 for Unix and Windows NT  Start the DB2 database  Shut down the DB2 database  Describe the DB2 TCP/IP connection setup  SAP AG 1999 (C) SAP AG BC535 4-7 The DB2 Process Model for Unix Database Servers Watch dog Per instance System control Global daemon spawner IPC communication manager TCP/IP communication manager Per database Prefetcher/ I/O server Page cleaner/ I/O cleaner Logger Per connection Agent  SAP AG 1999   One of the differences with the implementation of DB2 on UNIX and Windows NT is that the architecture on Unix is based on processes and the architecture on Windows NT is based on threads. DB2‟s processes/threads are divided into three groups:  The per instance processes/threads are started to enable the database manager system to run properly  The per database processes/threads are started for each database running within the database manager  The per connection processes/threads are started for each application program (or work process) connecting to the database  The DB2 processes/threads can be monitored using:  Unix: ps -ef (on Solaris use: /usr/ucb/ps -awwx)  NT: qslice (C) SAP AG BC535 4-8  The per instance processes are:  The listener processes - An inter-process communications listener for local client programs (db2ipccm) - One listener for each configured communication protocol, which is only TCP/IP in a R/3 system (db2tcpcm)  The database manager process or system control process (db2sysc)  The watch dog process (db2wdog), which is responsible for the cleanup of system resources (this is the only process that runs under root authority, all other processes are run with the instance owner db2).  The global daemon spawner (db2gds), which forks the database processes (exception: db2 agent processes for remote connections). (C) SAP AG BC535 4-9  Each DB2 database has a group of I/O processes:  One or more prefetchers (db2pfchr), used for asynchronous retrieval of data from disk into the buffer pool (db2 prefetchers are also called I/O servers)  One or more page cleaners (db2pclnr), which write changed pages from buffer pool to disk asynchronously (db2 page cleaners are also called I/O cleaners)  One logger process (db2loggr) for manipulation of database log files   Each work process (local + remote) is connected to a corresponding agent process (db2agent). If intra-query parallelism is enabled, this process is called the coordinator agent. DB2 then assigns a pool of sub-agents to a coordinator agent to work on parts of the same task. This is called intra-query parallelism, which reduces processing time on symmetric multiprocessor (SMP) systems. This setting is useful for SAP Business Warehouse database servers. (C) SAP AG BC535 4-10 The DB2 Thread Model for NT Database Servers System control Per instance threads IPC communication manager TCP/IP communication manager Per database threads Prefetcher/ I/O server Page cleaner/ I/O cleaner Logger Per connection threads  SAP AG 1999 Agent  DB2 implementation on Windows NT is multi-threaded. As with UNIX, there are three distinct functional groups, but they are implemented as threads. All threads run within the Windows NT program db2sysc.exe. Use the Windows NT resource tool kit program qslice to view the threads in a program. With this program, you can monitor the growing number of threads in program db2sysc during R/3 startup. More information can be accessed using the NT Performance Monitor perfmon.exe, which is located in the administrative program group, as described in section Performance Monitoring. Other than the above mentioned differences, the implementation of DB2 on UNIX and Windows NT are very similar. Threads and processes that are managed by the DB2 database server engine are also called EDUs (engine dispatchable units).     (C) SAP AG BC535 4-11 Startup of DB2 Explicit start of DB2 instance: command db2start Explicit start of DB: command db2 activate Buffer pool(s), etc. or Implicit start of DB: at first connection R/3 disp+work  SAP AG 1999  During R/3 startup, the DB2 instance is started with command db2start (if it is not already started). All the per-instance processes are started. There are two different ways to activate a DB2 database:  Implicitly, through the activation of the database by first connection request  Explicitly, executing command db2 activate database or db2 connect to   During activation, the per-database processes are started, the database buffers are initialized, and log files are created if needed. A DB2 agent (process db2agent) is created to service the connection request. Note: The DB2 database is not active after executing command db2start. The database is only started if a database connection has been established. Therefore, the first connection request to a DB2 database may take a while, until all buffers and files are initialized. On Unix, the DB2 watch dog process is a process without a controlling terminal. These processes are typically called daemon processes. This means the program will not stop when the user who started the program logs off. On Windows NT, the DB2 instance runs as a service (defined for automatic startup in NT registry).    (C) SAP AG BC535 4-12 Shutdown of DB2 Explicit stop of DB2 instance: command db2stop Explicit stop of DB: command db2 deactivate Buffer pool(s), etc. or Implicit stop of DB: with end of last connection R/3 disp+work  SAP AG 1999   During shutdown, the DB2 I/O servers flush the buffer pool(s) to disk and then stop the per-database processes. There are two ways to shut down a DB2 database:  Explicitly, by executing the command db2 deactivate database  Implicitly, when the last connection has been reset, the database shuts down automatically. Note: If the database was activated using the command db2 activate, it can only be stopped with command db2 deactivate.  The DB2 instance can be stopped with command db2stop. As long as applications are still running, the database instance cannot be stopped. To check the status of the applications, use command db2 list applications [show detail]. To perform an emergency shutdown of DB2, use command db2stop force. All applications are disconnected, running transactions are rolled back, and the buffers of the database are consistently written to disk.   (C) SAP AG BC535 4-13 DB2 TCP/IP Connection Setup disp+work db2tcpcm db2agent R/3 disp+work 1 1 Arbitrary port A A sapdb2 B B fork/exec 3 3 Instance processes db2tcpcm 2 2 C C Arbitrary port Connection processes db2agent  SAP AG 1999   This example shows the DB2 processes that are used during remote database connection setup. For the connection setup (red numbering), the following scenario applies:  An application program connects to the TCP/IP listener (db2tcpcm) on a predefined TCP/IP port. This port is defined in the DBM CFG parameter SVCENAME. (1)  The TCP/IP listener establishes a new socket on another arbitrary port and forks itself into what becomes a DB2 agent. (2)  The DB2 agent can now communicate directly with the application. The db2tcpcm is free to service additional requests. (3)  For the network communication (green lettering), the following scenario applies:  The application sends a connection request from an arbitrary socket to the database server (port name sapdb2). (A)  A new socket is created on an arbitrary port. On UNIX systems, the DB2 agent is created by forking the db2tcpcm. On Windows NT, a thread that acts as a DB2 agent is created. (B)  The DB2 agent is responding on the new socket and the communication is established. First, the maximum requested I/O block size is negotiated by the client (RQRIOBLK). For each blocking cursor there is always a buffer of RQRIOBLK size on client side. This can allocate a substantial amount of memory per work process (check for blocked cursors in the Application Snapshot using transaction ST04  Detailed analysis menu). (C) (C) SAP AG BC535 4-14   This example shows the DB2 processes that are used during local DB2 database connection setup. Here, the communication method is called inter process communication (IPC). For connection setup, the following scenario applies:  Since the database is cataloged locally, the application program connects to the local listener program (db2ipccm) through a message queue owned by db2ipccm. Information about the IPC is returned to the application program. (1)  The DB2 global demon spawner (db2gds) is instructed to handle the application request. (2)  The db2gds forks a DB2 agent on the database server on behalf of the application program. On Windows NT, a DB2 agent thread is created. The IPC information is known to the DB2 agent since it is forked. (3)  Local connections are established through the application support layer (ASL) heap, which acts as the main IPC component between the application and the DB2 agent. (4)  Local connections are faster than connections made through TCP/IP. (C) SAP AG BC535 4-15 SQL Statement Processing (1) SQL statement R/3 work process SELECT author, devclass, obj_name FROM sapr3.tadir WHERE 2 2 author=‟JOHN DOE‟ 1/6 1/6 Execution plan SELECT STATEMENT | (Estimated Costs = 661 [timerons] ) --RETURN | --FETCH TADIR | ------IXSCAN TADIR~2 #key columns: 1 Per instance Buffer pool Agent pool db2agent db2agent 5 5 Per connection 3 3 4 4 Disks db2pfchr Per database  SAP AG 1999   All work processes connect to the database as user sapr3. R/3 System users do not have a database system user ID. A work process is only active for one user during the dialog step, between screen input and screen output. Before screen output, the work process issues a commit to the database. This means different users use the same work process and database connection consecutively. The work process does not connect to and disconnect from the database between the dialog steps. This example shows the processes used for handling SQL statements:  An SQL statement is sent from the R/3 work process to its associated agent. (1)  The DB2 Optimizer in the DB2 agent transforms the SQL statement into an access plan on data. This process is called preparation. The plan may also be cached already. (2)  In many cases, the agent forwards information about the pages that need to be transferred from data containers into the buffer pool to the DB2 I/O servers. (3)  Several I/O servers work on the requests, performing I/O in parallel. (4)  The agent performs additional tasks, as defined in the DB2 access plan. In this example, the execution plan is an index scan with one search argument. If work can be divided into subtasks and intra parallelism is used, the agent uses agents out of the agent pool to enable parallel processing. (5)  The data is sent to the application using a FETCH SQL command. (6)  (C) SAP AG BC535 4-16 SQL Statement Processing (2) SQL statement R/3 work process 1 1 UPDATE sapr3.tadir SET devclass = “ZXX” WHERE author=‟JOHN DOE‟ Log buffer Log records 3 3 db2agent Buffer pool Per connection 2 2 db2agent Per database db2loggr db2pclnr 4 4 log_dir log_dir DB files  SAP AG 1999  This example shows the processes that handle database logging using a processing example:  UPDATE/INSERT SQL statements are sent from application to the associated DB2 agent. (1)  Data is manipulated in the buffer pool but not transferred to disk. The db2agent process writes information about the changes in the buffer as log records in the log buffer. (2)  The db2loggr process is responsible for writing the contents of the log buffer to the current active log file. (3) This is done: - When an application ends the transaction by issuing a COMMIT/ROLLBACK SQL statement - Every second - When the log buffer is full  I/O cleaners, also known as page cleaners, copy updated pages onto disk when triggered. (4) I/O cleaners get triggered when: - The maximum amount of log space that should be read during crash recovery has been reached (DB CFG parameter SOFTMAX) - The maximum percentage of changed pages has been reached (DB CFG parameter CHNGPGS_THRESH) - No pages are available during insert/update. In this case, “victim page cleaning” is started. - Note: I/O cleaners can be configured in a wide range. (C) SAP AG BC535 4-17 Parallel I/O Servers and I/O Writers Buffer pool R/3 work process db2agent db2agent REA D &W RITE db2clnr 1 n db2pfchr n 1 Disk 1 WRITE R D EA & READ T RI W E Disk 2 Disk n  SAP AG 1999  To achive optimal utilization of the I/O devices (physical disks), the number of I/O processes can be configured: - With disks containing database containers, you should configure the number of I/O servers slightly higher than . This way, there is always an I/O server available until the number of disks has been reached. In the unlikely situation that all of the I/O servers are busy, there is no reason to introduce more since they are all waiting for I/O on the disks. More I/O servers would only put higher load on the disk drives and increase the asynchronous read times. - As a rule of thumb, the number of I/O servers should not be higher than 25 on very fast SMP database servers and not higher than 12 on very fast uni-processor database servers. - If Transaction ST04 displays a higher value on the average asynchronous read time of I/O servers, you should decrease the number of I/O servers.  LONG VARCHAR data is not buffered by DB2's buffer pool(s). In this case, synchronous I/O is performed by the DB2 agents. Most of the tables that use unbuffered data types are buffered in the application servers. To display the list of tables that contain unbuffered data, issue the following SQL statement: db2 SELECT name, tbname, length FROM sysibm.syscolumns WHERE coltype ='LONGVAR'  If any performance bottlenecks occur, these unbuffered data objects should be analyzed. (C) SAP AG BC535 4-18 DB2 Database Fundamentals Part 3 Contents  Logging concept  Database log file handling  Logging modes Objectives At the end of this section, you will be able to:  Identify online and offline log files  Deactivate circular logging and activate log retention mode  SAP AG 1999 (C) SAP AG BC535 4-19 Database Logging (1) R/3 work process Log file header (SQLOGCTL.LFH) Recovery range Synchronous write on COMMIT/ROLLBACK Log files Log buffer Buffer pool db2agent Per connection Asynchronous write when triggered db2agent Per database  SAP AG 1999 db2loggr db2pclnr log_dir DB files  When an operation is committed or rolled back, all the contents of the log buffer are transferred to the current active log file. COMMIT/ROLLBACK statements are synchronous, that is, they are returned when the write operation is finished. If there is not enough space for writing the log records, database error message SQL0964 (transaction log for the database full) will occur. Since the log files are mandatory for recovery and the write operation is synchronous, the log files must reside on mirrored and fast disks. A good configuration is RAID 1. The copying of changed pages from buffer pool(s) to container files happens asynchronously. RAID 5 storage for the containers may be appropriate, although RAID 1 is faster. When the changed pages have been written to disk by the I/O servers, DB2 will not need to re-create those pages during crash recovery. Because of this, the log file header is moved “forward” to the first log record which contains data about pages that are changed and not on disk. If the LFH moves out of a log file, this file is not required for a crash recovery. Note: File sqlogctl.lfh contains the log file header. If this file is not readable, crash recovery is not possible. In this case, the database must be restored. Therefore, the home directory of the DB2 instance owner db2 should be located on a mirrored device as well.    (C) SAP AG BC535 4-20  This example shows how log file are handled:  Pages are changed in the buffer pool by the db2agent process/thread. (1)  Information about these changes are written as log records in the log buffer. (2)  Log records are written from the log buffer to log files in directory log_dir by the db2loggr process/thread. (3) This is done: - When an application ends the transaction by issuing a COMMIT/ROLLBACK SQL statement - Every second - When the log buffer is full The status of this log file is online active.  When a log file is filled with records, the db2 user exit (program db2uext2.exe) is called by the database and copies the log file into directory log_archive. The copied log file is called the offline log. When all referenced pages have been written to disk (from the buffer pool) the online active log file is deleted in the log_dir directory, but a copy of it remains as an offline log in the log_archive directory. (4) (C) SAP AG BC535 4-21  All online active log files reside in directory log_dir. Active log files contain committed and uncommitted transaction data that refer to changed pages in the buffer pool, which have not been written to disk yet. They are needed for ROLLBACK operations and crash recovery. Active log files are deleted only when they are no longer needed by DB2 because all referenced transactions are committed and all changed pages have been written down to disk. Also the DB2 user exit must have been successful in copying the active logs into the log_archive directory. Note: DB2 is configured to run the DB2 restart utility if an incorrect database shutdown is detected. DB2 then reads the online active log files to recreate the contents of the buffer pool at the time of the system crash and rolls back all unfinished transactions.   (C) SAP AG BC535 4-22  The log files that have been copied by the DB2 user exit reside in the directory log_archive. They are called offline because they are no longer needed by the database for rollback operations or a crash recovery. However, they have to be copied back to directory log_dir in case of a roll forward recovery. When directory log_archive fills with offline logs, the DB2 database administrator must archive log files using the CCMS or the DB2 Control Center. The state of log files on tape or ADSM is archived. Archiving is important since the database cannot continue to run if there is no space available. To avoid the situation of having no space available, the log files must be archived regularly.   (C) SAP AG BC535 4-23       At database startup, DB2 searches for log files in directory log_dir. If no log files exist, all primary log files are created by DB2. The total number of these log files is defined in the database configuration parameter LOGPRIMARY. The size of the log files (in 4KB pages) is defined in the database configuration parameter LOGFILSIZ. All log files are created during database operation Restore into new. In most cases, you may not see the full number of log files. Secondary log files are created on demand during database operations. The total number of secondary log files is defined in the database configuration parameter LOGSECOND. If the primary log files are all in use, secondary log files are created. (C) SAP AG BC535 4-24 Circular Logging LOGRETAIN = OFF log_dir X BC535 Active Inactive  SAP AG 1999  A DB2 database is configured in circular logging mode if the database configuration parameters LOGRETAIN and USEREXIT are set to OFF. This is the initial setting of the database after it is created, but it should not be the default setting for an R/3 database. Circular logging recycles log files that are no longer used, such as files that are not active. Since log files are overwritten, you cannot perform a roll forward recovery in the circular logging mode. Do not run a database for the R/3 System in circular logging mode. If a disk error occurs, you may not be able to recover your database.   (C) SAP AG 4-25 Log Retention Mode First active log file LOGRETAIN = RECOVERY log_dir USEREXIT = ON log_archive When full, db2uext2 is called  SAP AG 1999  SAP recommends running the database for your R/3 System in log retention mode. To do this, set the database configuration parameters USEREXIT to ON and LOGRETAIN to RECOVERY (in DB2 V2 and V5.x the parameter LOGRETAIN has to be set to ON). The total log space available for a database running in log retention mode is the same as for circular logging mode: LOGFILSIZ * (LOGPRIMARY+LOGSECOND). The database manager configuration parameter USEREXIT enables unattended transfers of log files from directory log_dir to directory log_archive. When a log file is filled with records, DB2 calls the logging user exit program db2uext2, which is integrated into the R/3 System. Note: Do not use the sample programs that are provided in the samples directory of the DB2 instance. In certain cases, you may have to move log files from the online log directory to the offline log directory manually. If this occurs, do not use the operating system command copy. Instead, manually call the DB2 logging user exit. For more information about the DB2 logging user exit, see the documentation of the sample programs or the log file db2uext2.log. The logging user exit program writes log information for each execution into the administration database.     (C) SAP AG BC535 4-26 Backup Pending Mode Active LOGRETAIN = OFF log_dir Logging mode after installation Inactive Change parameters and restart DB Database is backup pending Perform full offline backup LOGRETAIN = RECOVERY Production logging mode log_dir USEREXIT = ON log_archive  SAP AG 1999   The initial setting of parameters LOGRETAIN and USEREXIT have to be changed after the installation in order to enable roll forward recovery. When these parameters are set and become effective (for example after restarting the database), DB2 goes into backup pending state. You must then perform a complete offline database backup. This backup is used as the starting point for recovery. You cannot connect to the database until this offline database backup has been successfully completed.  (C) SAP AG BC535 4-27 DB2 Database Fundamentals Part 4 Contents  Naming conventions  Users and groups  Data security Objectives At the end of this section, you will be able to:  Identify the structures and naming conventions for DB2 and R/3 in a UNIX and NT environment  Describe the DB2 users and system administrators for R/3 in a UNIX and NT environment  Understand the importance of data security  SAP AG 1999 (C) SAP AG BC535 4-28 R/3 & DB2 Structures and Conventions on NT Directory Meaning DB2 software (specified at SW installation) DB2 instance directory DB2 offline log directory DB2 temp. storage of log files during roll forward CD1 copy during install DB2 online log directory Database diagnostic path Data containers / index containers Owner of the objects created on the database R/3 system administrator R/3 service owner for system R/3 database instance owner and administrator DB2ADMIN instance owner :\ :\db2 :\db2\\log_archive :\db2\\log_retrieve :\db2\\sapreorg :\db2\\log_dir :\db2\\db2dump :\db2\\sapdata1...N Windows NT users : sapr3 adm sapse db2 db2admin  SAP AG 1999   In the R/3 database server environment, directory and file names are standardized on Windows NT. Directory \usr\sap\\SYS\exe\run contains the R/3 executable programs, which are also programs that are used for database administration, such as:  brdb6rst  brdb6bck  brarchive  During the installation of the R/3 System on Windows NT, the user is prompted for the drive locations of the above directories. Note: Windows NT does not offer a single directory tree with mounted file systems. The diagnostics of the DB2 database are written to :\db2\\db2dump. Log files recording the archiving of log files reside in :\db2\saparch. Log files recording the restoring of archived log files are written to :\db2\saprest.    (C) SAP AG BC535 4-29 R/3 & DB2 Structures and Conventions on UNIX Directory Meaning DB2 software (specified during DB2 installation) DB2 instance directory DB2 binaries, ADSM control files, documentation DB2 directories for containers (usually mount-point) DB2 online log directory DB2 offline log directory DB2 temp. storage of log files during roll forward Owner of the objects created on the database R/3 administrator R/3 database instance owner, database administrator DB2ADMIN instance owner /$INSTDIR/db2_06_01/ /db2//db2 /db2//sqllib/bin,adsm,doc,... /db2//sapdata1..N /db2//log_dir /db2//log_archive /db2//log_retrieve UNIX users: sapr3 adm db2 db2as  SAP AG 1999  On UNIX systems, the files that reside on Windows NT in \sqllib are located in directories defined by the hardware vendor/UNIX flavor. For example:  On SOLARIS, it is located in directory /opt/IBMdb2/V6.1.  On AIX, it is located in directory /usr/lpp/db2_06_01/sqllib.  On Linux, it is located in directory /usr/IBMdb2/V6.1.    The diagnostics of the DB2 database are written to directory /db2//sqllib/db2dump. Log files recording the archiving of log files reside in directory /db2//saparch. Log files recording the restoring of archived log files are written to directory /db2//saprest. (C) SAP AG BC535 4-30 R/3 Naming Conventions: Review Tablespace name Directory Path Container name PSAP. container001 PSAP. container002 Prefix PSAP Abbreviation Extension D (data) or I (index) PSAP PSAPBTABD Logical layer Physical Physical layer layer Prefix Tablespace name Ext. Meaning PSAP PSAP PSAP PSAP PSAP PSAP PSAP PSAP PSAP PSAP PSAP PSAP PSAP SYSCATSPACE TEMP USER1 EL ES LOAD SOURCE DDIC PROT CLU POOL STAB BTAB DOCU D or I D or I D or I D or I D or I D or I D or I D or I D or I D or I D or I D or I DB2 Data Dictionary Sort Processes, temp tables, reorg Default tablespace Development environment loads Development environment sources Screen and report loads (ABAP) Screen and report sources (ABAP) ABAP Dictionary Log-like tables (for example, spool) Cluster tables Pool tables (for example, ATAB) Master data and transparent tables Transaction data, transparent tables Documentation, SAPscript, SAPfind Used by DB2 RDBMS DB2 RDBMS DB2 RDBMS R/3 Basis R/3 Basis R/3 Basis R/3 Basis R/3 Basis R/3 Applications R/3 Applications R/3 Applications R/3 Applications R/3 Applications R/3 Applications  SAP AG 1999  The DB2 database uses tablespaces. From a logical point of view, a tablespace holds database objects, such as tables and indexes. On disk, a tablespace consists of one or more data files, called containers. The capacity of a tablespace can be increased by adding containers to it. The R/3 naming convention for tablespace names is PSAP. The abbreviations in the tablespace name are part of the container name. Containers are numbered starting with 000. A full path specification for a DB2 container for R/3 System C11 would be:  /db2/C11/sapdata1/PSAPBTABD.container002 (UNIX)  h:\db2\C11\sapdata1\PSAPBTABD.container002 (Windows NT)    Note: The R/3 System and SAP tools (such as SAP DB2admin tools) require that the naming conventions be observed. Following the R/3 naming convention ensures fast and efficient support by SAP. (C) SAP AG BC535 4-31 OS/Database Users and Authorities OS/DB users sapr3 adm db2 Description Owner of database tables and indexes used by the R/3 applications. Has no privileges to perform database administration. R/3 instance owner. Can perform database administration such as startup, shutdown, and backup. Has no privileges to access database tables. Database instance owner and database creator. This is the DB2 superuser. Has all privileges for database administration and connect. Description Database owner. Can perform database administration. Has privileges to access all database tables. Can perform database administration. Has no privileges to access data in the databases (highest level of system control authority). Can perform database administration. Has no privileges to access data in the databases (second level of system control authority). Description Connection can be made by users of the SYSCTRL group. Connection using user name and password. Database authority SYSADM SYSCTRL SYSMAINT Connect request Implicit Explicit  SAP AG 1999   The following database authorizations are important for performing database administration tasks in the R/3 environment. With DB2, they are implemented as operating system groups. SYSADM is the highest level of administrative authority. Users with SYSADM authorization can run utilities, issue database and database manager commands, and access the data in any table in any database within the database manager instance. This authorization can control all database objects in the instance, including databases, tables, views, indexes, table spaces, node groups, buffer pools, event monitors, and more. SYSADM is assigned to the operating system group specified by the configuration parameter SYSADM_GROUP. Only a user with SYSADM authorization can perform functions such as Change database manager configuration or Grant DBADM authority. Note: User db2 has SYSADM authorization. SYSCTRL is the highest level of system control authority. Users with SYSCTRL authorization can perform maintenance and utility operations against the database manager instance and its databases. These operations can affect system resources, but they do not allow direct access to data in the databases. System control authorization is designed for users administering a database manager instance containing sensitive data. SYSCTRL authorization is assigned to the group specified by the configuration parameter SYSCTRL_GROUP. Only a user with SYSCTRL authorization (or higher) can force users off the system, create or drop a database, create/drop/alter a table space, or restore a new database. Users with SYSCTRL authorization also have the implicit privilege to connect to a database. Note: User adm has SYSCTRL authorization. SYSMAINT is the second level of system control authority. However, SYSMAINT is not used in the R/3 environment.   (C) SAP AG BC535 4-32 Roles of DB2 Database Administrative Users  Privileges required for SAP DB2admin actions such as backup and log archival:  Restricted database administration through SYSCTRL group membership DB2 users for R/3 in a UNIX environment OS user db2 adm OS group SYSADM SYSCTRL Database privileges Full R/3 database administration Restricted database administration  SAP AG 1999   To protect data and resources, DB2 uses a combination of external security services and internal access control information. During the first step, called authentication, the user must identify herself/himself. This is done by issuing an operating system user and the appropriate password when connecting to the database. DB2 verifies the given combination using operating system services. During the second step, called authorization, the database manager decides if the user is allowed to perform the requested action or to access the requested data. There are two types of permissions recorded by DB2: privileges and authority levels. Authority levels provide a method of grouping privileges and control maintenance and utility operations. Both users db2 and adm have sufficient authorization to perform DB2 administration in an R/3 System. The database administration tool SAP DB2 Admin Extensions requires the restricted database administration privileges available in the group SYSCTRL. SAP DB2 Admin Extensions only have access to the tables required for performing R/3 database administration in the background and to tables that reside in the administration database ADM. These privileges are assigned during R/3 installation or upgrade.     (C) SAP AG BC535 4-33 Data Security: DB Access Passwords Database server R/3 application server   De-crypt using KEY R/3 work process Connect as sapr3 using de-crypted password DB2 DB2DB6EKEY =XXXXXXX  Read dscdb6.conf  Authenticate user at the operating system level dscdb6.conf  SAP AG 1999  An R/3 work process connects to the database by retrieving an encrypted password from file dscdb6.conf. The R/3 work processes, which are started by user adm, use this password to connect to the database as user sapr3. If the password at the operating system level is changed, file dscdb6.conf will not be synchronized, and R/3 will not start. To check for this error, enter command R3trans -d as user adm. To change the password of user sapr3 and user adm, you can perform the following:  For UNIX: As user adm, use dscdb6up adm dscdb6up sapr3  For NT: As user adm, use dscdb6up.exe adm dscdb6up.exe sapr3  For BOTH: Use the SAP DB2 Admin Password management extension.   (C) SAP AG BC535 4-34 Unit Summary Now you are able to:  Explain the basic concepts of the DB2 UDB database server  Name the important database directories and their content  Start and shutdown the DB2 UDB database  Identify the operating system users and their DB2 UDB authorizations  SAP AG 1999 (C) SAP AG BC535 4-35 Unit Actions ?  Do the exercises  Solutions for the exercises  SAP AG 1999 (C) SAP AG BC535 4-36 DB2 UDB Database Fundamentals: Exercises No. 1 2 3 4 5 6 Exercise Start your test database using the DB2 command line processor. Which two methods can you use to start the database? Stop your test database using the DB2 command line processor. Use R/3 to display detailed information about DB2 logging. Find the names of the online log files Which online log files have already been copied by the DB2 logging user exit? Check if your test database is running in LOG RETENTION mode using the DB2 command line processor. Switch on LOG RETENTION mode. Note: For the test databases, we only change the DB2 parameter LOGRETAIN. For your actual R/3 database, you must also change the DB2 parameter USEREXIT. 7 8 9 Check the mode of your test database after changing the parameter LOGRETAIN. Check if your test database is running in LOG RETENTION mode using the DB2 Control Center. Switch off LOG RETENTION mode. How can parameter SYSADM_GROUP grant database administrator privileges to the DBA user db2? Which group on the operation system is configured as DB2's SYSADM_GROUP? Which one as DB2's SYSCTRL_GROUP? 10 11 12 13 14 Check if the passwords of sapr3 and adm are in sync between the file dscdb6.conf and the operating system. List the authorizations for user adm. Get the current DB2 version and find out the applied FixPak. How many I/O servers are configured in your test database? How many I/O cleaner are configured in your test database? (C) SAP AG BC535 4-37 DB2 UDB Database Fundamentals: Solutions No. 1 Solution To start the test database manager (DB2 instance), use command db2start. To start the database with the first connect, use command db2 connect to . To start the database without any database connections, use command db2 activate db . 2 To disconnect and shut down the database, use command db2 terminate. To stop the database without any database connections, use command db2 deactivate db . Note: The command db2 list applications shows the connections to all databases in one DB2 instance. To shutdown the database manager, use command db2stop. To shut down the database manager, even if an application is still connected to the database, use command db2stop force. To kill all databases processes, use command db2stop –kill. 3 Log on to the R/3 System. From the main R/3 menu choose Tools  CCMS  Control/Monitoring  Performance menu  Database  Activity (or use transaction ST04). Then choose Detail Analysis menu  Logging Overview. The names of the online log files are displayed in the lower part of the list. The directory log_archive is displayed in the middle part of the list. To retrieve the database configuration, use command db2 get db cfg for . Check for the value of parameter LOGRETAIN. To change the value, enter command db2 update db cfg for using LOGRETAIN RECOVERY. 7 To check the mode of the database, use command db2 connect to . Check the output of DB2 for the keywords backup pending mode. 8 To check the mode of the database, run the DB2 Control Center using command db2cc, and expand the DB2 database db2 icon. Right click on the database icon and choose Configure. Use the tab Logs to display the relevant parameters. To disable LOG RETENTION, search for the parameter description ‘Retain log files for roll-forward recovery and/or Capture’ or the DB2 parameter LOGRETAIN and click on it, choose the value No, and select OK. 9 The database manager configuration contains the parameter SYSADM_GROUP. This parameter contains the related operation system group. This can be checked by entering the command db2 get dbm cfg BC535 4-38 4 5 6 (C) SAP AG | grep –i group (use the grep command to filter the output) or by using the DB2 Control Center. Right click on the instance db2 icon and select the tab Administration. Search for the parameter description ‘System administration authority group’ and ‘System control authority group’. The related DB2 parameters are SYSADM_GROUP and SYSCTRL_GROUP. 10 Change to user : su – adm. To check the passwords for sapr3, use command R3trans –d. Check if the R3trans returns successfully. To check the passwords for adm. use command dmdb6snp –n -o DBASE_BUFFERPOOL. Check if the dmdb6snp returns successfully. 11 Change to user : su – tcdadm. Since you are logged on with this user ID, enter command db2 get authorizations Note: Direct authorizations must be set by database "grant commands". Indirect authorizations are set by user memberships to DB2’s administration groups. 12 To get the current DB2 version, use command db2level. (The last token displays the FixPak identifier) On Linux, you can also use command rpm –q –a |grep db2 to query the installed file sets. 13 14 To display the number of I/O severs, use command db2 get db cfg for | grep –i num_ioserver. To display the number of I/O cleaners, use command db2 get db cfg for | grep –i num_iocleaner. (C) SAP AG BC535 4-39 (C) SAP AG BC535 5-1 DB2 Cost-Based Optimizer Contents       DB2 UDB Cost-Based Optimizer Calling Explain Explain output Database configuration for CBO Runstats with DMDB6SRP SAP tools for updating statistics Objectives At the end of this section, you will be able to:  Efficiently use the DB2 Cost-Based Optimizer  Perform the necessary system administration tasks to ensure CBO performance  Recognize poor SQL statements  Update the statistics  SAP AG 1999 (C) SAP AG BC535 5-2 Cost-Based Optimizer: Introduction Performance problems Performance problems due to due to 1 1 3 3 Hardware Hardware configuration 2 2 Database configuration Database configuration Application problems Application problems ... Buffer pools Buffer pools Lock storage Lock storage Isolation level Isolation level  SAP AG 1999 ... Expensive Expensive statements statements  Poor database performance is normally caused by poor database configuration, application coding problems, or hardware capacity. To identify and correct performance problems in the first two categories, perform normal tuning in the database monitors as follows:  Check the database configuration (1) - Check whether the buffer pool(s) or lock list are sized correctly, or if I/O operations are concentrated on one or more disks which then become overloaded.  Use the database tools to verify the efficiency of application coding (2) - Check for lock contention or inefficient SQL coding - Check if SQL statements are being executed more frequently than necessary. - Check statements for any of the following high-cost factors: Poor WHERE clauses Missing indexes Fragmentation of data/ indexes on disk - Internal R/3 components might not be using the best possible isolation level. For example, you can use optimistic cluster reads to avoid locks resulting from standard cluster reads.  Consult with your hardware partner if performance problems are due to hardware capacity. (3) (C) SAP AG BC535 5-3 Facts Not Observed by the CBO Non-CBO issues Static behavior Static behavior Dynamic behavior Dynamic behavior Disk Disk RAM RAM Paging Paging ... Thrashing Thrashing Layout Layout  SAP AG 1999 Striping Striping   This graphic shows some of the facts that the CBO does not observe during SQL statement execution. Static behavior is the term used for system behavior based on properties which exist regardless of the existing load on the database server:  Disk behavior - Layout of database containers on disks. Are containers of a tablespace distributed over several disks, all having the same I/O characteristics? The DB2 CBO cannot perform selective I/O based on the container access properties. You can only define characteristics on a per-tablespace level. - Striping properties of the disk subsystem. Read and write operations are not equally expensive in all RAID configuration levels. For example, transfer of data TO a RAID-5 device is more costly than to other RAID levels. The CBO does not know which data has to be written to a RAID-5 device. You should configure other RAID levels for data writes from buffer pools.  RAM - Is all the installed RAM available to the DB2 processes running on the database server? Since DB2 maintains its own buffering with the buffer pools, you should check whether a certain amount of RAM is used unnecessarily on the operating system level for buffering file system I/O,.  Dynamic behavior is the term used for system behavior based on properties that become apparent during high load on the RAM, I/O, and CPU resources of the database server. For example, if the system is paging heavily, the CBO may waste system resources by using a large buffer pool. BC535 5-4 (C) SAP AG  For each SQL statement, the DB2 CBO tries to determine the most effective strategy for retrieving or manipulating database data. The access strategy used depends on many factors, such as:  Queried table data content (or tables, for a VIEW or JOIN)  Fields specified in the WHERE clause of the SQL statement  Indexes defined for the tables queried  Database statistics  The CBO computes the cost of data access strategies, and chooses the least costly, according to the cost-model defined. For this, the optimizer requires up-to-date statistical information about the tables and indexes of the database. Statistical information for a table or index is stored in the DB2 data dictionary. To collect the statistical information, the DB2 command runstats is executed in a special R/3 executable. Note: The runstats command is expensive, since it performs I/O. Schedule this job at times of low system load. Table and index sizes, and value distributions can change. If the current number of rows of a table differs greatly from the values determined by the last runstats run, the optimizer may choose an ineffective strategy and the database access time becomes longer. You should refresh the optimizer statistics at least once a week.    (C) SAP AG BC535 5-5    The access path for a statement results into an execution plan. This execution plan can be displayed in a readable format. Once an execution plan is created, DB2 caches it to be able to reuse it and to save the create time for an execution plan (also called prepare time). DB2‟s CBO estimates the most efficient way to retrieve data by:  Considering data volume and distribution, which are subject to continuos changes  Finding the right balance between CPU-based and I/O-based operations  Searching through the possible execution plans to find the least expensive one   DB2‟s CBO considers how much time it takes to get the plan. The Query Graph Model provides a formalism for transforming incoming SQL into a mathematically sound representation that can then be manipulated using well-defined optimization techniques while preserving the semantics of the original SQL. (C) SAP AG BC535 5-6 DB2 CBO: SQL Explain SQL statement text Execution plan  SAP AG 1999  The execution plan contains all the necessary data to be able to reproduce (follow) DB2‟s access path. If in doubt, you can start with the analysis of the execution plan to determine if the access path is adequate. You can run the R/3 command Explain using one of the following methods:  Transaction ST05  Transaction ST04  Detailed analysis  DB2 applications  Transaction ST04  Detailed analysis  DB2 SQL Cache  Report RSDB6TTE (cumulative DBSL trace)     Standalone tools, like DB2 Visual Explain, are also available. However, it is not easy to retrieve the statements executed by the R/3 System using these tools. The statement in this example has a very costly execution plan. You can prevent the CBO from using table scans by using indexes and well qualified WHERE clauses. The above SQL Explain Function in R/3 is available as of R/3 Release 3.1H. (C) SAP AG BC535 5-7 Understanding DB2 Explain Output Optimization level budgets query plan search Timerons are a relative cost unit  SAP AG 1999 Read the Explain output from the upper right hand corner   The optimizer search in DB2 UDB is budgeted by the optimization level selected for a query plan determination. The DB2 CBO cost model tries to be accurate but relies on certain assumptions. With optimizer level 0, the optimizer does not exploit statistical information to calculate the access plan. Greedy join enumeration is performed with nested loop joins and index scans only. There is only minimal query rewrites and no consideration of non-uniform distribution in statistics. List prefetch and index ANDing are disabled. Optimizer level 5 is the default setting in the R/3 environment. This enables dynamic programming with optimization effort. Heuristics are used in concert with self-adjusted throttling techniques to selectively apply greedy join enumeration in order to manage the tradeoff between optimization time and plan execution time. The optimizer considers all available statistics, all query rewrite rules, and most access paths. Materialized views and hash join access methods are used with an optimizer level greater than or equal to 5. Timerons are “virtual timing units” that are used as a relative measure of time on the same system. Provided you have two systems that are exactly the same, with the same database configuration parameters, then you may be able to compare the execution cost of the statements between the systems. The DB2 tool db2look is the only way to model the same environment on another system. Estimated costs are accumulated from input (disk), through operations (sorts, joins), to output (fetch).    (C) SAP AG BC535 5-8 Understanding DB2 Details Output The Details output contains additional cost information for each operator  SAP AG 1999   For each operator used in the Explain output, DB2 provides additional information. To display this information, mark an operator and choose Details. To receive a detailed explanation of the inner working model of the CBO, choose Details in an ST05 Explain output. For each Explain output, the details are generated in different parts. (C) SAP AG BC535 5-9 DB2 CBO: Details (1) -----------------------------------------------------------------------------------D E T A I L S -----------------------------------------------------------------------------------EXPLAIN INSTANCE -----------------------------------------------------------------------------------DB2_VERSION: | 06.01.0 SOURCE_NAME: | SQLL38N5 SOURCE_SCHEMA: | NULLID EXPALIN_TIME: | 1999-01-14 18:35:15.467001 EXPALIN_REQUESTER: | SAPR3 -----------------------------------------------------------------------------------Database Context -----------------------------------------------------------------------------------Parallelism: CPU speed [msec/instruciton]: Comm speed: Buffer pool size [4KB]: Sort heap size [4KB]: Database heap size [4KB]: Lock list size [4KB]: Maximum lock list: Average applications: Locks available: | | | | | | | | | | No parallelism 2.4679E-06 0.0000E+00 10.000 512 8.000 3.200 100 1 361.600  SAP AG 1999   This example shows the parameters displayed in the Details screen. EXPLAIN INSTANCE:  DB2_VERSION displays the current database release.  EXPLAIN_TIME shows the time when the Explain was performed.  EXPLAIN_REQUESTER shows the user ID.  Database Context:  Parallelism shows if parallel operations are allowed. Parallel operations are not necessary for standard R/3 Systems, but are good for SAP Business Warehouse Systems.  CPU Speed is the speed of the system determined at installation time of the DB2 instance by executing SPEC-INT style routines.  Buffer pool size is the size of RAM storage for data and index pages.  Lock list size is the size of RAM storage holding lock information. The size of a lock on an object is 64 bytes for the initial lock and 32 bytes for each additional lock on the same object. (C) SAP AG BC535 5-10 DB2 CBO: Details (2) ------------------------------------------------------------------------------------ Package Context -----------------------------------------------------------------------------------SQL type: | Dynamic SQL Optimization level: | 5 Blocking: | Block all cursors Isolation level: | Uncommitted read ------------------------------------------------------------------------------------ STATEMENT SECTION 1 397 | | | | | | 264 Select No No 1 -----------------------------------------------------------------------------------QUERYNO: QUERYTAG: Statement type: Updatable: Deletable: Query degree:  SAP AG 1999   This example shows other parameters that might be displayed in the Details screen. The Package Context displays the optimization level of the package, the blocking type of the cursors, and the isolation level. If a cursor is blocked, more than one row is transferred to the client side communication area to support efficient communication. For each blocked cursor, a memory area is allocated (RQRIOBLKSZ). Since R/3 uses dynamic SQL, each DB2 package has only one section that contains the properties of the statement executed, which are:  Statement type  Updatable  Deletable  Query degree   The Query degree describes the parallelism that has been selected for the statement. For example, if a degree of N is specified, DB2 tries to distribute the execution of the statement onto N agents, all trying to work in parallel. However, with a typical R/3 System workload, this intra-query parallelism is not needed. (C) SAP AG BC535 5-11 DB2 CBO: Details (3) ------------------------------------------------------------------------------------ Original Statement: -----------------------------------------------------------------------------------SELECT TABNAME, TABFORM, REFNAME FROM DDNTT WHERE NOT ((TABFORM = „J‟) AND (TABTYPE = „J‟)) ORDER BY TABNAME ------------------------------------------------------------------------------------ Optimized Statement: -----------------------------------------------------------------------------------SELECT Q1:TABNAME AS “TABNAME”; Q1.TABFORM AS “TABFORM”, Q1.REFNAME AS “REFNAME” FROM SAPR3.DDNTT AS Q1 WHERE ((Q1.TABFORM <> „J‟) OR (Q1.TABTYPE <> „J‟)) ORDER BY Q1.TABNAME  SAP AG 1999    Another part of the Details screen displays the original SQL statement and the result of the query rewrite process, which is performed by the CBO. Query Rewrite applies the common SQL optimization techniques that would be observed by very experienced SQL programmers, and resolves any referenced views. In this example, the De-Morgan theorem is applied: A AND B = NOT(NOT(A) OR NOT (B)) (C) SAP AG BC535 5-12 DB2 CBO: Details (4) --------------------------------------------------------------------------------Access Plan: --------------------------------------------------------------------------------Total cost: | 7.3872E+03 [timerons] Query degree: | 1 ... --------------------------------------------------------------------------------4 ) TBSCAN -------------------------------------------------------------------------------... -------------------------------------------------------------------------------Arguments: -------------------------------------------------------------------------------TABLOCK ROWLOCK PREFETCH SCANDIR MAXPAGES BUFFERS | | | | | | INTENT NONE NONE SEQUENTIAL FORWARD ALL 1720  SAP AG 1999   An important indicator for the performance of a query is the data access method used. In this example, an INTENT NONE table lock ensures that the table is not dropped by other programs during the execution of the statement, and there are no row-level locks involved. The I/O servers are enabled to efficiently read FORWARD on the containers to retrieve an estimated total of 1720 4 KB pages. Note: The complete output of the analysis is located in the exercises for this section. As a general rule, the cost of operations is “pushed” upwards and accumulated in the Explain tree.  (C) SAP AG BC535 5-13 SQL Enhancements Affecting Query Execution SQL statement text SELECT **FROM MARA SELECT FROM MARA WHERE mandt = „001‟ WHERE mandt = „001‟ AND matnr = „1000‟ AND matnr = „1000‟ AND bismt = „0001‟ AND bismt = „0001‟ Access path TBSCAN TBSCAN + OPTIMIZE FOR OPTIMIZE FOR ROWS ROWS Execution plan Select + FETCH FIRST FETCH FIRST ROWS ONLY ROWS ONLY Fetch TBScan SET CURRENT QUERY SET CURRENT QUERY OPTIMIZATION OPTIMIZATION  SAP AG 1999 For more information, refer to SAP Note 150037  OPTIMIZE FOR N ROWS (OFNR)  Optimizer choose the quickest way to return a result with n rows  Does NOT limit the result to n rows, but returns all records which match the query  Changes in the access plan can be: Nested Loop Joins instead of mass join techniques or get sorted records by using an appropriate index  FETCH FIRST N ROWS ONLY (FFNR)  Limits the result to the first n returned rows does not affect CBO decisions  Is not available as a single ABAP hint because it does not affect the decision of the CBO  SET CURRENT QUERY OPTIMIZATION  Changes DB2„s search strategy to find the result set.  As of R/3 Release 4.6A, you can pass hints to the optimizer from ABAP to DB2 UDB using: SELECT * FROM RESB WHERE MATNR = '200-100' AND WERKS = '1100„ %_HINTS DB6 'OPT_FOR_ROWS 15„. SELECT * FROM RESB WHERE MATNR = '200-100' AND WERKS = '1100„ %_HINTS DB6 'USE_OPTLEVEL 0'. Or both SELECT * FROM RESB WHERE MATNR = '200-100' AND WERKS = '1100„ %_HINTS DB6 'USE_OPTLEVEL 0„ DB6 'OPT_FOR_ROWS 15„. (C) SAP AG BC535 5-14 SELECT SINGLE Execution Plans SELECT SINGLE * FROM ... Tran e sferr d SELECT * FROM ... FETCH FIRST ... OPTIMIZE FOR ...  SAP AG 1999  SAP‟s open SQL statement SELECT SINGLE * FROM ... is internally transfered to a DB2 SQL statement using DB2‟s clauses:  FETCH FIRST n ROWS ONLY and OPTIMIZE FOR n ROWS. (C) SAP AG BC535 5-15 UP TO ROWS Execution Plans ... UP TO ROWS ... d ferre rans T SELECT * FROM ... FETCH FIRST ... OPTIMIZE FOR ...  SAP AG 1999  SAP‟s open SQL statement ... UP TO ROWS ... is internally transferred to a DB2 SQL statement using DB2‟s clauses:  FETCH FIRST n ROWS ONLY and OPTIMIZE FOR n ROWS (C) SAP AG BC535 5-16 DB2 Operators DELETE FETCH FILTER GENROW GRPBY HSJOIN INSERT IXAND IXSCAN MSJOIN NLJOIN RETURN RIDSCN SORT TBSCAN TEMP TQ UNION UNIQUE UPDATE Delete Fetch Filter rows Generate row Group by Hash join Insert Index ANDing Index scan Merge scan join Nested loop join Result Row identifier (RID) scan Sort Table scan Temporary table construction Table queue Union Duplicate elimination Update  SAP AG 1999  For more information about the operators of a plan, see Appendix D in IBM DB2 Universal Database, Administration Guide Performance Version 6. (C) SAP AG BC535 5-17 DB2 JOIN Concepts: MERGE MERGE SCAN JOIN Still sorted T1, Column 2 A A B C A A B B T1.C2 = T2.C1 T2, Column 1 A B B 1. Read T1, C2 and scan T2, C1 until same value is found. Then join the rows. 2. Read T2 until the value changes, always joining the rows with the row in T1. 3. Then read next value in T1 and start at the row in T2 which was visited last. 4. If the value matches, join the rows. Otherwise search until T2, C1 matches T1, C2. 5. Continue this process until the end of T1. SORT 1 2 3 1 SORT 2 Table 1  SAP AG 1999 Table 2  Merge join (also known as merge scan join or sort merge join) requires that the columns which are to be merged are sorted. This input may come from data which is received through an index, or which is sorted through other means (temp table). Merge join requires an equality join predicate, such as the predicate “=”. The merge join provides good performance if T2 (above) is large and sorted. This is the case if the rows of T2 are read from an index. Then, the T2 data does not have to fully fit into the buffer pool at once. It can be read through prefetching and does not have to be re-used in the same operation.   (C) SAP AG BC535 5-18 DB2 JOIN Concepts: NESTED LOOP NESTED LOOP JOIN expr(T1.C2) < T2.C1 T1, Column 2 B A B C B A A B T2, Column 1 A B A D Read T1.C2 until end of table T1 Read T2.C1 until end of table T2 if expr(T1.C2) reloop T2.C1 is true join the rows endif end read T2 end read T1 1 2 3 1 2 Table 1  SAP AG 1999 Table 2   The nested loop join can be used by the CBO when a relational operator (=, <, >, <=, >=) is used. It can also be used with expressions based on columns in the left (outer) table. The nested loop join does not need sorted data as input and will not provide a sorted result set. Therefore, it is very efficient. But for large tables, T2 (inner) table must be in the buffer pool to allow efficient operation, or as with DB2 the inner table must be sorted before being used.  (C) SAP AG BC535 5-19 DB2 JOIN Concepts: HASH Hash Join T1.C2 = T2.C1 T1, Column 2 A C B C A C C B B C C T2, Column 1 C B A D C B B C A D 1. Read T2.C1, create entries for all rows into partitions based on the hash code generated from C1. 2. Read T1.C2 and calculate its hash code. 3. Use this code to access the partitions. 4. Within the partitions the columns are compared. If equal, the actual rows are joined. 5. Continue at (2) until the end of T1 is reached. 1 2 3 1 2 Table 1  SAP AG 1999 Table 2   Hash join is a highly efficient join method. It can only be applied with the equality predicate “=” and if the column data types are the same. The Hash Join method uses memory from the sort heap. If the space is not sufficient, it will create temporary tables to hold further hash partitions. These temporary tables reside in the buffer pool, and might spill over into the PSAPTEMP tablespace if they become too large. This is the reason why Hash Joins are not good for very large tables. The CBO will detect this and will use another join method.  (C) SAP AG BC535 5-20  The following major database configuration settings are observed by the DB2 CBO:  BUFFPAGE (determines the size of the buffer pool)  SHEAPTHRES (maximum soft limit for all sortheaps within a database instance)  LOCKLIST (determines the size of the lock list)  CPUSPEED (determines the speed of the CPU during installation)  DFT_DEGREE (determines the default degree for query operations)  AVG_APPLS (determines the share of the buffer pool per application)   For each table and index accessed by the execution plan, the CBO uses statistics collected in the system catalog. For each of the disks used for the containers of accessed tables and indexes, the CBO uses data defined for the tablespaces. (C) SAP AG BC535 5-21 R/3 Tools for Updating Statistics: dmdb6srp Index_1_Table_1 Table_1 Index_2_Table_1 R/3 dmdb6srp (REORGCHK+RUNSTATS) (REORGCHK+RUNSTATS) Table_2 Index_1_Table_2  SAP AG 1999  DB2 RUNSTATS updates the DB2 catalog with statistics information. During RUNSTATS, information about cardinality, number of pages, and record length is collected. If desired, various properties of the indexes are collected as well. The DB2 command REORGCHK is discussed in a later unit. The R/3 implementation of RUNSTATS is called dmdb6srp, and contains an extended set of analysis tools which build on the DB2 RUNSTATS API. dmdb6srp updates R/3 tables DB6IREORG and DB6TREORG, and the DB2 catalog. dmdb6srp uses optimization techniques common to R/3 Systems (DBSTATC), as discussed in a later unit. The DB2 native RUNSTATS does not correctly display the size of tables with long varchar fields. Since R/3 has many tables with columns with this type of field, dmdb6srp calculates the size of these fields as well. For very large tables, you can specify an execution-time limit. After this limit has been reached, the program stops the calculation of the size of the table and estimates the size based on the cardinality and other available data. You can also specify the total execution time of dmdb6srp, after which the program will terminate. It will "know" the tables which have been visited and will start "oldest statistics" first at next invocation. Certain tables must not receive new statistics (for example, VB tables) and are not updated during a RUNSTATS called by dmdb6srp. However, the DB2 native RUNSTATS destroys the statistical configuration of these tables. For this reason, do not run DB2 RUNSTATS with R/3.     (C) SAP AG BC535 5-22     Full database update statistics should be scheduled as need arises. The update of the statistics is performed by the R/3 DB2 CCMS, which uses the DB2 runstats API. Do not enter this command directly. Use the DBA Planning Calendar (transaction DB13) to schedule the statistics update of all tables. You may limit the runtime of the command. Use the CCMS CBO menu (transaction DB20) to run unscheduled updates immediately. (C) SAP AG BC535 5-23 (C) SAP AG BC535 5-24   Using R/3 to update the statistics ensures that not only the DB2 catalog is updated, but also internal R/3 tables that maintain additional information on the database state. The executable dmdb6srp is the interface between the DB2 command runstats and DB2specific R/3 tables. The executable dmdb6srp stores output information from the DB2 commands runstats and reorgchk in R/3 tables. This data is displayed when transaction DB02 is called.  (C) SAP AG BC535 5-25  Only up-to-date statistical information can ensure that DB2‟s Cost-Based Optimizer chooses the optimal access path. However, gathering optimizer statistics is expensive and reduces system performance. To ensure up-to-date statistics for all tables and optimal analysis runtime, SAP has implemented a two-phase strategy:  In the first phase, SAP tools determine which tables require a statistical update. The data collector CCMS_DB6_CT_TUNE determines which database objects have exceeded an update threshold, and modifies the control table DBSTATC accordingly.  In the second phase, the statistics of the tables marked TODO in the control table DBSTATC are refreshed. To do this, use the SAP CCMS DB-Administration and schedule the job: Update Statistics + Reorgcheck (DBSTATC) or run dmdb6srp at the command line.    In phase 1, the CCMS data collector CCMS_DB6_CT_TUNE runs on a daily basis and is triggered by the SAP Alert Monitor background activity jobs. To schedule CCMS_DB6_CT_TUNE on a daily basis, SAP‟s Alert Monitor needs to be activated. To do this, call transaction RZ21 and choose Technical Infrastructure  Method execution  Activate background dispatching. (C) SAP AG BC535 5-26 Refreshing Daily Object Statistics: Phase I SAP CCMS Admin Workplace (Database) Data collection method CCMS_DB6_CT_TUNE g Trig ers Cal ls Function module DB6_ALM_TUNE da Up tes Table DBSTATC Table DB6GSDTBS  SAP AG 1999  To get to the SAP Alert Monitor, choose Administration  CCMS  Control/Monitoring  Alert Monitoring (or call transaction RZ20). Expand the CCMS Monitor Sets and choose SAP CCMS Monitor Templates  Database. Expand the following nodes to get to the update threshold leaf: Database  Performance  Optimizer. According to the properties of the MTE class of update threshold exceeded, you find the data collection method CCMS_DB6_CT_TUNE. This method is triggered on a regular basis to determine the tables for a daily runstats. The data collection method CCMS_DB6_CT_TUNE calls the function module DB6_ALM_TUNE. This function module finds tables that have received an update or write threshold and therefore the table statistics should be updated by the daily runstats job. The DB2 snapshot for tables is used as basis for the daily analysis. Table DB6GSDTBS holds the information about the update and write activity of the tables. Based on the difference between the current number of update or writes and the numbers stored in table DB6GSDTBS, function module DB6_ALM_TUNE is able to determine if the threshold is exceeded or not. The current number of update and write activities are added to the numbers already stored in table DB6GSDTBS to be the basis of the next run of DB6_ALM_TUNE. Table DBSTATC contains all the tables that should not receive statistics updates. In addition, the function module DB6_ALM_TUNE inserts table names and flags those entries for an update statistics. This is based on information in table DB6GSTBS.    (C) SAP AG BC535 5-27  The second phase of the two-phase strategy analyzes those objects that need a refresh of statistical information according to DBSTATC. This is normally a very small subset of all the R/3 tables. This ensures a minimal runtime of the second phase. Only statistics of tables that are marked with new statistics needed in the control table (DBSTATC) are refreshed. The refresh of the DB2 statistics is done by The executable dmdb6srp using the information defined in control table (DBSTATC). After the refresh, the entries in control table (DBSTATC) that were marked as TODO are deleted by dmdb6srp. Control table DBSTATC does not contain only DB6 entries, it also contains entries for other database vendors. Note: With the R/3 default settings, there are are no statistics created for pool and cluster tables.    (C) SAP AG BC535 5-28 Modifying the Algorithm to Update the Statistics  SAP AG 1999   To modify the standard procedure used by SAP for refreshing the optimizer statistics, you can use the CBO control panel (transaction DB21). Set the TODO flag so the next time the statistics are refreshed, new statistics for the newly defined entries will be created. (C) SAP AG BC535 5-29 Summary Now you are able to:  Describe the basic concepts of SQL optimization  Use the SAP tools that access the DB2 CBO  Execute the DB2 Explain command from transaction ST05  Analyze execution plans generated by the DB2 CBO  Explain why the R/3 RUNSTATS replacement dmdb6srp must be used instead of DB2 tools  SAP AG 1999 (C) SAP AG BC535 5-30 Unit Actions ?  Do the exercises  Solutions for the exercises  SAP AG 1999 (C) SAP AG BC535 5-31 DB2 UDB Cost-Based Optimizer: Exercises No. 1 2 3 Exercise Logon to R/3 and enable the tracing of your own transactions. Open another mode and call transaction ST04. Stop tracing your own transactions. Call DB2 Explain on an arbitrary SQL statement from within the SQL Trace you have listed. Explain the following single SQL statement using the SQL Trace: SELECT * FROM MARA What is DB2’s estimated cost for executing this statement? 4 5 6 7 You are only interested in the column MATNR of the statement. How would you change the SQL statement? Call DB2 Explain on the new statement. What is the difference between the old and the new execution plan? What is the name of the DB2 utility used to update the DB2 catalog with new statistics? Explain why the standard DB2 tool should not be used in an R/3 environment. What is the name of the SAP utility used to perform the same actions? Call transaction DB20 to update the statistics of table MONI, but only if it is necessary. List the tables that will be treated as “special” by SAP’s CBO tools (either because they should receive daily updates or because they are excluded from RUNSTATS). What is the ACTIVE flag setting of VBDATA? 8 9 (C) SAP AG BC535 5-32 DB2 UDB Cost-Based Optimizer: Solutions No. 1 Solution To enable the tracing of your own transactions, log on and call transaction ST05. To enable the SQL Trace, choose Trace On. Call transaction ST04 by entering /oST04. To stop the trace, choose Trace Off. 2 3 Select an SQL statement and choose Explain. It is not possible to explain all rows. Operations such as “CLOSE” are not explainable. Call transaction ST05 and select Explain one SQL Request. Enter the SQL statement and choose Save. In the execution graph, you will see the total calculated cost as a number in exponential format. 4 5 6 7 Change the statement to the following: SELECT MATNR FROM MARA WHERE MANDT=’001’ MATNR is part of the index MARA~0 (primary key). The access to the data is now index-only. RUNSTATS is used to update the DB2 catalog with new statistics. SAP’s dmdb6srp program is used to call the DB2 API for RUNSTATS and REORGCHECK. It should be used because: It is more accurate for calculating the size of tables with long fields. It will terminate after a specified runtime. It will make sure that statistics for tables, which might be very large, will not be reduced only because there is currently no data in the table. It will update information in the tables DB6TREOG and DB6IREOG. These tables are used for CCMS reorganization analysis. 8 To update the statistics, call transaction DB20 and enter MONI. Press Count Total number of rows to display the current cardinality. If there is a difference, choose Refresh statistics. To list the tables, call transaction DB21. Choose Position and enter VBDATA. The values should be N, or R, but never A. With values N or R, the table will not receive updates though SAP’s runstats. 9 (C) SAP AG BC535 5-33 (C) SAP AG BC535 6-1 DB2 UDB Tool Environment Contents:  Tools for managing DB2 UDB databases Objectives: At the end of this unit you will be able to:  Use the DB2 Control Center  Install SAP‟s DB2Admin Extensions  Use the DB2 command line processor (CLP)  Utilize the most common DB2 CLP commands  Describe important DB2 tools  SAP AG 1999 (C) SAP AG BC535 6-2  The administration infrastructure of R/3 Systems in the DB2 environment contains: the DB2 administration server, the SAP DB2 instance, further SAP and DB2 standalone executables, and the graphical DB2 Control Center. The DB2 Control Center - and its SAP extensions - provides a graphical interface for the administration of the DB2 databases and instances. The DB2 Command Center and DB2 Script Center provide easy-to-use interfaces to schedule and run tasks on your database. The DB2 Command Line Processor (DB2 CLP) provides a text interface for the administration of DB2 databases and instances. SAP tools and DB2 tools are also available as standalone utilities. These programs are either started by SAP Systems, or are started manually as the need arises. For example, the program used to check DB2 databases for integrity is called db2dart (DB2 database analysis and repair tool). Most of the administrative tasks on a database server are started by the DB2 administration server, also known as the DB2 administration instance. It allows the remote and local control of the DB2 instances installed on a server system. This means, without the administration server, DBAs would not be able to remotely start and stop the SAP DB2 instance.     (C) SAP AG BC535 6-3  The administration database is available for all R/3 Releases on DB2 UDB. While using a second database sounds complicated, there are compelling reasons why it is used: • All client systems in the network can connect to the centrally kept administrative information, without the need to access remote file systems of the database server. • Authentication is available through DB2. • The administration database is in the same DB2 instance as the R/3 database. Data can easily be exchanged between both databases. • If the R/3 database is down for maintenance or if an R/3 database recovery is necessary, the administration database, which contains vital recovery data, is still available. • The administration database can easily be recovered, since a backup of the administration database is included on each log file archive tape. (C) SAP AG BC535 6-4  After installing the R/3 System, data is copied from the administration database to the SAP database by scheduling a copying process using the executable sddb6mir. You should schedule the following command on an hourly basis:  sddb6mir –m  The administration database is backed up as soon as the log files are archived to tape. Each backup of the archived log file contains a current backup of the administration database. If required, you can restore the administration database using either of the following:  Restore the admin db image from tape using the option brrestore -ex  Restore the admin db from the R/3 database using the option sddb6mir -r Option 1 (brrestore -ex ) can always be performed. Option 2 (sddb6mir -r ) can only be used if the R/3 database is available, and only if the DBA has enabled the copy process. Since this process only runs on an hourly basis, the administration data in the SAP database is not always up-to-date and should therefore not be used if option 1 is available.   (C) SAP AG BC535 6-5 Installing the Admin Database and Server Tools  The following objects must exist in the SAP DB2 Admin environment:     Admin database ADM Admin tables DB6... Stored procedure sddb6das on the server SAP tools on the server, such as BRARCHIVE, BRRESTORE, and db2uext2  The administration database and all the administration tools on the server are automatically installed during R/3 installation  To manually install the SAP‟s R/3 DB2 extensions, use sddb6ins  SAP AG 1999  To install the SAP DB2admin objects on the server, run program sddb6ins -h. This program is usually run during SAP software installation. The sddb6ins program requires you to enter the SAP Release of the R/3 System to be administered. If you are going to administer multiple R/3 Releases, you must repeat this procedure for each R/3 Release. Program sddb6ins -h. is also used during an R/3 Release upgrade. During the upgrade, you must specify the start and the target release of the upgrade. It will remove old programs, install new executables, and adapt database structures to the new SAP Release. The administration database is also created during the installation of the extensions.    (C) SAP AG BC535 6-6  For graphical administration of the DB2 databases, you must install the DB2 UDB administrative tools. These tools are contained in various DB2 software packages, such as the DB2 UDB Personal Edition Package. After installation, you may start the DB2 Control Center using the command db2cc. On NT, you can also start the program using Start  Programs  DB2 for Windows NT  Control Center. There is always exactly one database administration server (DAS) installed per physical server system. The DAS allows the remote-control of tasks, such as:  Remote configuration of DB2 databases and instances  Planning and scheduling of jobs operating on DB2 databases  Remote operations on DB2 databases and instances     The administration database is used to integrate SAP-related data into the DB2 Control Center using SAP‟s DB2 Admin Control Center Extensions. To retrieve configuration parameters for the DB2 administration server, use command db2 get admin cfg. To obtain the name of the DAS on your UNIX server, use command dasilist. To obtain the name of the DAS on your NT server, use the command db2admin.  (C) SAP AG BC535 6-7  DB2 Version 6 offers a JAVA-based GUI for database administration. It requires JDBC support on the database server. Either directly, or through these programs, the GUI talks to the DB2 administration server with administrative requests. To start the JDBC daemon on UNIX, you can either start the daemons directly (issue db2jd) or use command db2jstrt, which returns after forking the daemons. To do this, enter:  db2jstrt 6789 (6789 is the default port number, which is used if db2jstrt is started without a port number) - for the JDBC network driver  db2jstrt 6790 - for the JDBC Control Center Driver  Add the script rc.db2 to the inittab to start the JDBC daemons during reboot     On Windows NT, these services are integrated into the NT service manager with the DB2 JDBC Applet Server and the DB2 JDBC Applet Server - Control Center services. The DB2 administration server always listens to requests from the DB2 Java daemons using TCP/IP port 523. You can run the Control Center as a Java application or as a Java applet through a Java enabled web browser. In both cases, you need a supported Java Virtual Machine (JVM) installed on your workstation to run the Control Center. SAP‟s DB2 admin extensions are not available to run as Java applets. This is, because the SAP extensions are running using DB2‟s JDBC Application Driver out of performance reasons.  (C) SAP AG BC535 6-8 Control Center: Installation  To install the administrative client software on a PC, use the software provided on the R/3 RDBMS CD  Run the R/3 installation program db2setup on the PC  To install SAP‟s R/3 extensions, unpack the package DB6CCEXT.CAR (DB6CCEXT.SAR), then run:   NT: Setup UNIX: Install  SAP AG 1999  The DB2 Control Center is part of DB2 UDB for all released platforms. Make sure that your Java Run Time Environment (JRE) is compatible with the DB2 CC. You can install the Control Center software on all operating systems :  On Win32, DB2 installs a compatible JRE for you  On Linux, ensure you have JRE 1.1.8.2 or higher installed (older JREs will cause some problems)  On all other UNIX platforms, JRE 1.1.7 and higher is acceptable  To install the SAP extensions to the DB2 Control Center, switch to a temporary directory and use the command car to uncompress the file db6ccext.car. As of R/3 Release 4.6C, SAP compression/archiving is provided with SAP‟s new SAR tool. It's invocation is compatible with the old CAR tool. The reason for shipping CAR or SAR files is based on the 8.3 file name convention for SAP‟s CDs. Since files for the installation may have longer file names, they cannot be directly put onto the CDs, they have to be shipped in CAR or SAP archives.  (C) SAP AG BC535 6-9 Control Center: SAP DB2 Admin Extensions  SAP AG 1999  The SAP DB2 Admin Extensions are:  At the instance level - Password management: Choose this item to change the password of the user sapr3 or adm on a system-wide basis. - Option management: Choose this item to modify the configuration database and permanently save settings of the R/3 DB2 admin tool. Up to R/3 Release 4.0, some of these tool parameters were defined in the file /db2//dbs/init.sap. - All values entered using Option management are entered into the administration database.  At the database level - Tape management: Choose this item to define tapes, device classes, devices, and locations. - Log file management: Choose this item to control log files, archive, restore, and user exit. (C) SAP AG BC535 6-10 Control Center: Handling 1 1 2 2 3 3 4 4 5 5  SAP AG 1999    Use the DB2 Control Center to manage systems, DB2 instances, and database objects. All DB2 databases must be cataloged before they appear in the DB2 Control Center. The DB2 Control Center consists of five main elements:  Menu bar: Selecting a menu from the menu bar allows you to perform all functions. (1)  Admin GUI tools in the Control Center toolbar. (2)  Object tree pane: Displays icons for all the database servers and objects that you can administer from the Control Center. (3)  Contents pane: This pane shows all the objects that are contained in the selected object in the object tree pane. (4)  Contents pane toolbar: Allows you to tailor the information in the contents pane. (5) (C) SAP AG BC535 6-11 Control Center: Cataloging of Databases 1 1 System 2 2 Instance 3 3 Database  SAP AG 1999   To catalog a database, you can use the DB2 Control Center or the DB2 command line processor (DB2 CLP). With the DB2 Control Center:  Add a system - provide system name as used for DB2 and the UNIX/NT host name. If the refresh option is used, the Control Center will broadcast into the network and wait for DB2 admin servers on the network to answer and advertise their data. Because of this time delay, the retrieve-option will be faster if the hostname is known.  Add an instance - provide DB2 instance information of the database you want to connect to. This information can be provided by the DB2 admin server.  Add a database - provide DB2 database information manually, or, as retrieved from the DB2 admin server.  With the DB2 CLP, the same steps can be issued as commands:  Add a system: CATALOG ADMIN TCPIP NODE REMOTE REMOTE_INSTANCE SYSTEM OSTYPE NT  Add an instance: CATALOG LOCAL NODE INSTANCE SYSTEM IBMCC50 OSTYPE NT  Add a database:CATALOG DATABASE AS ON (C) SAP AG BC535 6-12 DB2 Command Line Processor C:\SQLLIB\BIN>db2 (c) Copyright IBM Corporation 1993,1997 Command Line Processor for DB2 SDK 6.1.0 You can prompt. db2 db2 issue database manager commands and SQL statements from the command For example: => connect to sample => bind sample.bnd For general help, type: ?. For command help, type: ? command, where command can be the first few keywords of a database manager command. For example: ? CATALOG DATABASE for help on the CATALOG DATABASE command ? CATALOG for help on all of the CATALOG commands. To exit db2 interactive mode, type QUIT at the command prompt. Outside interactive mode, all commands must be prefixed with 'db2'. To list the current command option settings, type LIST COMMAND OPTIONS. For more detailed help, refer to the Online Reference Manual. db2 =>  SAP AG 1999    The DB2 command line processor is used to access DB2 without the need to use graphical tools. Experienced administrators can use the DB2 CLP to interface their administration scripts to DB2. The command db2 starts the DB2 CLP. The command quit stops it. The resources associated with the DB2 CLP will not be released until you enter command terminate. You can also use the DB2 CLP to run SQL commands or statements interactively from a shell. For example, db2 “select * from sapr3.svers” can be issued from adm‟s c-shell. However, you should be aware that the shells will perform special operations on wild-card characters. Whenever a wild-card character is used, it has to be in quotation marks. On NT platforms, the command window running the DB2 CLP needs special environment settings. These settings are provided using command db2cmd.exe . Help on major DB2 commands is provided using the help parameter “?”. To display all DB2 commands, enter db2 “?”. To display help on specific commands, enter the command after the “?”. For example, enter db2 “? backup”.    (C) SAP AG BC535 6-13 DB2 CLP: Important Commands 2 2 1 1 C:/> db2stop C:/> db2 (c) Copyright IBM Corporation 1993,1997 Command Line Processor for DB2 SDK 6.1.0 db2=> ? Backup database ..... db2=> reorg table sapr3.svers 2 2 C:/> db2stop  SAP AG 1999  CLP commands are used to control the system interactively. The commands below are grouped by function:  Database manager control: get dbm cfg, update dbm cfg, get admin cfg  Database control: create db, drop db, activate db, get db cfg, update db cfg  Database directory management: catalog db, list db directory  Node directory management: catalog tcp/ip node, list node directory  System commands require a complete DB2 software installation and one DB2 instance. These commands are not executed by the DB2 CLP:  db2start... Start DB2 instance  db2stop... Stop DB2 instance  db2ilist... List instances on the system  db2set... Access DB2 profile registry (C) SAP AG BC535 6-14 DB2 CLP: Architecture C:\>db2 (c) Copyright IBM Corporation 1993,1997 Command Line Processor for DB2 SDK 6.1.0 DB2 database DB2 CLP DB2 backend process DB2 connection Inter-process communication DB2 agent  SAP AG 1999    The DB2 CLP uses a DB2 backend process as the interface DB2. On UNIX systems, this process is called DB2BP in the process overview list. The DB2 CLP does not always communicate with a DB2 agent directly. A DB2 backend process is always used to issue the commands to the database server on behalf of the DB2 CLP. Using this architecture, DB2 connections can also be maintained within UNIX shells or NT command windows. Connect to the database using the command db2 connect to user using . After this command returns, you can execute the shell commands. Also, you can retrieve data using the connection that has been established, such as db2 “select * from sapr3.svers”. With this command, data is retrieved by the DB2 backend process that has been established by the DB2 CLP with the command connect. Remember to terminate your DB2 CLP sessions. Only using the quit command will leave the DB2 backend process up and running. As a worst case, you will not able to shut down your database while these processes are connected. Then, you must force the database instance shutdown using command db2stop force.  (C) SAP AG BC535 6-15 Data Security: DB Access Passwords SAP application server DB2 database server db2 connect to user sapr3 using YYYY R/3 work process DB2 database    Read dscdb6.conf De-crypt password using DB2DB6EKEY Connect as sapr3 using password  Authenticate with user ID sapr3 at the OS level dscdb6.conf Read file /sapmnt//global DB2DB6EKEY=XXXX  SAP AG 1999  An R/3 work process connects to the database by retrieving an encrypted password from file dscdb6.conf. The R/3 work processes, which are started by user adm, use this password to connect to the database as user sapr3. If the password at the operating system level is changed, file dscdb6.conf is out of sync with the information contained in the file, and R/3 will not start. To check for this error, enter command R3trans -d as user adm. To change the password of user sapr3 and user adm, perform the following:  For UNIX: As user adm, use dscdb6up adm or dscdb6up sapr3  For NT: As user adm, use dscdb6up.exe adm or dscdb6up.exe sapr3  For BOTH: Use the R/3 DB2ADMIN Change password option for users sapr3 and adm. As of R/3 Release 4.6C, the executable dscdb6up is shipped with enhanced error messaging functions. You can also use the new implementation on older SAP Releases. To change the password inside the file dscdb6.conf only, use command db6util. In order to write a new dscdb6.conf file, you must rename the old dscdb6.conf file.  db6util -c <adm>     (C) SAP AG BC535 6-16 DB2 Tools to Extract Statistics: db2look Use: • When predefined statistics have been destroyed (APQD, ...) • When CBO must be tricked into specific behavior db2look (extract DDL & stats) CREATE TABLE "SAPR3 "."APQD" ( "QID" VARCHAR(20) NOT NULL WITH DEFAULT ' ', ...... ) Tables and Indexes: • Number of rows • Number of index levels • Number of distinctive values UPDATE SYSCAT.TABLES SET CARD=-1, NPAGES=-1, FPAGES=-1, OVERFLOW=-1 WHERE TABNAME = 'APQD' AND TABSCHEMA = 'SAPR3 '; R/3 Database  SAP AG 1999     Program db2look is used to extract data definition language statements (DDLs) and statistics of a DB2 database. db2look is installed by the DB2 software installation routines, and can be used at the command line by user db2. Using db2look, you can extract DB2 DDLs and statistics for tablespaces, tables, and indexes without exporting the database content. Since the output - even for a single table - contains all necessary database DDLs, the file contains a lot of data. For proper execution, you must edit the file and remove unnecessary statements. (C) SAP AG BC535 6-17 DB2 Utilities: db2look  Program db2look  Is used in the process of moving tables and indexes to another tablespace Saves structures of tables and indexes on the file system level Creates SQL commands for generating statistics entries in the database catalog    SAP AG 1999  Program db2look generates DDL scripts for copying structures of tables and indexes. Execute the following command to get a script containing all the statements for creating all tables, indexes, primary keys, and views (Note: In the R/3 environment, this returns a lot of information):  db2look –d -u SAPR3 –e –o  If you only want to view specific tables, us the–t option (you can specify up to 30 single tables):  db2look –d -u SAPR3 –t ... –e –o  The tables that are copied with db2look are empty, the data must be copied separately using the db2 export utility from the source system and then using the db2 IMPORT/LOAD utility into the target system. Alternatively, data can be selected and inserted using SQL statements. You can use db2look to get the database statistics of a table using:  db2look –d -u SAPR3 –t [-r] –m –o    To create a script to copy statistic entries to tables with the same structure (statistic patches), use option – r to deactivate the RUNSTATS command on the table specified. For detailed information about this program, see SAP Note 102200. (C) SAP AG BC535 6-18 DB2 Utilities: db2dart Physical database consistency check 1 1 2 2 3 3 db2stop db2dart [Option] [Option] ... Check .RPT and DART.ERR  SAP AG 1999  The service tool db2dart is used perform consistency checks of the DB2 database or to research a database error situation, which is reported in directory db2diag.log. This tool must be started by user db2. When you call db2dart, an overview of all options is displayed. If you run db2dart the important messages are written to two log files:  .PRT, which contains the result of the examination  DART.ERR, which contains the return codes     If db2dart reports no errors, you will find a success message at the end of .PRT The important db2dart options are:  /DB Inspects entire database (default option)  /T Checks a single table  /TS Inspects a single tablespace and the tables within  For further information about the db2dart service tool, see SAP Note 98524. (C) SAP AG BC535 6-19 Unit Summary  Now you are able to:  Administer your DB2 UDB databases using the DB2 Control Center and the DB2 command line processor  Install the DB2Admin Extensions  Catalog remote database instances and databases  Use the db2look and db2dart tools  SAP AG 1999 (C) SAP AG BC535 6-20 Unit Actions ?  Do the exercises  Solutions for the exercises  SAP AG 1999 (C) SAP AG BC535 6-21 DB2 Tool Environment: Exercises No. 1 2 3 4 5 Exercise Start the DB2 Control Center and select the DB2Admin Extensions. How many Database Administration Servers (DAS) are installed on the server? How many JDBC daemons are running? Check if the installed Java version is at least 1.1.8 Which minor version of the Java runtime environment is installed? Which command must be scheduled to mirror the administration database into the SAP database? Which command can be used to rebuild the administration database out of the SAP database? Check if a mirror job was scheduled. 6 7a Determine the values of the following database manager parameters: NUMDB and INTRA_PARALLEL. Change the following database parameters in your test database: DBHEAP = 4000 BUFFPAGE = 2500 7b Change the following database manager parameter in your test database using the DB2 Control Center: NUMDB = 10 8 9 10 11 Assume you received the database error SQL01072N, how could you get more information on this? Which DB2 profile registry values are set on an instance level? How do you update the database statistics for a table in an R/3 environment? Update the R/3 table SVERS. Create a file that contains all database statistics for R/3 table MONI. (C) SAP AG BC535 6-22 DB2 Tool Environment: Solutions No. 1 Solution To start the DB2 Control Center, use command db2cc. To get to the R/3 Option Management and R/3 Password Management, right click on the db2 instance icon. To get to the R/3 Tape Management and R/3 Log File Management, right click on the database icon. 2 To display the amount of servers, use the following commands: dasilist (on UNIX) db2admin (on NT) 3 To check the daemons, use command ps –ef | grep db2jd. Note: You can start the JDBC daemons either by using command db2jd or by using command db2jstrt. 4 To check the installed Java version, use command jre –de. To check the minor version, use command rpm –q –a |grep –i java. 5 To mirror the administration database into the SAP database, use command sddb6mir –m . To rebuild the database after a crash, use command sddb6mir –r ADM . To check if a mirror job was scheduled, log on to R/3 and call transaction SM37, use a job name MIRROR_ADMIN_DB. 6 To determine the values of the database manager parameters, you can either Use command db2 get dbm cfg, or Log on to the R/3 System, call transaction DB03 and choose Active Parameters 7a To change the database parameters, use the DB2 command line processor, and issue command db2 “update db cfg for using dbheap 4000 buffpage 2500”. To change the database manager parameter using the DB2 Control Center, enter db2cc. Select the database instance icon db2. Right click on the icon and choose Configure, select tab Environment. Search for the parameter ‘Maximum number of concurrently active databases’ or the DB2 parameter NUMDB. Enter the value 10, and choose OK to save your settings. To get more information, use the DB2 command line processor, and enter command db2 “? SQL01072N”. To check the profile registry values, use command db2set –i. To update the database statistics for table SVERS, log on as user adm su - adm, and issue command dmdb6srp –n -t BC535 6-23 7b 8 9 10 (C) SAP AG sapr3.svers. 11 To create this file, log on as adm: su - adm and issue command db2look –d -u SAPR3 –t MONI –m –o . (C) SAP AG BC535 6-24 (C) SAP AG BC535 7-1 Backup and Log File Management Contents:  Backup strategies for databases and log files  Different aspects of data safety  DB2 backup architecture  R/3 and DB2 backup tools  Online and offline backups Objectives: At the end of this unit, you will be able to:  Define your backup requirements  Understand the importance of file system management and database redundancy  Know which tools to use and which objects require backing up  Describe online and offline database backups as well as offline log file archiving  SAP AG 1999 (C) SAP AG BC535 7-2 Defining Your Backup Requirements Expected data volume Consequences of data loss Maximum downtime service level agreements Size of backup window Protection against hardware failure Integration with enterprise backup policies Organization, test and escalation plans Protection against logical errors  SAP AG 1999    External factors, physical errors, and logical errors can cause system downtime and may lead to data loss if you do not have a suitable backup strategy. Your backup strategy must be designed according to the needs of your company. A self-assessment regarding the criteria mentioned above should be performed prior to implementation considerations. To ensure the availability of your R/3 System, the backup strategy developed by your database administrator must be carefully tested before your R/3 System goes live, and validated after any changes to your backup strategy or infrastructure. As a basis for successful problem handling, you should create documents containing organizational descriptions of procedures and an escalation plan. These documents must be available and understood by the persons in charge of database restore and roll forward. Since most enterprises have developed backup and restore policies, the SAP and DB2 UDB backup strategy has to comply with both the existing infrastructure and regulations.   (C) SAP AG BC535 7-3 Aspects of Data Safety: Separating File Systems DB2 container Online log files Operating system swap/page files /db2//sapdata1 ... /db2//log_dir /db2//sapdata /db2//log_archive Offline log files  SAP AG 1999  A well-designed disk layout ensures minimal impact of data loss due to hardware errors as well as well-performing system operation. The following rules should be obeyed for reasons of performance (P) and safety (S). Separate the operating system directories (especially the paging or swap files/devices) from all database directories. (P) Since the database logging requires intensive and synchronous I/O whenever the database log buffer is flushed, it is recommended to have the online log directory on isolated disks. (P) If the online log directory is lost, a restore and roll forward will occur. In this case, it is crucial that as many offline log files as possible are still present to prevent unnecessary data loss. This goal can be achieved by separating online and offline log files onto different physical devices. (S) If database containers are lost, a restore and (in most cases) a subsequent roll forward are necessary. In order to be able to reapply all transactions, both online and offline log directories should be separated from the container devices. (S) Further aspects of a well-performing disk layout is discussed in the Storage Management unit.      (C) SAP AG BC535 7-4 Aspects of Data Safety: Redundancy Reducing the risk of a restore or data loss by mirroring Database Containers sapdata1, ..., n Online log files log_dir Configuration files instance directory Offline log files log_archive Should be mirrored using hardware or operating system to reduce the risk of a restore Must be mirrored by hardware or operating system Must be mirrored by hardware or operating system Should be mirrored by hardware or operating system to reduce the risk of data loss  SAP AG 1999  As part of your backup strategy, you must consider the consequences of losing specific database components and you must take appropriate measures to reduce these risks:  If database containers are lost, the database (or at least the tablespaces affected) have to be restored. To minimize the risk of losing a container, you should mirror the directories containing the DB2 containers (For UNIX: /db2//sapdata, for NT: \db2\\sapdata).  If an online (active) log file is lost, severe database problems will occur, and you will eventually have to restore the database. Since all the transactions cannot be reapplied after such a restore, data loss is unavoidable. Therefore, you must provide redundancy for the online log directory. (UNIX: /db2//log_dir, NT: \db2\\log_dir).  The same problems occur if database configuration files are lost. Again, redundancy of the instance directory/file system is advised. (UNIX: /db2//db2, NT: \db2).  If an offline log file is lost, the ongoing database operation is not directly affected. However, in case of a restore, the database cannot be rolled forward to its latest consistent state. (And an immediate database backup is mandatory if a loss of an offline log file is detected). To prevent this data loss, you should mirror the offline log files.  Since there are no reliable mirroring techniques provided by DB2, mirroring should be performed either by operating system means (such as by logical volume manager capabilities) or hardware components (such as RAID1 or RAID5). (C) SAP AG BC535 7-5 Data Backup Objects Database backup DB2 configuration files DB2 BACKUP DB2 container(s) Offline log file(s) BRARCHIVE Online log file(s) R/3 data ... R/3 archiving ... Interfaces ... SAP executables  SAP AG 1999 Computing center data ??? Operating system information  To correctly implement your database backup strategy, you must know which objects are backed up and which tools are used:  If you use the DB2 backup utility, the databases are backed up under control of the DB2 instance. DB2 backup processes create backup images that contain both the database‟s data and the contents of the database configuration files. Please note that this backup image does not consist of a copy of container and configuration files, but rather their contents.  To back up the offline log files from the log_archive directory/file system, we use a non-DB2 tool called BRARCHIVE. BRARCHIVE has been implemented jointly by IBM and SAP, and reflects the SAP-specific environment.  As you can see, online log files are not backed up (by DB2 BACKUP or BRARCHIVE). Filled log files are immediately copied by the DB2 logging user exit to the log_archive directory/file system and can be backed up at this point in time. (Note that this concept relies very much on mirrored devices for the online log directory.)  R/3 data is not backed up with DB2 tools or BRARCHIVE. You have to use operating system tools to do this. (C) SAP AG BC535 7-6  It is important to understand that DB2 database backups are performed under the control of the DB2 instance. Because of this architecture, the DB2 backup utility will only read the contents of the objects that need to be backed up (rather than backing up files on the operating system level). Both the contents of the containers for the specified tablespaces and the configuration information (such as the container location, sizes, and database configuration values) are read by the utility and written into a DB2-specific backup image. The backup image may reside on disk devices, tape drives, or may use advanced storage solutions like Tivoli Storage Manager or Legato Networker. Each backup image created is identified by a unique timestamp. A corresponding entry is logged into DB2‟s backup and recovery history file.    (C) SAP AG BC535 7-7 DB2 Recovery History File Recovery history file:         Database or tablespace backup Database or tablespace restore Database or tablespace roll forward Tablespace alteration Tablespace quiesce Table load Table reorganization Table statistics update System System Database, DB server Database, DB server Day, Time Day, Time Operation type: Operation type: First log file: First log file: Last log file: Last log file: No. of Tablespaces: No. of Tablespaces: Tablespaces: Tablespaces: Location: Location: BUD BUD DB6 is0005 DB6 is0005 21.02.2000 20:30:08 21.02.2000 20:30:08 ONLINE ONLINE S0000903.LOG S0000903.LOG S0000906.LOG S0000906.LOG 21 21 SYSCATSPACE SYSCATSPACE PSAPBTABD PSAPBTABD ... ... PSAPUSER1I PSAPUSER1I /db2/BUD/sqllib/lib\ /db2/BUD/sqllib/lib\ /libxbsa.a /libxbsa.a DB2 Backup Image Backup information Recovery history Data • • • Log file information  SAP AG 1999  The summarized backup information in the recovery history file can be used to recover all or part of the database to a given point in time. The information in the file includes:  The part of the database that was backed up and how  The time the backup was made  The location of the backup data (the device information and the logical way to access the data)  The last time a restore was performed  Every backup operation (tablespace and full database) includes a copy of the recovery history file. The recovery history file is linked to the database. When a database is dropped, the recovery history file is deleted. Restoring a database to a new location restores the recovery history file. When a database is restored, the existing history recovery file is not overwritten. If the current database is unusable or not available and the associated recovery history file is damaged or deleted, an option on the restore command allows only the recovery history file to be restored. The recovery history file can then be reviewed to provide information about which (earlier) backup to use to restore the database.  (C) SAP AG BC535 7-8 DB2 Backup Types: Offline Backup SAP GUI .... .... ______________________ ______________________ ______________________ ______________________ .... R/3 instance SPO WP BTC WP BTC WP DIA WP DIA WP Dia WP Offline backup Performed by DB2 instance DB2 instance -- Database is not available + Backup image is consistent + (No logs are required for recovery)  SAP AG 1999  The first type of DB2 backups is the offline backup. To be able to perform this backup, no application can be connected to the database. The DB2 backup utility creates the backup image and does not allow any new connections during the course of the backup. Offline backups are always consistent because the backup images are read from a consistent database state with no ongoing transactions. To preserve the buffer qualities of R/3 application server buffers, the R/3 System may remain running during the time of the backup. However, all work processes are disconnected from the database and remain in a reconnecting state. That is, they are not operational to end users during the time of the backup. After the backup is complete and the database is available again, these processes reconnect to the database if they are triggered by user or system action.   (C) SAP AG BC535 7-9 DB2 Backup Types: Online Backup SAP GUI .... .... ______________________ ______________________ ______________________ ______________________ .... R/3 instance SPO WP BTC WP BTC WP DIA WP DIA WP Dia WP Online backup Performed by DB2 instance DB2 instance + Database is available + -- Backup image is inconsistent (Logs are required for recovery)  SAP AG 1999   The second type of DB2 backups is the online backup, which is performed by the DB2 backup utility in parallel to ongoing activities of database applications, such as R/3 work processes. Since transactions are executed during the runtime of an online backup, the backup image created cannot reflect a consistent state of the database. In case of a restore of an online backup, all changes that occurred during the time of the online backup have to be reapplied or rolled back (depending on the commit or rollback of the corresponding transaction). Therefore, it is absolutely necessary to be able to provide all the log files that were written during an online backup in order to obtain a consistent state using a roll forward operation. Since R/3 operation continues during online backups, system availability is increased while high application server buffer qualities are maintained. Note: DB2 can only perform online backups if your database is operating in LOG RETENTION mode.    (C) SAP AG BC535 7-10 Backup Strategies: Tablespace Level Backups ... DB2 tablespaces DB2 configuration files PSAPBTABD PSAPUSER1D ... PSAPUSER1I PSAPSTABI DB2 backup utility DB2 backup on tablespace level: + + + + Reduces backup time A complete logical database backup can be performed incrementally Recovery window may be an issue Restore activities become more complex Backup image ---  SAP AG 1999   The DB2 backup utility supports backups on a tablespace level. This feature can be used, for example, after tablespace extensions. Problems might arise if you perform partial backups of a database by backing up the first group of tablespaces during one night and the second group of remaining tablespaces during the second night since you may not be able to restore the complete database within the maximum time frame. However, with the DB2 backup utility you can selectively restore a group of tablespaces from a full database backup image. This feature will be discussed in detail in the Restore and Recovery unit.  (C) SAP AG BC535 7-11 R/3 and DB2 Database Backup Tools Option 1: DB2 command line processor (CLP) 1a. On demand C:\SQLLIB\BIN>db2 backup database TC1 online to \ d:\backups, e:\backups, f:\backups, g:\backups, h:\backups\ with 6 buffers parallelism 3 Backup successful. The timestamp for this backup image is: 200002191542209 1b. Scheduled regularly using scripts UNIX: /db2//batch/brdb6bucron.ksh Stops R/3, performs DB2 offline backup, then restarts R/3  SAP AG 1999  There are three ways in which you can back up a DB2 UDB database. The first option uses the command line interface DB2 CLP. There are two ways to use the command line processor:  As shown in example 1a., you can directly issue a DB2 backup command out of a CLP session. If you are not too familiar with the syntax of the utility, you can obtain help by issuing command db2 “? backup”  As shown in example 1b., you can use crontab (available on UNIX platforms only) to schedule offline database backups using the script /db2//batch/brdb6bucron.ksh: - First, the script will stop the R/3 System. - Then the DB2 backup utility will be invoked to perform an offline backup of your database. - Finally, the R/3 System is restarted.  This utility is quite useful for scheduling offline backups, for example, during the weekend. (C) SAP AG BC535 7-12 R/3 and DB2 Database Backup Tools Option 2: DB2 Control Center  SAP AG 1999  The DB2 UDB database can also be backed up using the graphical user interface, DB2 Control Center:  If you use the DB2 Control Center, backups can be started immediately or scheduled using the script center. (C) SAP AG BC535 7-13 R/3 and DB2 Database Backup Tools Option 3: R/3 DBA Planning Calendar (DB13)  SAP AG 1999  The R/3 System provides the third way to perform DB2 database backups, which is suitable for online backups:  If you use the CCMS DBA Planning Calendar (transaction DB13), you can conveniently schedule periodically executed online database backups. (C) SAP AG BC535 7-14 ADM Backup Tools R/3 database Containers Admin database ADM Database configuration Online log files Mirroring with sddb6mir -m 1. 1. Implicit Transfers table entries created after last execution of sddb6mir into R/3 tables 2. 2. Explicit Each log file archival by brarchive will backup the contents of ADM  SAP AG 1999  There are two ways you can back up the contents of the admin database ADM:  Implicitly  Explicitly  Implicit backup: As part of the post-processing of each installation you are required to schedule an R/3 job using transaction sm36 that runs the executable sddb6mir -m on an hourly basis on your database server. Each invocation will extract the previously unsaved data and insert those records of ADM into corresponding tables in the R/3 database . Invoking sddb6mir -r allows you to restore the ADM database from the R/3 database. Explicit backup: Whenever offline log files are archived, the contents of ADM are also backed up to the same target media.  (C) SAP AG BC535 7-15 Backup Cycle: DB2 Database Backups DB2 database backups of Online Offline ...  Daily full online backup  Weekly full offline backup Online 28 days ... Online ... Offline  SAP AG 1999  The standard database backup cycle for DB2 includes performing:  An offline backup of the complete R/3 database once a week, and  A full online backup of once a day. (C) SAP AG BC535 7-16 Backup Frequency Considerations  The more frequently backups are performed, the less time is needed in case of a database recovery Trade-off between backup costs and recovery downtime Recovery Cost 200000 180000 160000 Too few backups can become very expensive Keep roll forward times in mind Cost per recovery 140000 120000 100000 80000 60000 40000 20000 0 0 10 20 30 40 50 60 70 80 90 Number of backups per year  SAP AG 1999   The calculations shown here clearly show the importance of backups. When you create your backup strategy, you must consider the following:  Having consistent readable backups is the only way to ensure a database can be recovered.  Ensure that you use high-quality disks and/or redundancy to minimize the need for recovery.  Fast recovery is crucial. Test your system‟s throughput. Do not rely on estimates.  For critical systems, consider advanced solutions, which will be discussed later.  Remember, database administrators are always asked about backup costs, but never about the cost of downtime. (C) SAP AG BC535 7-17   The db2agent process communicates with and controls the operation of the db2med and db2bm processes. The db2med processes are of type media controller. They transfer data on a FIFO basis from backup buffers that are full. The number of db2med processes depends on the number of backup devices or sessions. The db2bm processes are of type buffer manipulator. Their task is to move data from a tablespace to backup buffers (not buffer pools). The buffer manipulators are set in parameter PARALLELISM. Since only one buffer manipulator can work on a tablespace at a time, you should not set the value for PARALLELISM higher than the number of tablespaces. The db2bm processes use prefetchers to improve parallelism to access the tablespaces. If you use multiple tapes or PARALLELISM with value larger than 1, the number of buffers you should have must be large enough to keep the media controllers and their attached devices busy. The size of the backup buffer should be 1024, or preferably 2048 4 KB pages (4 MB, 8MB). Example: You have 2 DLT tape drives and 5 independent RAID1 mirrored disks for the containers. Provided that you have correct striping of the containers, you will keep all disks busy when backing up 5 tablespaces at the same time (PARALLELISM=5). To have a free buffer when the last one is full, use 10 buffers. Since you are performing online backups, the number of I/O servers should be at least 5, since the R/3 System will also do prefetching. 2 media controllers are used.     (C) SAP AG BC535 7-18 Using DB2 Backup Parallelism WRITE WRITE db2 backup db online to /dev/rmt0, /dev/rmt1 with 6 buffers parallelism 3 6 backup buffers db2med db2agent 2x db2med WRITE db2bm 3x db2bm db2pfchr 1.... m  SAP AG 1999 Disk 1 READ Disk 2 Disk n  The degree of parallelism that is used for your database backups can be set using the DB2 CLP:  In parameter PARALLELISM, specify how many buffer manipulator processes are started.    You can specify how many memory areas are used to store data before it is written to the target media in parameter BUFFERS. The number of sessions is determined by the number of target devices (which must equal the number of media control processes). When determining your optimal backup strategy, include a variation of all three parameters with subsequent measurements. (C) SAP AG BC535 7-19 DB2 Backup Performance Tips  Use more than one process to exploit parallelism  Provide a sufficient number of backup buffers:  Number of backup buffers = (2 x the number of db2med) + a few extra  Provide enough I/O server processes  Number of I/O server >= the number of max. disks for a tablespace + 2  SAP AG 1999   The DB2 UDB database utilizes backup buffers efficiently, switching fast between buffers. For optimal performance, you should use more than one process to exploit parallelism. To do this, you must have at least one backup buffer available for each of the following:  Each db2med process writing to a medium  Each db2bm process receiving data from tablespaces  In live systems, backup buffers are transferred to media much more slowly than they are filled by the db2bm processes. You should therefore have less filled buffers waiting for db2med processes than there are db2bm processes. For optimal performance, the number of backup buffers should be twice the number of devices or sessions plus a few extra. During online backups, backup buffers compete for RAM with other programs and buffers (buffer pool). You must take this into account when defining your number of buffers. During online backups, the db2bm processes utilize DB2 I/O servers (prefetchers) for I/O. It is therefore good practice to configure a slightly higher number of NUM_IOSERVERS.   (C) SAP AG BC535 7-20 Backup Device Configuration Tips Fixed block size: 512 1024 2048 4096 bytes Variable block size: 0 bytes Not r me ecom nded Buffer size is limited WRITE Backup buffers Any buffer size DB2 backup image Header 4 KB  SAP AG 1999     When you use fixed block sizes for devices, only 512, 1024, 2048, and 4096 bytes are supported as block sizes. This is because DB2 BACKUP writes a 4 KB header onto the tape device. Note: Backup buffer sizes are not restricted with fixed device block sizes. If the block size is set to 0, variable block size will be used. The use of variable block sizes is not recommended. For more information, see SAP Note 199665. However, if you must use variable block sizes to increase the performance of the backups, the following condition must be met:  The buffer size specified in the backup command must be less than or equal to the maximum variable block size supported by the hardware/OS vendor.  If the backup buffer size and tape block size do not have the correct combination, there is a possibility that the backup will complete successfully but it may not be possible to perform a restore from that backup image. Note: If you are not backing up to tape, larger backup buffers are better. For example, you can use larger backup buffers when you perform backups to disk and hierarchical storage systems, such as Legato Networker or ADSM.  (C) SAP AG BC535 7-21 Block Size Limits of Selected Backup Devices Device Attachment 8mm scsi 3420 s370 3480 s370 3490 s370 3490E s370 3490 s390 3490E s390 7332(4mm)* scsi 3490e scsi 3590** scsi 3570 Magstar MP Block size limit 131072 65536 65536 65536 65536 65536 65536 262144 262144 2097152 262144 DB2 buffer size limit (4KB pages) 32 16 16 16 16 16 16 64 64 512 64 (*) The 7332 device does not implement a block size limit. 256 KB is only a suggested value. Block size limit is imposed by the parent adapter. (**) While the 3590 device does support a 2 MB block size, you might experiment with lower values (such as 256 KB), provided performance is adequate.  SAP AG 1999     The best backup and recovery strategy is the one that has been tested. Before going live, you must test a restore of the production database to make sure that block and buffer sizes are not only correct for backups, but also for a restore. Consult with your hardware vendor about the block size limit of the tape device and, if applicable, the parent adapter. Note that maximum block sizes sometimes vary between tape devices of the same type. Therefore, restore tests are mandatory. (C) SAP AG BC535 7-22 Tivoli Storage Manger Administration  To manage database backups and archived offline log files in the Tivoli Storage Manager, use the following executables:  db2adutl queries, selects, extracts, and marks backups as inactive brachive archives offline log files brdb6qry searches for archived log files brdbsdsd deletes archived log files brrestore retrieves archived log files      SAP AG 1999  SAP delivers several executables to manage database backups and log files archived offline:  db2adutl is used to administrate the Tivoli Storage Manager (formerly known as the ADSM ADSTAR Distributed Storage Manager), and is described in SAP Note 67789. - If used with option Query, backup images are selected in the ADSM. - If used with option Extract, backups from the ADSM are extracted to disk. - If used with option Delete, database backups in the ADSM are marked as inactive, and deletion will take place according to retention policy.  brachive is used to store offline retained log files to the ADSM.  brdb6qry is used to search for offline archived log files in the ADSM.  brdbsdsd is used to delete offline archived log files from the ADSM.  brrestore is used to restore offline archived log files from the ADSM.  Note: The ADSM client program on INTEL platforms is currently not reentrant. This means that you cannot run multiple sessions to back up a DB2 database server on Windows NT. This limitation will, however, be removed in the future. (C) SAP AG BC535 7-23 Advanced Backup Scenarios: Split Mirror Backup Procedure 1. Split the third mirror 2. Backup the contents of the third mirror 3. Resynchronize mirrors 1, 2, and 3 Logical level Production DB Split Physical level Mirror 1 Sync Mirror 2 Sync Mirror 3 “Backup”  SAP AG 1999   Instead of backing up the production database as discussed up to now, you can consider using an advanced backup concept, such as using the features of the underlying disk subsystem. In this example, production data is stored redundantly on three different physical devices, all in control and normally synchronized by the disk subsystem. As a first step, the third mirror is split apart and its contents are transferred as if it was a backup. Because the database was in continual operation, these changes that were recorded on disk mirrors 1 and 2 would have to be reapplied to mirror 3 by the disk subsystem. The benefit of this technique is to minimize the impact the backup has in the production environment.  (C) SAP AG BC535 7-24  In this second advanced backup scenario, a second database server is used, which has initially been set up by a restore of the production database. This second (standby) database is permanently in the state roll forward pending. That is, it cannot be accessed by applications by “waits” for the application of transaction log files. Whenever a log file is filled on the production system, a special version of the DB2 logging user exit will copy this file to its standard target device (such as directory log_archive). In addition, it will copy it to a common directory that the production and standby database servers share, using UNIX or NT shares. On the standby database server, the logging user exit will again be used to retrieve the log files copied by this procedure. Note that these log files are not applied immediately, but after a configured amount of time. This provides the chance to treat logical errors. That is, the corresponding log records of these logical errors must not be reapplied. Instead, the standby system is opened shortly before the logical error occurred and substitutes the former production server.    (C) SAP AG BC535 7-25 Importance of Offline Log Files The database cannot be rolled forward past this point in time Point in time of the database error Sequence of offline log files: Lost information X Lost offline log file Intact but unusable offline log files Time If one offline log file is lost, none of the following files can be used in case of a recovery  SAP AG 1999     Although the database operation is not immediately affected if an offline log file is lost, these files are crucial in case of a restore and roll forward recovery. If a database backup image is restored, the subsequent roll forward cannot be continued past the missing file. This reveals the fact that losing an offline log file is more harmful than losing a database backup. If a loss of an offline log file is detected, an immediate full database backup is absolutely mandatory. (C) SAP AG BC535 7-26 2-Step Log File Management ADM Logfile Copy-RC Archive-RC log_dir 1 1 DB2 logging user exit 0911 0912 0913 0 0 0 0 0 - log_archive 2 2 BRARCHIVE Tape / Storage management system  SAP AG 1999  When an online log file is filled with log records, the database invokes the DB2 logging user exit, which copies the file to the log_archive directory and update logging tables in administration database ADM. BRARCHIVE is used to archive offline log files to a constant storage media, such as to tape or a storage management system (like ADSM or Legato). BRARCHIVE retrieves the range of log files that are to be archived out of the administration database ADM. If you use a storage management system as BRARCHIVE‟s target device, tape management is done automatically by the storage management system. If you use tapes as the direct target media, you must manage the tapes manually.    (C) SAP AG BC535 7-27 Native BRARCHIVE Tape Management 1. Configure a device class 2. Configure a device 3. Initialize tape  SAP AG 1999  Tape management relies on a hierarchy that has to be defined by the administrator:  For each kind of tape device in the system, a device class has to be defined. The tape device has a number of attributes specific to a certain class of tape devices, such as capacity and tape handling commands.  For each physical device, a tape device has to be defined. The name of that device should be the device name, for example, /dev/rmt0.  Each tape that will be used for log file archiving has to be defined. This means the tape must be given a name and initialized.  To initialize a tape, from the DB2 Control Center choose R/3 Tape Management  Tapes. Select the device class to which the tape to be initialized belongs. Select Tapes. Press the right mouse button and select Initialize Tape. In the Initialize Tape dialog box, enter the name of the new tape. Select the device where the tape is located. To initialize the tape, choose Init. All tape actions and their results can be seen in the Journal page. To remove a tape, select the tape in the tree, press the right mouse button, and select Delete.  (C) SAP AG BC535 7-28 Tools for Offline Log File Management Option 1: Direct invocation of brarchive 1a) On demand C:\SQLLIB\BIN>brarchive -sd -n 10 -d ADSM -confirm 1b) Scheduled regularly using scripts Use crontab or at mechanisms  SAP AG 1999   There are three ways in which you can archive offline log files using BRARCHIVE. The first option uses the command line interface of BRARCHIVE. There are two ways to do this:  As shown in example 1a., you can directly issue the brarchive command from the command prompt.  As shown in example 1b., you can use crontab (available on UNIX platforms only) to schedule offline log file backups using a script. (C) SAP AG BC535 7-29 Tools for Offline Log File Management Option 2: DB2 Control Center T01 Archive  SAP AG 1999   A second interactive method to trigger BRARCHIVE is provided by SAP‟s enhancements to the DB2 Control Center. You should archive log files when you want to be able to keep them over a longer period of time. You can either archive them to tape or to ADSM. To archive log files, from the DB2 Control Center choose R/3 Log File Management  Archive. Specify the node where you want to archive the log files. Specify the log file up to which you want to archive. If you do not want the log files to be deleted from DB2DB6_ARCHIVE_PATH after archiving, select the don„t delete log files in file system check box. Specify where you are going to archive to, that is, select either ADSM (left radio box) or Tape (right radio box). If you select ADSM, choose a management class from the ADSM management class box. If you select Tape, specify the name of first tape and its device. If you want to use two tapes, follow the same procedure for the name of the second tape and its device. To start the archive process, choose Archive.  (C) SAP AG BC535 7-30 Tools for Offline Log File Management Option 3: R/3 DBA Planning Calendar (DB13)  SAP AG 1999  The R/3 System provides the third way to start BRARCHIVE. If you use the CCMS DBA Planning Calendar (transaction DB13), you can conveniently schedule periodically executed log file archiving. (C) SAP AG BC535 7-31 Tape Management Recommendations  Incremental file system backup of log_archive in addition to BRARCHIVE can be useful if 2-step log file management is in place  Do not backup online log files  Keep all the log files needed to restore the oldest database backup in your backup cycle  Schedule checks for freespace in log_archive to trigger BRARCHIVE as soon as required  SAP AG 1999  A good way to archive offline log files is to schedule an incremental backup of the log_archive directory using a hierarchical storage management system. Also, call BRARCHIVE on a regular basis. With this method, you will also have two copies of each log file available. The active log files in directory log_dir are locked by the database when in use. Therefore, there is no necessity to back up online log files. If you do back up this directory, you will encounter database runtime problems. You must ensure that you have all the log files available that are needed to recover the oldest backup in your backup cycle. Ensure your retention period for log files is 28 days. If you use cron (UNIX), you are able to call a shell script that checks the freespace in log_archive on a regular basis. When the freespace is below a certain level, the shell script will call BRARCHIVE automatically.    (C) SAP AG BC535 7-32 Backup Cycle DB2 database backups and log file archival Online Offline Archives (2x) Online Archives (2x) 28 days Online Archives (2x)  SAP AG 1999     You must back up the offline log files each workday, as well as after every online and offline backup. Ensure that you back up the offline log files twice, on separate tapes, before they are deleted. Remove the last verified full offline backup of each cycle from the tape pool, and keep this backup in long-term storage. Replace the tapes, and initialize new ones. To verify a backup, check the database for logical errors and the database backups for physical errors. Perform backup verification at least once in the backup cycle. Perform additional backups after each database structure modification or a system upgrade. Place these additional backups in long-term storage. (C) SAP AG BC535 7-33 1-Step Log File Management log_dir 1 1 DB2 logging user exit Storage management system  SAP AG 1999  As an alternative to the previously discussed 2-step log file management, you can set up the 1-step log file management:  By a different configuration of the DB2 logging user exit, filled log files are transferred immediately to storage management systems. As a consequence, BRARCHIVE is not needed in this setup.  The benefit of this approach is that log files are stored on safe, external media as soon as possible. In case of a roll forward recovery, these log files can directly be retrieved by the DB2 logging user exit. There is no operator intervention required as it would be necessary to retrieve log files from tape in the 2-step scenario. To avoid file system full conditions in the log_dir directory, you must make sure that your storage management solution is highly available.  (C) SAP AG BC535 7-34 Data Backup Objects Database backup DB2 configuration files DB2 BACKUP DB2 container(s) Offline log file(s) BRARCHIVE Online log file(s) R/3 data ... R/3 Archiving interface ... Interfaces ... file systems SAP Executables  SAP AG 1999 Computing center data R/3 & ??? Operating system system information Operating  Remember that your backup strategy must include backing up the operating system data as well as R/3 file systems (such as transport directories, archive file, executables, and scripts). The tools to backup these components are highly specific to the underlying operating system. Apart from all planning and scheduled jobs, it is important that every backup strategy consists of training, knowhow, documentation, and regularly performed restore and disaster recovery tests  (C) SAP AG BC535 7-35 Unit Summary Now you are able to:  Define an efficient backup strategy that uses:     DB2‟s Control Center for database backups CLP for database backups CCMS Planning Calendar for online backups BRACHIVE for DB2 for log file archiving  Estimate the amount of tapes needed for your backup strategy  Understand DB2‟s 1-step and 2-step log file management  SAP AG 1999 (C) SAP AG BC535 7-36 Unit Actions ?  Do the exercises  Solutions for the exercises  SAP AG 1999 (C) SAP AG BC535 7-37 Backup and Log File Management: Exercises No. 1 Exercise For these exercises, make the following preparations: Enter your -directory cd /db2/T Create a backup directory mkdir backup Enter the backup-directory cd backup 2 3 4a 4b 5 6 Change the logging mode of your test database into LOG RETENTION mode. Perform an offline backup of your test database. Write down the timestamp of your backup for further use. Perform an offline tablespace backup of the PSAPEL46BD and PSAPBTABD tablespaces. Perform an offline backup of your test database using the DB2 Control Center. Retrieve information about all backups that have been performed on your R/3 database server up to now, using R/3 monitoring transaction. Retrieve the same information about the backups using the DB2 Control Center. (Hint: Use the DB2 Journal). 7 8 9 10 11 Retrieve the DB2 recovery history information of your test database for all backups using the DB2 CLP. Retrieve the DB2 recovery history information of your test database for all backups made since yesterday, using the DB2 CLP. Use the scenario that your DB2 recovery file has been destroyed. Restore your recovery file from the latest backup using DB2 CLP. Perform the same operation using the DB2 Control Center. (Hint: Use the DB2 Journal) Which transaction has to be used to show information about the success of the mirroring of the administration database adm? (C) SAP AG BC535 7-38 Backup and Log File Management: Solutions No. 1 Solution Enter your -directory cd /db2/T. Create a backup directory mkdir backup Enter the backup-directory cd backup. 2 3 To change the logging mode of the test database, use command db2 "update db cfg for using logretain recovery". To perform an offline backup of the test database, use command db2 "backup database to /db2/T/backup with 4 buffers buffer 1024 parallelism 2" The timestamp for this backup image is 20000327181524. 4a To perform an offline tablespace backup, use command db2 "backup database tablespace PSAPEL46BD, PSAPBTABD to /db2/db2t0/T/backup with 4 buffers buffer 1024 parallelism 2". To start the DB2 Control Center, use command db2cc. Right click on the test database icon and choose Backup  Database. In the tab Backup, specify the backup directory /db2/db2t0/T/backup. In the tab Options, select Offline. To start the backup, select Backup now. 5 6 To retrieve the information about all the backups, use the Overview Backup Status Monitor (transaction DB12). To retrieve the information about all the backups using the DB2 Control Center, you must mark View and choose Journal. Choose the History tab, and select your database. To retrieve the DB2 recovery history information, use command db2 list history backup all for . To retrieve the DB2 recovery history information since yesterday, use command db2 list history backup since 20000327 for . To restore the recovery file from the latest backup, use command db2 restore db history file online from To restore the recovery file from the latest backup using the DB2 Control Center, choose Tools  Journal. Choose the History tab, and select your database. Right click on the latest backup containing the history file and choose Restore Recovery History. To review the success of the mirroring job of the administration database, use the job overview in transaction SM37. Note: This transaction must be scheduled on an hourly basis. 4b 7 8 9 10 11 (C) SAP AG BC535 7-39 (C) SAP AG BC535 8-1 Restore and Recovery Contents:  Overview of recovery options with DB2 UDB  Restoring a database and single tablespaces  Performance considerations in restore situations Objectives: At the end of this unit you will be able to:  Restore a DB2 database from a backup image  Roll forward the database using the offline log files  Define recovery procedures  SAP AG 1999 (C) SAP AG BC535 8-2 Roll Forward Vs. Restart Recovery Manual intervention Automatic, no intervention needed Database restart DB DB Roll forward recovery: restore + roll forward Restart recovery: connect  SAP AG 1999  DB2 offers two types of recovery:  A roll forward recovery must be performed when all or parts of the persistent storage (disks) have been lost or corrupted. The process is lengthy and requires manual intervention.  A restart recovery is performed by DB2 whenever data in the non-persistent memory (RAM) has been lost due to a system hardware failure or a power loss. - In this case, restarting the DB2 database initiates a crash recovery. DB2 reruns all transactions that were performed previously but have not been recorded in persistent memory. The DB2 log file header file contains the log sequence number, which must be used as a starting point for this type of recovery. If you lose this file, you are unable to restart your database and must perform rollforward recovery. - To ensure that DB2 automatically starts the restart recovery, the DB2 database parameter AUTORESTART must be set to On. (C) SAP AG BC535 8-3 Restart Recovery: Background Buffer pool DB2 agent 1 1 DB2 agent DB2 I/O cleaner 2 2 DB2 logger 3 3 tely edia Imm 4 4 d erre De f Online log files Log records Log sequence number Log rec. data Tablespaces n+1 01001010010 XXXXXX 01001010011 XXXXXX n+2 01001010012 XXXXXX 01001010013 XXXXXX Data not stored on tablespaces ...  SAP AG 1999 ...    DB2 agents perform database transaction triggered by R/3 work processes. (1) All database changes are immediately logged to the log files by the DB2 logger. This is called write ahead logging. (2) Pages containing committed transaction data are moved to persistent storage by DB2 I/O cleaners and DB2 agents. (3) Those processes are triggered by soft check points. Soft check points define the interval for a buffer pool flush. Soft check points are defined by:  DB2 parameter SOFTMAX  DB2 parameter CHNGPGS_THRESH (change pages threshold)  However, DB2‟s buffer pool flushes do not write the entire buffer pool content to disk. There is always a difference between the committed data, stored in the log files and in the buffer pools, and the data stored on the persistent storage. If a DB2 database crashes because of power failure, the database is in an inconsistent state. To solve this inconsistent state, DB2 performs a restart recovery before it is up and running after a database crash. The restart recovery reapplies all data at the point in time of the crash, which was committed and logged to the log files but not yet moved to persistent storage. (4) (C) SAP AG BC535 8-4 Restart Recovery Log file header holds recovery range Online Log Files Log records Log sequence number Log rec. data lied app Re Tablespaces n+1 01001010010 XXXXXX 01001010011 XXXXXX n+2 01001010012 XXXXXX 01001010013 XXXXXX Data not stored on tablespaces ...  SAP AG 1999 ...     The next database start after a crash starts DB2‟s restart recovery. The goal of the restart recovery is to get DB2 into a consistent state. The log file header holds the restart recovery range by pointing to the first log sequence number, which holds committed data that is not yet applied to the tablespaces. As long as the database performs a restart recovery, no connections are allowed. The db2diag.log contains entries that are required in the case of a restart recovery, which show the first and last log sequence number (LSN) used during crash recovery. (C) SAP AG BC535 8-5 Roll Forward Recovery  Performed with operator intervention:    Restore the offline/online database backup Restore the log files Roll forward using log files Containers Backup 1 1 DB2 RESTORE 3 3 Database configuration Log files 2 2 Roll forward Online log files BRRESTORE  SAP AG 1999   With a roll forward recovery, a backup image (online or offline) and all the subsequent log files created after the backup are used to recover the database to a consistent state. When you design your backup strategy, consider how much time you want to spend on a recovery. A current backup enables you to perform a faster recovery since there are fewer log files to redo. (C) SAP AG BC535 8-6 Roll Forward Recovery Scenarios db2 rollforward database to Roll forward to a point in time t t1 DB2 BACKUP n n+1 n+2 n+3 n+4 Offline log files Roll forward to end of logs t t1 tEnd db2 rollforward database to end of logs  SAP AG 1999  There are two ways to perform a roll forward recovery:  You can roll the database forward to a certain point in time  You can roll the database forward to the end of the logs.  If you perform a point in time recovery, ensure that you are using coordinated universal time (CUT) – also known as Greenwich mean time – since the database server calculates the timestamps based on this time zone. Applications from different time zones may connect to the database, but internal processing is done in CUT. Note: The timestamp used for backups is based on the local time zone of the database server.  (C) SAP AG BC535 8-7 Database Recovery: Work Flow 1 1 2 2 History Restore 3 3 Database Logs 5 5 4 4 Database Roll forward  SAP AG 1999  You must perform a database recovery in several steps:  Use the DB2 recovery history file to search for the timestamp of the most recent backup. If you performed full database backups, you can identify the backup image using this timestamp. If the size of your database mandated backups on tablespace level, you must search for multiple backups. (1)  Restore the database using the DB2 Control Center or the DB2 command restore. (2)  Retrieve the log files that are requested in the recovery history file. The file specifies the log files needed to maintain consistency of an online backup. If you want to recover all operations made to the database, you must retrieve all the log files that have been created. (3)  In the roll forward phase, use the DB2 Control Center to roll forward the transactions using the log files that have been retrieved. (4)  Finally, you must instruct the database to roll forward stop. The database will then be consistent. (5)  This example does not show the roll back phase, which is the last step in this process. During the roll forward process, all committed transactions are reapplied to the database. At the end of the roll forward, a list of open transactions exists. These transactions are still waiting for a commit. For data consistency reasons, open transactions are then rolled back to make sure that changes that are not committed are not applied to the database. (C) SAP AG BC535 8-8 Restore and Recovery with Logical Failures Logical failures No structural change Logical failure (such as a dropped table) t Roll forward to PIT Restore database Restore database with CUT P Us e 2 CL DB 11:15:00 MET = 10:15:00 CUT  SAP AG 1999  In this example, the database is returned to a previous given status and then rolled forward to another (later) specified time. The following steps outline the procedure for doing this:  First, a restore is performed using the most recent backup.  Then all required archive files are copied back from the archive tapes.  The database is then rolled forward, up to the specific point in time when the logical failure occurred.  This type of recovery is called point-in-time (PIT) recovery. You should only use PIT recovery if the data that is not applied to the database can somehow be re-created (since it has been added in later transactions than the PIT). Time specifications for the PIT have to be made in CUT. Do not use your local time zone, unless you live in the GMT time zone. The UNIX command date helps you to retrieve local time and CUT. Note: If you use the DB2 Control Center for a PIT recovery, the timestamp you apply must be in local time. The DB2 Control Center performs the conversion for you (ensure you have the most recent FixPak applied).   (C) SAP AG BC535 8-9  You can use the DB2 Control Center to solve simple recovery cases, such as after losing data files because of a defective hard disk. First, determine the cause of the defect (such as hard disk defects caused by vibrations). This may help you to avoid similar situations in the future. After a hard disk defect, however, you need a new hard disk. To perform a restore and recovery using DB2 Control Center, call DB2 CC on your control workstation: 1 Check the tablespaces that have been destroyed with the disk crash. 2 Insert the DB2 backup tape with the correct backup timestamp. 3 Restore the tablespace out of your full online of offline database backup. 4 Insert the tape with the needed volume label. 5 Retrieve the log files that are needed to roll forward to the end of logs from the tape pool. 6 Roll the database forward using the DB2 Control Center. The DB2 logging user exit moves all the log files that are needed for roll forward from the offline log directory to the online log directory.   After all the log files have been applied, the database is made available with the command db2 rollforward stop. Open transactions are then rolled back and the database is ready for use. Note: Never drop the whole database if partial recovery is possible. This will save you the time required to re-create the database container files and restore mostly correct data.  (C) SAP AG BC535 8-10   The db2agent process communicates with and controls the operation of the db2med and db2bm processes, also during a restore. During restore operations, the media controllers transfer data from device to restore buffers. When a buffer is full, it is transferred to disk on FIFO basis. The number of db2med processes depends on the number of restore devices or sessions. The parameter PARALLELISM may be used during a restore, but if you are not using multiple tape devices or ADSM sessions, multiple db2bm processes are not used. It is always much faster to empty the buffers to disk than to fill them from tape or ADSM. For example, you should use PARALLELISM when reading the backup images from disk. The number of buffers should be large enough to keep the media controllers and their devices busy (more than 2). The size of the restore buffer should be 1024, or preferably 2048 4 KB pages (4 MB, 8MB). You may use a multiple of the backup buffer size. But if you achieve good backup performance with a certain backup buffer size, you can ensure excellent restore performance by using the same size for the restore buffers. Note: During a restore, DB2 uses page cleaners to transfer the buffer contents to disk.    (C) SAP AG BC535 8-11 DB2‟s Restore Tools DB2 Control Center Restore and roll forward Command line processor  SAP AG 1999  To issue the DB2 restore and roll forward commands, you can use:  The DB2 Control Center, or  The DB2 command line processor (CLP)   The DB2 Control Center is DB2‟s graphical user interface used for perform database administration tasks. DB2‟s command line processor allows you to perform database administration task using SQL commands. (C) SAP AG BC535 8-12 DB2 Restore Tools: DB2 Control Center Select a backup from DB2‟s backup history list Check that the source of the backup is available  SAP AG 1999  To perform a restore using the DB2 Control Center, go to the main screen of the DB2 Control Center. Place your cursor on the database name (SAPSID), click the right mouse button, and choose Restore  Database. To configure the restore command, the DB2 Control Center is divided into five tabs, allowing you to adapt the restore commands to your needs:  Backup image  Tablespaces  Containers  Roll forward  Options   In the Backup image tab, specify which backup will be used for the restore. Ensure you choose a recent backup from DB2‟s backup history list and check that the source of this backup is available. To check if the source of the backup is available, check the List of directories or tapes. (C) SAP AG BC535 8-13 DB2 Restore Tools: DB2 Control Center Tablespaces Use a full database backup to avoid inconsistency  SAP AG 1999   In the Tablespaces tab, select Use a full database backup to avoid inconsistency. If you select a single tablespace or group of tablespaces to perform a partial tablespace restore, you may create a database that holds information in different tablespaces that do not match, from an application point of view. (C) SAP AG BC535 8-14 DB2 Restore Tools: DB2 Control Center Containers Only select this option if you want to perform a redirect restore Select a table space you are going to restore redirect Use Add, Change, and Remove to change the container layout per tablespace Tip: Use SAP‟s redirect restore tool  SAP AG 1999   In the Containers tab, option Redirect table containers enables you to change the container layout per tablespace. If you select this option, you need to mark and configure each tablespace that you want to restore redirect. If you are going to change a high number of tablespaces and containers this may take a long time. Also, there is no way of temporarily saving any results of your work. And if you have a large number of tablespaces and containers, you may not have an adequate overview of your redirected restore layout. Note: If you are going to change the layout of your database, use SAP‟s redirect restore tool.  (C) SAP AG BC535 8-15 DB2 Restore Tools: DB2 Control Center - Roll Forward Only select this option if you want to perform a roll forward directly after the restore. If selected, specify either a point in time or end of logs recovery. Select this option if you are going to perform a roll forward after a restore. Use roll forward item after a restore to perform roll forward  SAP AG 1999  In the Roll forward tab, you can specify if you want to perform a roll forward right away, after a restore. If you select this option, you must define whether it will be a roll forward to a point in time (PIT) or a roll forward to the end of logs. If you do not want to perform a roll forward right away (after a restore), you can set a roll forward item in the DB2 Control Center. To do this, after you have performed a successful database restore, place your cursor on the database name (SAPSID) and click the right mouse button. Choose Rollforward... Again you can choose between a roll forward to a point in time (PIT) or a roll forward to the end of logs. If you have selected Leave in roll-forward pending state, you must issue a roll forward stop command to finish the roll forward procedure.   (C) SAP AG BC535 8-16 DB2 Restore Tools: DB2 Control Center - Options Select the option Offline to avoid inconsistency Configure the number of buffers and the buffer size DB2 uses for read and write operations Choose Show Command to display the corresponding DB2 command  SAP AG 1999   In the Options tab, select the option Offline to ensure consistency while you perform the restore. In the section Performance, you can specify the number of buffers and the buffer size DB2 will use to read from the backup media and write the information to disks. (C) SAP AG BC535 8-17 DB2 Restore Tools: DB2 CLP Commands DB2 restore command DB2 restore and roll forward command DB2 roll forward command  SAP AG 1999  To perform a restore using the DB2 command line processor, you must first have the syntax for each command. At the command prompt, enter:  db2 “? restore”  db2 “? rollforward”  Alternatively, you can use the DB2 Control Center to configure the restore and roll forward (as previously described), and then choose Show Command. The corresponding CLP command is displayed. Save this CLP command in a file, and modify it to meet your requirements. For detail information about the restore and roll forward CLP commands, refer to DB2‟s Command Reference.  (C) SAP AG BC535 8-18 Log File Life Cycle for 2-Step Log File Management log_dir DB2 logging user exit DB2 logging user exit 1 1 4 4 log_archive log_retrieve ADM 2 2 BRARCHIVE Tape / Storage Management Solution  SAP AG 1999 3 3 BRRESTORE  Log files can be managed in two-steps with the use of DB2‟s logging user exit, and the SAP tools BRARCHIVE AND BRRESTORE:  The DB2 logging user exit copies log files from the online log directory (log_dir) to the offline log directory (log_archive). For each log file copied, an entry is created in the administration database (ADM). The logging user exit also copies log files from the log_retrieve directory to the online log directory (log_dir) in the event that a roll forward has to be performed.  The SAP tool BRARCHIVE provides log file storage management functionality. For each log file that is copied or deleted to or from the offline log directory (log_archive), a corresponding entry in the administration database is made.  The SAP tool BRRESTORE provides log file restore management functionality. For each log that is restored to directory log_retrieve, a corresponding entry in the administration database is made. (C) SAP AG BC535 8-19 Log File Management: DB2 Control Center Choose the backup you want to use for the restore S0000100.LOG.2000012053624.NODE0000 ADSM:TCCB2. S0000101.LOG.2000012063624.NODE0000 ADSM:TCCB2 S0000102.LOG.2000012073624.NODE0000 ADSM:TCCB2 S0000103.LOG.2000012083624.NODE0000 ADSM:TCCB2 S0000104.LOG.2000012093624.NODE0000 ADSM:TCCB2 The related log files are displayed Restore Restore the log files from the backup media  SAP AG 1999  Log files can also be managed using the DB2 Control Center:  From the DB2 Control Center., place your cursor on the database name (SAPSID) and click the right mouse button. Choose R/3 Log File Management  Restore. Specify the node where you want to restore log files. To determine which log files are to be restored, specify a backup date. All available log files for the selected backup are displayed (together with the medium on which they are stored). Specify the log file range to be restored. To start the restore procedure, choose Restore. A dialog box appears telling you that the restore process has been started. After the restoring has finished, another dialog box appears telling you it it was successful. All restore actions and their results can be seen in the Journal page. (C) SAP AG BC535 8-20 Log File Management: BRRESTORE Restoring log files from tape Command syntax Description brrestore -a 110-120 -d tape -v D4XA99 -out Tries to retrieve the log files with the numbers 110 to 120 from tape D4XA99 and prints out all messages. Emergency log file restore from ADSM Command syntax Description brrestore -ex "*" S000112* 19980612 –d adsm Stores log files available from ADSM to the current directory, provided they match the given file name pattern and were stored to ADSM on 12 June 1998 or later. Emergency log file restore from tape Command syntax Description brrestore -ex "*" –t /dev/rmt0.1 Stores ALL files available on the tape in device /dev/rmt0 to the current directory. Query functions Command syntax Description brrestore –q '*NODE0002' -out Displays information about the archiving work to be done. The names of all archived log files are under the node NODE0002. Query functions Command syntax Description brrestore –q adsmMC -out Displays the names of all known ADSM management classes.  SAP AG 1999  If you use the SAP tool BRRESTORE to manage log files, you can use the following commands in combination with brrestore [] WHERE :  -d[evice] {tape | adsm [MC]} specifies where to store or retrieve the devices. The default value is Tape, unless other command line parameters are set to ADSM.  -node { | ALL } specifies the DB node name. The default value is NODE0000. 'ALL' is currently only permitted with DB2 EEE for store operations.  -n[umber] specifies the number of files to act on. This is only used for store operations. The default value is 99999.  -out displays the log files on stdout. This is only used for store operations. The default value is 99999.  -sid specifies the SAP System ID. This entry is required unless there is information available in the DB2DBDFT environment variable  -t[ape -device] specifies which device to use.  -v[olume] specifies which volume to use.  -vndlib specifies a fully qualified lib file. Normally, this entry is not required. (C) SAP AG BC535 8-21  If your administration database needs to be restored, you must copy the mirrored data of the administration database out of the R/3 database back into the administration database. To do this, use the executable sddb6mir with the -r option. To ensure the administration database can be recovered, an export of essential information about that database is archived to a storage solution either to file or to tape. The log file archiving tool does this automatically. The backup image is a compressed archived file (CAR file) made up of individual table exports. This image does not contain action or action detail information such as that shown on SAP-DB2admin's Journal pages. This data is deleted after the administration database is recreated using this image. To recover the administration database, you must run the following executables  -brrestore with option -ex  -sddb6mir -c ADM  -unpack  -db2move ADM load  Then set the constraints for immediate checked.    For more information, check the R/3 Online Help. (C) SAP AG BC535 8-22 Why Perform a Redirected Restore? Tablespace PSAPBTABD sapdata2 • Unequal container sizes PSAPBTABD. container003 ... PSAPpBTABD. container002 PSAPBTABD. container112 • Misspelled or misplaced • System copy • Changes in disk layout containers (e.g. new disks) PSAPBTABD.container001  SAP AG 1999 • Too many small containers • I/O hot spots  A redirected restore should be performed if there are any changes to the container layout caused by:  Unequal container sizes  Misspelled or misplaced containers  Too many small containers  I/O hot spots  A system copy (such as creating a quality assurance system from a production backup)  Changes in disk layout (C) SAP AG BC535 8-23  SAP offers the executable brdb6brt (brt = backup and restore tool), which creates a DB2 CLP script that can be edited to perform a redirected restore. This database maintenance tool can be used to perform the following:  Back up a database and create an DB2 CLP file for subsequent restores  Only create an DB2 CLP file for subsequent restores   You can also use the DB2 command line processor and the DB2 CLP script as an input file to restore a database with different container names, container paths, or container sizes. For more information about this area of database maintenance, see the following SAP Notes :  45233 - Decreasing the size of a tablespace with redirected restore  73717 - Tools for system copy  76577, 115397, 115399 - Tools for redirected restore  122222 - DB2 redirected restore using DB2 CLP  114569 - Roll forward option with redirected restore (C) SAP AG BC535 8-24  All actions and error messages from brdb6brt are displayed on the screen and reported in the file .out. The file resides in the current working directory, in most cases the directory where .scr can be found. As a general recommendation, you should ensure that all files that are generated – from start of the backup until recreation of the database - will be placed in the same directory. To restart the script, you must execute brdb6brt with option flag –r and parameter .out. Together with the log files, this tool can determine which commands have been executed without errors and which need to be put into a new script. The newly created script is called ., where is a number string between 000 and 999, starting with 000. The first time you restart this script, a second script named .000 will be created. This script can be edited and be investigated with regard to the errors reported by the DB2 CLP. The new script has to be executed by db2 –tvf .000. If another error occurs during execution of the new script, a restart is still possible using brdb6brt –r .out. However, this will create a script with the name .001. The log file .out must not be changed or deleted until the database has been restored completely and the screen displays THE RESTORE PROCEDURE HAS NOW FINISHED SUCCESSFULLY.     (C) SAP AG BC535 8-25 Reducing Tablespaces With Redirected Restore Redirected restore Tablespace Extent 0 Reduce TBS size High watermark No space  SAP AG 1999   When reducing the tablespace size using redirected restore, you must ensure that the total size of the tablespace is not reduced below the high watermark of the tablespace. If this is not the case, DB2 RESTORE will try to write an extent that does not exist any more on disk. (C) SAP AG BC535 8-26 Reducing the High Watermark With db2dart Use db2dart to reduce high watermark db2dart /LHWM /TSI /np 0 Tablespace Extent 0 Extent 0 Tablespace New high watermark High watermark  SAP AG 1999  To reduce the high watermark on a tablespace, you can perform the action Reorg all tables in tablespaces in the CCMS DBA Planning Calendar (transaction DB13). If the high watermark was not changed, you must repeat this procedure (if necessary, several times). In an extreme case, the number of repetitions equals the number of tables in the tablespace. To avoid such a complicated procedure, as of DB2 version 6.1, FixPak 3, you can use use db2dart to specify the tables that are connected to the high watermark. For a complete reference on how to reduce the high watermark on a tablespace using db2dart, refer to SAP Note 152531.   (C) SAP AG BC535 8-27 Restore: Preventing Backup Errors Logical data check: Verify database consistency with db2dart SQL2412: DB2 data block corrupted SAP Note 98524 “db2dart” Physical data check: Verify backup by performing a restore DB2 containers Database backup Database backup  SAP AG 1999    Your backup strategy must include a verification of the data to be backed up and a verification of the database backups. Corrupt DB2 blocks (error SQL2412) can appear in your R/3 database as a result of operating system or hardware errors. Corrupt DB2 blocks may make a backup unusable. The existence of these blocks only becomes evident during the next read access attempt to a table within the database. Since this particular access attempt may not occur often, and corrupt DB2 blocks are not recognized during a database backup, corrupt blocks can remain undetected in your system for a long time. You must also perform a logical data check to verify the consistency of the DB2 database. You can perform this logical data check at regular intervals using db2dart. For optimal performance, perform this check during periods of low system activity, such as on weekends. Perform a physical data check to verify the tapes used for a database backup. After a successful backup, perform a test restore of the database to check the physical correctness of the data transferred, the correctness of the tape device, and its software drivers.   (C) SAP AG BC535 8-28 Classification of Database Recoveries Restore and roll forward recovery Type Restart recovery (= crash recovery) Restore offline backup Restore and roll forward to ... ... point in time ... end of logs Hardware failure (e.g. disk crash) Online or offline backup plus offline (and online?) log files User intervention: restore (online or offline backup) AND reapply all logs AND end roll forward pending state Possible reason Power failure or Reset system Logical error (e.g. abnormal termination after tests table dropped) Online log files in Offline backup (no log files) User intervention: restore offline backup AND end roll forward pending state Online or offline backup plus offline (and online?) log files User intervention: restore (online or offline backup) AND reapply logs to point-in-time AND end roll forward pending state Required log_dir resources (no offline log files) Procedure No user intervention: triggered automatically during 1st connect after instance restart  SAP AG 1999 (C) SAP AG BC535 8-29 Database Restoring Tips  Remember that DB2CLP uses CUT for roll forward  In case of a accidental deletion during recovery, you must be able to retrieve the log files again  Ensure all your offline retained log files are in a safe location  Schedule an online backup of the database as soon as possible after recovery  Ensure you know how to perform a restore using the DB2 Control Center and the DB2 command line If the recovery procedure fails, open a customer message in SAPNet  SAP AG 1999    Recovery situations can be extremely complicated. Rash actions can result in permanent loss of data, which makes a complete recovery impossible. Remember to make a backup copy of all online archived log files first. Should a recovery using the DB2 Control Center conclude unsuccessfully, use remote consulting. (C) SAP AG BC535 8-30 Unit Summary  Now you are able to:  Recover your R/3 DB2 database using the DB2 CLP and the DB2 Control Center  Understand the various recovery options  SAP AG 1999 (C) SAP AG BC535 8-31 Unit Actions ?  Do the exercises  Solutions for the exercises  SAP AG 1999 (C) SAP AG BC535 8-32 Restore and Recovery: Exercises No. 1 Exercise For these exercises, make the following preparations:   2 3 Enter your directory cd T Enter the backup directory cd backup Create a database description file of your test database using SAP’s redirected restore tool brdb6brt. Perform the following changes on the previously created . scr file:   Search for: ** Path or device where the backup image is stored. And enter: /db2/T/backup Search for: -- TAKEN AT Remove the (--) In the following line, insert the timestamp of the offline backup you wrote down before. Search for: -- WITHOUT ROLLING FORWARD Remove the (--) Add a container to tablespace PSAPEL46BD Insert the following line into the section “SET TABLESPACE CONTAINERS FOR 1 USING”:,FILE /db2/T/sapdata3/PSAPEL46BD.container002 256 (Do not forget the “,” before FILE)  4 5 Perform a redirected restore on the previously changed . scr file. Check the success of the restore. (C) SAP AG BC535 8-33 Restore and Recovery: Solutions No. 1 2 Solution Enter the directory cd T. Enter the backup directory cd backup. To create a database description file of your test database, use command /usr/sap/TD6/SYS/exe/run/brdb6brt -s -bm RETRIEVE. Search for: ** Path or device where the backup image is stored. And enter: /db2/T/backup Search for: -- TAKEN AT Remove the (--) In the following line, insert the timestamp of the offline backup you wrote down before. Search for: -- WITHOUT ROLLING FORWARD Remove the (--) Add a container to tablespace PSAPEL46BD Insert the following line into the section “SET TABLESPACE CONTAINERS FOR 1 USING”:,FILE /db2/T/sapdata3/PSAPEL46BD.container002 256 (Do not forget the “,” before FILE) 4 5 To perform a redirected restore, use command db2 -tvf T.scr. To check the success of the restore, use command ls /db2/db2t0/T/sapdata3/PSAPEL46BD* 3 (C) SAP AG BC535 8-34 (C) SAP AG BC535 9-1 Storage Management Contents:  Space management  Fragmentation considerations  Reorganization of data  Extension of tablespaces Objectives: At the end of this unit you will be able to:  Understand the space allocation of the R/3 DB2 database  Reclaim space as it is freed up by R/3 or archiving  Extent the database using zero-downtime techniques  SAP AG 1999 (C) SAP AG BC535 9-2   R/3 data is stored in database tables, which are the primary database objects. Other database objects include indexes and views. Triggers are also database objects, but they are not used in R/3. For data access using SQL, knowing the location of data is not necessary. But the proper assignment of tables and indexes to tablespace will help to improve database throughput. For example, R/3 tables and their respective indexes are always stored in different tablespaces. If a read/write head of a disk has read index information, access using read/write head to related data in the table will be independent, provided that the data tablespace resides on a different disk. During R/3 database creation, the tables and indexes are assigned to predefined R/3 tablespaces. Although it is possible to move tables or indexes into a different tablespace, you should schedule these procedures well in advance because the process of moving data involves database downtime.  (C) SAP AG BC535 9-3  R/3 data is stored in database tables. Tables contain records of data. One or several records of a table are stored in a DB2 data page. Pages are the minimum I/O unit of DB2. A DB2 data page can contain one or several records. But a record must fit into a data page. If a record of a table does not fit into a 4096 byte page (4 KB), the table must be defined in a tablespace that is based on a larger page size. DB2 also provides page sizes of 8192 bytes (8 KB), 16384 bytes (16 KB), and 32768 bytes (32 KB). For improved access to data, indexes are pre-defined by SAP developers. They can also be defined later, as further need arises. An index is defined using a few columns of a table, which are accessed frequently. Index data structures allow for efficient retrieval of small quantities of data. Indexes are based on nodes, their storage is maintained within DB2 index pages. Since the pointers pointing to other index nodes are also stored in the index pages, the storage of indexes is not as compact as the storage of data records.   (C) SAP AG BC535 9-4 Table Storage Details Page header Slot directory (255 entries) (100, -1, 190, 240,...) Table Data Free Data Data DB2 data page  Each record can be located by the record identifier (RID)  The RID consists of the data page number and the entry number in the slot directory  SAP AG 1999   DB2 data pages contain a page header, slot directory, and a data area, which is described by the slot directory. Each record in DB2 can be located by the record identifier (RID), which consists of the data page number (3 bytes) and the entry number in the slot directory (1 byte). The slot entry contains the byteoffset to the data page, which must be used as the start location for the data record. Once a record has been stored on a page, it will not move until the table is reorganized. Deleted space is marked in the slot directory (-1), and can be re-used for new records of the same table. The slot directory contains exactly 255 entries. For tables with small records, compared to the page size, there is a potential of unused space on each of the pages.  Example: With 4 KB pages and a table defined with a single CHAR(1) field, only 255 records can be stored on each data page. The inaccessible free space for each of the pages of the table is more than 3 KB.     Note: The above problem does not exist in R/3 Systems, unless you use DB2 pages of 8 KB, 16 KB, or 32 KB. (C) SAP AG BC535 9-5 Index Storage Details Index (f, RID, PID) (r, RID, PID) (dhk, RID, PID) Root node (a, RID, PID) (e, RID, PID) (f, RID, PID) (g, RID, PID) (h, RID, PID) (r, RID, PID) (b, RID) (d, RID) (e, RID) Intermediate nodes (m, RID) (o, RID) (r, RID) Table Leaf nodes e d b  SAP AG 1999 7 1 1 0xAF 0x00 0xFF DB2 index page   For efficient data access, index data structures are used. When data (also known as a key) is queried, the root node of the index is examined by the database. The entries in the node represent the largest existing key in the next level of the index. This process is repeated through the intermediate nodes, until the existence of the key can be checked down in the leaf nodes. In this example, checking for the existence of the key “d” would require access to the root node page of the index, an intermediate node, and the leaf node containing the key “d”. To retrieve the the data record storing the key, the RID is provided. The RID contains the exact page number in the DB2 tablespace. Using the page number, a single additional I/O of a data page allows the rest of the record (d,1,0x00) to be retrieved. The decision to use an index is based on database statistics. If the cardinality (number of records) of a table is low, it may be cheaper to search through data based on the data pages. But with large cardinality, access through index is very efficient. The dummy high key (DHK) entry can be used if an extension of the index with a new high key must be performed.    (C) SAP AG BC535 9-6 Tablespace Details Tablespace ZSAPMMD Extent # 0 1 2 3 4 5 6 ... n ...  SAP AG 1999 Tablespace header Space map pages (SMP) Tablespace object table Extent map pages (EMP) for first table Data pages of first table db2 create tablespace ZSAPMMD managed by database using (......) extentsize 2 prefetchsize 2  Consecutive pages are allocated based on the extent size defined during tablespace creation  For each tablespace, one extent size is defined EMP for second table Data pages for second table Space map pages (SMP)    This example shows the DB2 command used to create tablespace ZSAPMMD. The extent size is 2, which means that two pages will form an extent. The tablespace header in extent 0 contains technical information about the state of the tablespace. The space map pages (SMP) in extent 1 contain a bitmap image of the tablespace. Each bit shows if a certain extent is allocated to a database object or if it can be assigned to a new or growing table needing more space. SMPs occur at regular intervals in the tablespace. The tablespace object table in extent 2 describes the objects of the tablespace and their location. The extent map pages (EMP) of a table describe the internal extent allocation of the table. The first data extent of a table is always allocated, even if no data is inserted. If tables are created in sequence, as seen by R3LOAD during R/3 installation, the EMP of the table that has been created next will now follow.     (C) SAP AG BC535 9-7 Data Distribution Using DB2 Containers  Extents are allocated in a circular way for optimal distribution  Each container should be located on a separate disk to avoid hot spots  All containers should have the same size to avoid hot spots Extent Container 1 0 3 6 Container 2 1 4 7 Container 3 2 5 Disk 1 Disk 2 Disk 3  SAP AG 1999    New extents are allocated as soon as the existing extents of the object have been filled. The allocation takes place in the “next” container, in a circular fashion. The next extent allocation strategy ensures striping of data onto all the available containers. There are no hot spots for table access. If you place more than one container of a tablespace onto a disk, your throughput will not be optimal, since I/O and prefetching will increase.  For example, if you have one small and one large container for a tablespace, the small container will fill up immediately. The large container will only be used for new extents. This will create a hot spot.  All the above considerations also apply for large RAID devices or Intelligent Storage Subsystems. But container placement is not critical, since data is striped by the device. In these cases, large containers are suitable. (C) SAP AG BC535 9-8 System Managed Vs. Database Managed Space SMS:  Each DB object is stored files  For each file system specified, there is only one file per object created  Files grow and shrink DMS:  Space is pre-allocated using containers  DB space management is made in containers  Containers maintain fixed size ZSAPMMD Tablespace Containers File systems ZSAPMMD Tablespace Files File systems  SAP AG 1999  DB2 provides two ways to manage storage in tablespaces:  System managed space (SMS)  Database managed space (DMS)  SMS is appropriate if you do not want to pre-allocate the space for objects in a tablespace. With SMS, one or several directories are presented as container names. The directories must be available and empty during the tablespace creation. For very large SAP Systems, the directories should have their own file system on UNIX, residing on a separate disk. When an object (such as a table or an index) is created, a file is created in the directory. If an extent has been filled up, the file will be created on the next directory (SMS container). This is performed in a circular fashion. If an object is dropped, the files are deleted. If an object is reorganized, the file size is adapted. SMS is ideal for temporary tablespaces. Because of file system-overhead, SMS tablespaces are not used for small and medium sized tables. DMS is SAP's standard DB2 tablespace definition. With DMS-based tablespaces, containers are preallocated. Either by DB2 having FILE based containers, or by the system administrator having DEVICE based containers (such as RAW devices (UNIX) or PARTITIONS (NT)).     (C) SAP AG BC535 9-9 Temporary Tablespaces: Recommendations Temporary table life: 1. Table creation 2. Insertions ... N. Drop table PSAPTEMP File systems Table files are finally deleted Use SMS-based temporary tablespaces  SAP AG 1999    Based on the experience from SAP development, DB2 customer systems, and IBM Laboratory, SMS-based temporary file systems should be used for tablespace PSAPTEMP. Note: SAP Systems are installed on SMS-based temporary tablespaces by default. Temporary sort operations that cannot be accommodated in the SORTHEAP of a DB2 agent are accommodated in the buffer pool using TEMP(N,M) -tables. As soon as this temporary sort operation starts to compete with buffer pool usage for transaction processing, the temporary table spills out onto the temporary tablespace. Good layout of the temporary tablespace is mandatory for these large spilled sort operations. The space defined for the SMS-based temporary tablespace can be used elsewhere if not needed for large sorts. For example, the space can be used for EXPORT/LOAD space for high-speed offline table reorganizations.  (C) SAP AG BC535 9-10 Database Object Growth: Extent Allocation Tables 1 ”Space to grow" 1,5,6,7 3 9 5 11 2 8 4 10 6 7 12 Container 1 1 3 9 5 11 Container 2 2 8 4 10 6 12 2,3,8,9,10,11 ”Space to grow" 13 7 4,12 Container 1 1 7 3 9 5 11 Container 2 2 8 4 10 6 12 Tablespace full SQL0289C Container 1  SAP AG 1999 Container 2    When database objects grow, space is allocated at an extent level. If there is not enough free space in the container of a tablespace, the allocation of new extents fails. To avoid this, monitor tablespace growth regularly. Use the CCMS DBA Planning Calendar (transaction DB13) to analyze past and present tablespace growth behavior. If you encounter a SQL0289 error situation of your DB2 database, you must extend the tablespace. (C) SAP AG BC535 9-11 Database Object Growth: Out of Space Situation  Consequences of tablespace full situations     Additional data cannot be added to the tablespace Involved transactions are rolled back Extension of space has to be performed by DBA Extension of tablespace takes time DBA action Container 1  SAP AG 1999 Container 2 Container 3   When all containers are full, new space cannot be allocated even if data from other tables is deleted. Free space will only be available after a table is reorganized. Extending a DB2 tablespace is a DBA task that involves manual intervention. Therefore, you must first ensure your DB2 database is running in an uninterrupted mode. (C) SAP AG BC535 9-12 Monitoring Tablespace Growth: History  The maximum size of DB2 tablespaces is 64GB, 128 GB, 256 GB, or 512 GB  Careful planning is mandatory to avoid downtimes  The weekly or monthly growth of the tablespaces must be recorded to calculate if the limit will be reached or not  Table growth also impacts overall system performance  The database server machine sizing may have to be reevaluated  SAP AG 1999  For tablespaces larger than 64 GB, you must use different page sizes:  For page size of 4 KB, the maximum size of a tablespace is 64 GB  For page size of 8 KB, the maximum size of a tablespace is 128 GB  For page size of 16 KB, the maximum size of a tablespace is 256 GB (at least DB2 UDB V6.1)  For page size of 32 KB, the maximum size of a tablespace is 521 GB (at least DB2 UDB V6.1)  All tablespaces are installed with an initial page size of 4 KB. For large DB2 databases (such as in SAP Retail), you must create additional tablespaces on 8 KB or 16 KB pages to accommodate large SAP tables. If you define tablespaces with larger page sizes, you must define a new buffer pool with the same page size using the DB2 statement create bufferpool or using the DB2 Control Center. To reorganize tables in this new tablespace and temporary tables, you must define an additional temporary tablespace with the same page size. Since DB2 UDB maintains a limited storage area for the container information in a tablespace, there is an upper limit to the total number of containers for each tablespace. The maximum number of containers per tablespace is approximately 200. Since 64 GB is the maximum tablespace size with 4 KB page sizes, this limit is rarely reached in production systems since container-sizes are usually defined as 2 GB and larger.    (C) SAP AG BC535 9-13 Monitoring Tablespace Storage Allocation  SAP AG 1999  Use the DB2 UDB tablespace monitor to review the percentage of extents used within a tablespace. (C) SAP AG BC535 9-14 Monitoring Container Placement  SAP AG 1999   The container placement for tablespaces is critical for system performance. Review the appropriate layout of your database with the DB2 UDB container configuration monitor. (C) SAP AG BC535 9-15  Tablespaces are extended using the SQL statement alter tablespace. Since all information is in the DB2 log files, you do not have to back up the configuration files of a database even though this statement makes structural changes to the database. To add several containers to a tablespace without repeating the work of extending each container, use the DB2 CLP as shown here. The containers must be added in a single command. This command adds several containers in one SQL transaction. DB2 rebalances the tablespaces only once after the line has been entered and committed (if the AUTOCOMMIT option is set to On, this is done immediately). Ensure you use the correct path, file system, and naming conventions. If the location you enter is incorrect, the tablespace will be extended onto a wrong device. Then you will have to back up and restore the tablespace using a redirected restore. Note: Because the rebalancing process can affect I/O performance, it should only be performed during periods of low system activity.     (C) SAP AG BC535 9-16 Automated Rebalancing DB2 Extents Container 1 Before 1 7 3 9 5 11 Container 2 2 8 4 10 6 12 “Additional I/O" 1 4 7 2 11 5 8 3 12 6 9 After 10 Container 1 Container 2 Container 3  SAP AG 1999  This example shows the reassignment of extents towards the containers. Since there is a new container available, the extents must be redistributed for DB2. This ensures the use of highly efficient storage lookup after redistribution. However, since almost all of the extents will be moved, the I/O involved with extending a tablespace is considerable. Since runtimes on very large DB2 database may be very long, you should try to schedule the operation during periods of low system activity, such as on the weekends.   (C) SAP AG BC535 9-17 Monitoring Rebalancing Progress  The DB2 SQL statement alter tablespace is asynchronous  The rebalancing process is difficult to monitor  Since it is not an error situation, it is not written to the DB2DIAG.LOG at low DIAGLEVELS  A dedicated “rebalancer” reallocates the DB2 extents  Check UNIX systems with: ps -ef | grep db2rebal  SAP AG 1999  The added space for a tablespace is only available after the rebalancer has finished. (C) SAP AG BC535 9-18 DB2 Rebalancing Strategy  Rebalancing time is O(n), where n is the number of extents in a tablespace  If the runtime is linear, for example, but n is large, the runtime is still long  Rebalancing comparison    2 containers added in one transaction, runtime is O(n) 2 containers added in subsequent transactions, runtime: 2 x O(n) Plan ahead for several months using growth monitor  A large DB2 system should be installed on large containers  Maximum file size is operating system-dependent, but a 2-10 GB container size might be appropriate  New space is only available after rebalancing  SAP AG 1999   The complexity of the algorithm to rebalance a tablespace is linear. But with a high number of extents, this may still take hours to perform. Scenario: PSAPBDATD grows 20 GB within the next 6 months. Therefore, you extend a tablespace with 20 GB based on 2 new disks, thus having 2 containers with 10 GB each. If the disks are already available, it may be better to add both containers at the same time. This prevents you from having to run the rebalancing process within the next 3 months. Do not make your DB2 environment more complicated than necessary: if your DB2 database is going to be large, get the initial setup of your production database into a good position to grow. If - during production use - you realize that your database layout is not good, you will have to use the DB2 redirected restore to re-design the layout. This may involve extended downtime (for a BACKUP-RESTORE cycle) if there is no standby DB server. If there is a standby DB server, you may restore a DB2 backup using redirected restore onto the standby system. Then, using the log files form the production system, you can roll the database forward until end of logs. After shutting down the production database server, the most recent log files will be applied to the new system, the hostname and IP addresses are changed and the new DB2 database server can be made available.   (C) SAP AG BC535 9-19       Having structural changes to the database stored in DB2 log files allows containers to be re-built during roll forward operations. In very rare situations, this introduces another problem: A DB2 database is in production use, during this course a database backup has been taken. (1) During the use of the database, a tablespace is extended, since the DBA has foreseen growth in the tablespace. (2) One example can be IDOC, RFC, or Batch Input-based heavy inserts into the database. (3) The database becomes unusable because of a disk crash, recovery is needed. The database is restored and the log files are used to roll the DB2 database forward, one of the log files will contain the alter tablespace ... add command. Rebalancing is started and is running asynchronously with the roll forward operation. (4) Since roll forward may be faster than rebalancing, the new space will not be available in-time. The recovery will fail. (5) If you run into this situation, you must make sure that the space will be available up-front. This can be done during a redirected restore. For information about performing a roll forward recovery, see SAP Notes 44490 and 113862. Also, a backup that has been performed after the container addition will also contain the free space.    (C) SAP AG BC535 9-20 DB2 Redirected Restore: Redefinition of Storage DB2 command sequence to perform a redirected restore: 1 1 2 2 RESTORE DATABASE E4X FROM /dev/rmt0 TAKEN AT 19990420115337 INTO E4X WITH 2 BUFFERS BUFFER 1024 REDIRECT; SET TABLESPACE CONTAINERS FOR 0 USING ( FILE /db2/E4X/sapdata2/SYSCATSPACE.container001 32000); ... 3 3 4 4 RESTORE DATABASE E4X CONTINUE ; ROLLFORWARD DATABASE E4X TO END OF LOGS; The commands are generated by SAP tools  SAP AG 1999  The initial SAP redirected restore tool has been enhanced several times. Starting with R/3 4.6B, you will only need one executable brdb6brt. This tool generates a DB2 command line processor script that can be edited at your own convenience. With the new design, error-handling is simpler and a restart of the redirected restore can be performed more efficiently.   (C) SAP AG BC535 9-21 Table Reorganization Check in CCMS SAP DB2 REORG CHECK 3 3 1 1 2 2  SAP AG 1999  The CCMS DBA Planning Calendar (transaction DB13) is used to call the SAP DB2 REORG check tools. These tools are based on DB2 REORGCHK APIs. The output of the command is stored in SAP tables for efficient retrieval. To schedule this step, (1) double-click the day, (2) select the Update stratistics + reorgcheck all tables step, and (3) select the time. Note: The data provided is only accurate up to the runtime, which is suggested to be weekly. For accurate data, you must run the utility using transaction DB02.   (C) SAP AG BC535 9-22 Freespace Monitoring of Tables 2 2 1 1  SAP AG 1999   To review the “internal” freespace of a table, call the SAP R/3 DB2 Space Monitor, select Detailed Analysis from the Tables and Indexes tab, and enter the table name. A overview list appears. Double-click the requested table, and a detailed analysis list is shown. (C) SAP AG BC535 9-23 Monitoring Fragmentation of Tables in R/3 Table statistics for MONI Statistics updated Reorgcheck executed : : 2000-02-21 10:28:10.218000 2000-02-21 10:28:10.218000 Reorg. Recommendation Tablename................MONI Tableowner...............SAPR3 Table space..............PSAPBTABD Cardinality.............. 2.100 Overflow records......... 67 Number of pages with data 1.426 Total number of pages.... 2.426 Table size (kB).......... 4.502 Index statistics Indexname................MONI~0 Owner....................SAPR3 Table space..............PSAPBTABI Cardinality.............. 2.100 Number of leafs.......... 46 Number of levels......... 2 Distinct 1st key value... 12 First2keycard........... 922 First3keycard............ 2.100 First4keycard............ 1Fullkeycard.............. 2.100 Clusterratio............ 92 Clusterfactor........... -1,00000E+00 Sequential_pages........ 29 Density................. 87 Index size (kB).......... 0  SAP AG 1999 Overflown rows...........% tablesize / alloc.space..% full pages / alloc.pages.% 3 25 58 * * Reorg. Recommendation Clusterratio % indexsize / alloc.space..% number of entries..../... no. of possible entries..% 92 50 3 -  This detailed analysis shows the fragmentation data on tables and their indexes. (C) SAP AG BC535 9-24 Overflow Records  If record cannot be extended in-place, index RID info is not changed  An overflow record is written, containing the new RID Data OVL Data Data Data  SAP AG 1999 DB2 data page  Overflow records occur with tables defined using one or several VARCHAR data fields. If an inplace extension of these files in not possible, DB2 will place an overflow record into the original location of the row. It will contain the RID of the new location holding the extended record. Overflow accesses involve two read operations. They may be in-page, in-extent, but in the worst case, they may be out-of extend. This means the data is not in proximity of the original location and another page must be read. Overflow accesses may decrease I/O performance. But only a careful analysis of the situation will show you if a table has to be reorganized. Two examples:  Table MONI contains 67 overflow records, but the size is 4 MB. Even with heavy use of all of the rows of the table, this table may easily fit into buffer pool. There will not be any I/O impact.  Table ACCTID contains 10% overflow records, and the size is 5 GB. It will not fit into buffer pool, and large scans are made onto the table. With heavy read activity on the table, the table should be reorganized twice a year.   (C) SAP AG BC535 9-25 Index Cluster Properties Index Records 100 % clustered Good sequential prefetching versus n % clustered n < 100 Zero sequential prefetching  SAP AG 1999   When data is selected from the DB2 database, first an index is accessed, then - if the table column is not part of the index- data pages from a table are read. If the data records, which are stored in pages, and the index are clustered, DB2 can efficiently perform sequential prefetching techniques. This improves the speed of the availability of the data pages in buffer pool. If the data records, and the index are poorly, sequential prefetching cannot be performed. After the RIDs have been sorted by DB2, list prefetching may be used instead.  (C) SAP AG BC535 9-26 DB2 Table Reorganization in Same Tablespace Tablespace Table I Table II Reorganization in same tablespace Copy data into new location Tablespace Warning: This is not possible with very large tables or if the tablespace has low freespace  SAP AG 1999   The reorganization of tables within their own tablespaces is only recommended for very small tables. When a table is reorganized in the same tablespace, the data is moved to a new location within the tablespace. After the reorganization, some space may be available in the database, and the table will be unfragmented. (C) SAP AG BC535 9-27 Reorganizing Tables Using Tablespace TEMP Tablespace Table I Table II Temporary tablespace Reorganization in temporary tablespace Tablespace Copy data into PSAPTEMP Warning: This is not possible with very large tables  SAP AG 1999   Reorganizing tables should only be performed in exceptional cases only. It is not a daily task. During a reorganization, your R/3 System may stay up and running. However, your will not to be able to run a heavy transaction load on the tables that are reorganized, and many deadlocks may occur. Since the temporary tablespace PSAPTEMP is used to copy the table, you must make sure that this tablespace can hold all the data of the copied table. In general, it should have twice the physical size of the table according to the tables and indexes monitor (transaction DB02). If the online reorganization using PSAPTEMP fails, the transaction is rolled back. No data is lost. The online reorganization of the database is scheduled using the R/3 CCMS DBA Planning Calendar (transaction DB13). Very large tables should not be reorganized using the online method. For reasons of performance and storage, you should schedule downtime to perform an offline reorganization using either:  REORG TABLE, with a temporary tablespace that has been created for this purpose, or  The DB2 EXPORT and DB2 LOAD commands to move the table out of the tablespace. If you use this method, you must drop the table (since the command delete from logs every record that is deleted) then you must re-create the table using the R/3 DDIC. Then, the DB2 command LOAD is used to load the exported table into the tablespace without any logging. This method improves the performance of the reorganization, but requires system downtime.     (C) SAP AG BC535 9-28 Reorganization Tools in CCMS 3 3 1 1 2 2  SAP AG 1999  To reorganize a table using the CCMS DBA Planning Calendar (transaction DB13), you must (1) select the day of reorganization, (2) select the activity Reorganize flagged tables & update statistics, and (3) select the flagged table and choose OK. You cannot reorganize a table that has not been flagged, unless you select the activity Reorganize all tables in tablespace(s). This prevents unnecessary reorganization efforts.  (C) SAP AG BC535 9-29 Reorganizing Large Tables  Table reorganization also involves index reorganization  Space consumption is at least twice the size of the table  The R/3 DB2 database can be up and running during REORG, but access to the table is blocked  Using EXPORT/LOAD, you will improve performance, but your tablespace must be offline  Index creation for very large tables needs large temporary tablespaces  Consider enabling online index reorganization instead of reorganizing tables  SAP AG 1999 (C) SAP AG BC535 9-30 Online Index Reorganization Table Reorg table: Reclaim space Re-align records according to index Online index reorg: reorg: Reclaim leaf pages Index MINPCTUSED clause: Defined during index creation Reorganization is automatic  SAP AG 1999  If the MINPCTUSED clause is applied, DB2 UDB reorganizes indexes online. MINPCTUSED defines the minimum percentage of used space on a page. MINPCTUSED can be defined when indexes are created or rebuilt. During run time, index leaf pages are reclaimed as deletions from these pages take place. This means, no explicit command is needed to reorganize the indexes. A backward leaf pointer points to the previous leaf page (the leaf to its left) in the index's B+ tree. Two index leaf pages are merged by moving the keys from the left leaf page to the right leaf page. Once the left leaf page is empty, it is deleted. For example, if - as keys are deleted - the used space on a page is lower than the threshold defined, an attempt to merge this page with its neighboring page is made. The high key for the deleted leaf page is removed from the page's parent. If this causes the parent to become empty, it will also be deleted and its high key is removed from its respective parent. This deletion process is propagated up the B+ tree as necessary, in the same way that node deletions are propagated up the tree.    (C) SAP AG BC535 9-31  When creating tablespaces, certain rules apply:  For all tablespaces with a page size other than 4 KB, you must make sure that a buffer pool with the same page size exists.  A temporary tablespace with the same page size must exist to allow the spilling of pages to disk.  DB2 must have all tablespaces of a “spanned” object with the same page size. A spanned object is a table with regular data in one tablespace, index data in another tablespace, and long data (long varchar and LOB objects) in another tablespace.  Since LONG tablespaces are not buffered, never put their containers on a RAW device.  Since REGULAR and INDEX tablespaces are buffered, you can put the containers of these tablespaces onto RAW devices to reduce CPU usage. (C) SAP AG BC535 9-32 Unit Summary Now you are able to:  Understand the space allocation of the R/3 DB2 database  Reclaim space as it is freed up by R/3 or archiving  Extent the database using zero-downtime techniques  SAP AG 1999 (C) SAP AG BC535 9-33 Unit Actions ?  Do the exercises  Solutions for the exercises  SAP AG 1999 (C) SAP AG BC535 9-34 Storage Management: Exercises No. 1 2 Exercise Check whether there are space problems in a specific tablespace. Is it necessary to extend those tablespaces right now? Will be there any space problems in the next 10 days? Justify your decision. What about PSAPTEMP? Explain why PSAPTEMP is 100% allocated and if this is a space problem. 3a 3b 4 Extend tablespace PSAPBTABD of your test database. Describe your procedure in the form of a checklist. From what point in time on can you use the added freespace? Which is the largest table having a critical number of empty pages? How could you change this? What prerequisites regarding freespace in tablespaces have to be fulfilled to do so? Would your system fulfill this condition? How can you meet this need? (C) SAP AG BC535 9-35 Storage Management: Solutions No. 1 Solution To check if there are space problems, choose Tools  Administration  Monitoring  Performance  Database  Tables/Indexes (or call transaction DB02). To display an overview of tablespace space consumption, choose Detailed analysis from the Tablespace section of the screen. 2 To determine if the tablespaces have to be extended, double-click a tablespace and select History. This will provide a basis for further analysis. If several tablespaces have rather high usage rates, which have been almost static, you do not need to increase them. The tablespace of PSAPTEMP is SMS. All other tablespaces are DMS. SMS tablespace are only allocated as much as needed. 3a To extend the tablespace, you must first determine the location (that is, the directory or file system), the number of containers, and the size of the tablespace you want to increase. Check for sufficient freespace in the target directory or file system of the new container. To add the new container using the DB2 CLP, first issue command db2 “list tablespace containers for 23” to get an output of all containers allocated for PSAPBTABD. Note: Remember to use the same container size for all containers of a tablespace. To extend the tablespace, create a file tcon.sql, and then insert the following command alter tablespace PSAPBTABD add (FILE „/db2/db2t0/T/sapdata4/PSAPBTABD.container002‟ 256); Apply the command using db2 –tvf tcon.sql. 3b 4 Check the successful completion of the rebalancing process, which makes the added freespace available using DB2’s diagnostic file db2diag.log. To check the size of the tables, from the Tables and Indexes section of transaction DB02, choose Detailed analysis menu. Select all tables (*) and tablespaces (*). By sorting the output by the table size and scrolling down, you can determine the largest table having critical empty pages. Reorganize the table. When you reorganize this table, remember that PSAPTEMP file systems must be two to three times as large as this table. To check the size of the table and the tablespace, use transaction DB02. Increase the tablespace. (C) SAP AG BC535 9-36 (C) SAP AG BC535 10-1 Performance Monitoring Contents:  DB2 UDB Cost-Based Optimizer Review  Memory configuration  Application design  Physical and logical layout: Minimizing and enabling parallel I/O Objectives: At the end of this unit you will be able to:  Define a strategy for refreshing the statistics used by the CBO  Identify performance problems caused by the CBO, memory configuration, the application design, or by the physical and logical layout  SAP AG 1999 (C) SAP AG BC535 10-2   Database performance problems normally result from poor configuration of the database memory configuration, application design problems, or incorrect physical or logical layout. This unit focuses on the steps you should take to identify and correct the performance problems using R/3. For normal tuning, perform the following steps as recommended by SAP:  Check the general database configuration. (1)  Use the R/3 database tools to verify the efficiency of the application design. (2)  Check that the update statistic strategy is sufficient. (3)  Verify the physical and logical layout. (4) (C) SAP AG BC535 10-3  This section covers DB2 memory configuration, and explains how to determine the:  Proper size of the buffer pool, which helps to achieve adequate hit ratios.  Correct usage of the package and catalog cache, and proper size for these caches.  Proper size of the lock list, and an adequate amount of memory for lock objects.  Proper size of the sort heap, which helps to avoid sort and sort threshold overflows.  Note: The best reference for database monitoring and performance tuning measures is the “DB2 System Monitor Guide and Reference”. This book contains detailed discussions of the monitoring elements provided by DB2. (C) SAP AG BC535 10-4 DB2 Memory Configuration 1 Database global memory Utility heap (UTIL_HEAP_SZ) Backup buffer (BACKBUFSZ) Restore buffer (RESTBUFSZ) Buffer pool (BUFFPAGE) Lock list (LOCKLIST) Ext. memory cache Database heap (DBHEAP) Log buffer (LOGBUFSIZ) Catalog cache (CATALOGCACHE_SZ) Package cache (PCKCACHESZ) DB2 memory usage  SAP AG 1999  DB2 allocates memory in the following steps:  The database manager is started, and global control blocks are allocated  The first application connects to the database or an activate database is issued, and global and private memory areas are allocated  Most memory heaps are only allocated as required. Exceptions to this rule are listed below. These heaps are allocated at database start:  Package cache  Buffer pool(s)  Lock list  Application support layer (ASLHEAPSZ)  As a rule of thumb, use this formula to determine the memory that is allocated as a minimum:  Minimum DB2 memory = Buffer pool (BUFFPAGE 4 KB) + Package cache (PCKCACHESZ 4 KB) + Database heap (DPHEAP 4 KB) + Lock list (LOCKLIST 4 KB) + Utility heap (UTIL_HEAP_SZ 4 KB) + (Number of DB2 agents * 10 MB). (C) SAP AG BC535 10-5 Database Memory Configuration 2 Agent private memory Application heap (APPLHEAPSZ) Query heap (QUERY_HEAP_SZ) Agent stack (AGENT_STACK_SZ) DRDA heap (DRDA_HEAP_SZ) Statistics heap (STAT_HEAP_SZ) Sort heap (SORTHEAP) Statement heap (STMTHEAP) UDF memory (UDF_MEM_SZ) Client I/O block (RQRIOBLK) Agent / Application shared memory Application support layer heap (ASLHEAPSZ) Application shared memory Local client Client I/O block (RQRIOBLK) DB2 memory usage Remote client  SAP AG 1999  The agent private memory is also allocated by the database manager to store data for client applications. (C) SAP AG BC535 10-6 Memory Configuration 3    The buffer pool functions as a cache for the database The package cache caches parsed SQL statements The catalog cache caches data dictionary information from the database Memory area Database global memory RDBMS Buffer pool SELECT * FROM MARA WHERE ... Logical reads Database heap Package cache R/3 work process DB2 agents parsed SQL statements and execution path Catalog cache dc information about objects of the database Physical reads Database Table spaces PSAPBTABI Container  SAP AG 1999 PSAPSTABD ... System  Buffer pools: Buffer pools provide the storage for data and index pages. Buffer pools function as an optimized cache for the database to improve database system performance. Since this cache optimizes its strategy for database use, it is better to use the buffer pools than to use a large file system cache. The goal is to minimize disk accesses (physical reads) and to maximize buffer pool access (logical reads). The size of the primary buffer pool is controlled by the DB2 parameter BUFFPAGE. There is at least one buffer pool per database. Depending on your performance analysis, you can also define buffer pools at tablespace level. Package cache: After a dynamic SQL statement is compiled and used by a DB2 agent, its access plan (package) is cached in the package cache. Other DB2 agents executing the same statement again use the version already compiled in the package cache, and thus avoid the cost of compilation. This process is also known as preparation. Catalog cache: The catalog cache stores binary and compressed descriptors for tables, views, and aliases. Each time a dynamic SQL statement is compiled, the system reads queries from system tables to gather information about all tables, views, and aliases. Descriptors are held in the catalog cache to avoid reading from disk.   (C) SAP AG BC535 10-7 Memory Configuration 4   Lock list contains the locks held by all applications Sort heap is used for sorting Memory area Database global memory RDBMS Buffer pool R/3 work process DB2 agents Agent private memory Sort heap Lock list Maximum storage for lock list Database Table spaces PSAPTEMP Container  SAP AG 1999 PSAPSTABD ...  Lock list: Locking is the mechanism used by the database manager to control concurrent access to data. Both rows and tables can be locked. There is one lock list per database, it contains the locks held by all applications concurrently connected to the database. Its maximum size is 256 MB. With 64 bytes for the first lock on an object and 32 bytes for subsequent locks on the object, at least 400,000 row locks can be set before problems arise. Sort heap: The sort heap is used for sorting. Sorting is required for a query, for example if the order by clause is used in the SQL statement. If the configuration of the sort heap is not adequate for a query, a temporary table(s) in PSAPTEMP is used to handle the sort request.  (C) SAP AG BC535 10-8 Buffer Pool Considerations Database performance analysis: DB2 for NT database overview DB analysis Goto Monitor System ?   Help     Refresh Database DB Server Buffer Pool Detail analysis menu D3G is0010 Day, Time Since Start up 08.10.1997 23.09.1997 09:38:49 15:18:25 Database summary Size Overall buffer quality Sync. buffer quality Av. phys. read time AV. phys. write time Av. sync. read time Database files closed KB % % ms ms ms 40000 94,97 98,11 4,71 43,46 0,21 0 Data Logical reads Physical reads Physical writes Index Logical reads Physical reads Physical writes Data Synchronous writes Data Synchronous reads 15722530 895300 28752 10275767 411864 730 11942 78515  SAP AG 1999  Buffer pool size: The number of pages allocated for the default buffer pool IBMDEFAULTBP in KB. To display sizes for other buffer pools, call transaction ST04 and choose Detailed Analysis Menu  Buffer Pools. Overall buffer quality: This represents the ratio of physical reads to logical reads in the default buffer pool IBMDEFAULTBP. Data synchronous writes: This is the number of write operations that do not use buffer pools. They are writes to tables containing long varchar fields. Since these operations are not buffered, you should usually put tablespaces containing these tables onto DMS file type containers. File system buffering helps to improve performance. Note that most SAP tables with long fields are buffered by the application servers (For example, ABAP Repository in D010S) Data synchronous reads: The number of read operations that cannot use the buffer pool (again, long fields are involved). Buffer pool data pool hit ratio: In addition to overall buffer quality, you can use the Buffer pool data pool hit ratio to monitor the database: (data logical reads - data physical reads) / (data logical reads) * 100% Buffer pool index pool hit ratio: In addition to overall buffer quality, you can use the Buffer pool index hit ratio to monitor the database: (index logical reads - index physical reads) / (index logical reads) * 100%.      (C) SAP AG BC535 10-9 Assessing the Efficiency of the Buffer Pool Database performance analysis: DB2 for LINUX database overview DB analysis Goto Monitor System ?   Help     Refresh Database DB Server Buffer Pool Detail analysis menu D3G is0010 Day, Time Since Start up 08.10.1997 23.09.1997 09:38:49 15:18:25 Database summary Size Overall buffer quality Sync. buffer quality Av. phys. read time AV. phys. write time Av. Sync. read time Database files closed KB % % ms ms ms 40000 Data Logical reads 94,97 >95 Physical reads 98,11 Physical writes 4,71 Index Logical reads 43,46 Physical reads 0,21 Physical writes 0 Data Synchronous writes Data Synchronous reads 15722530 895300 28752 10275767 411864 730 11942 78515  SAP AG 1999      The overall buffer quality should be >= 95%. The buffer pool data hit ratio should be >= 95%. The buffer pool index hit ratio should be >= 98%. However, the hit ratio is not optimal after a RUNSTATS or REORG. Warning: You should only evaluate the values after your system has been up and running with a typical workload for some time. For the first few hours after startup, you will have poor hit ratios. Usually you must wait until the number of select statements has exceeded 1,000,000. (C) SAP AG BC535 10-10 Increasing the Size of the Buffer Pool Hour Pages in Pages out /h /h 11 227 2.162 626 22 22 42 74 3.034 1.648 22 29 89 83 33 1.063 22 8.157 22 128 4.046 53 281 39 0 0 2.542 464 0 0 64 64 2.363 1.106 0 0 0 0 0 0 0 2.435 0 0 3.056 0 0 0 Paged in Paged out [Kb/h] [Kb/h] 44 908 8.648 2.504 88 88 168 296 12.136 6.592 88 116 356 332 132 4.252 88 32.628 88 512 16.184 212 1.124 156 0 0 10.168 1.856 0 0 256 256 9.452 4.424 0 0 0 0 0 0 0 9.740 0 0 12.224 0 0 0  Parameter BUFFPAGE Use the Operating System Monitor to analyze the operating system paging statistics before and after increasing BUFFPAGE 13 12 11 10 9 8 7 6 5 4 3 2 1 0 23 22 21 20 19 18 17 16 15 14  SAP AG 1999   If the hit ratio is lower than 94%, you should increase the buffer pool. In addition, we recommend performing a Dynamic SQL Cache Analysis. To increase the size of your database buffer, change DB2 parameter BUFFPAGE (which is specified in 4 KB pages). This parameter specifies the number of database pages buffered in memory.  Note: When you increase this parameter you are reducing the memory available to other processes in the system, which may cause OS paging and/or swapping to occur.  To check the OS paging, use the OS Monitor (transaction ST06) and choose Detailed Analysis Menu  Previous Hours: Memory (UNIX: Pages out; NT: Pages in). Each hardware platform has an upper limit on the total amount of shared memory that can be allocated. The sum of the fixed and variable portions (buffer pool, database heap, lock list, package cache, and utility heap) of the database global area cannot exceed this amount.  (C) SAP AG BC535 10-11 Package and Catalog Cache Considerations Database performance analysis: DB2 for NT database overview DB analysis Goto Monitor System ?   Help     Refresh Detail analysis menu Caching Catalog cache size Quality KB % 256 Catalog cache lookups 99,67 >90 Catalog cache inserts Catalog cache overflows Catalog cache heap full 2048 Package cache lookups 72,06 >98 Package cache inserts 137497 457 0 =0 0 396419 110773 Package cache size Quality KB %  SAP AG 1999         Package cache size: Maximum size of the package cache that is used to maintain the most frequently accessed sections of the package. Package cache quality: Ratio of package entries (inserts) to reused package entries (lookups). Catalog cache size: Maximum size of the catalog cache that is used to maintain the most frequently accessed sections of the catalog. Catalog cache quality: Ratio of catalog entries (inserts) to reused catalog entries (lookups). Catalog cache overflows: Number of times that an insert into the catalog cache failed due the catalog cache being full (increase catalog cache size ). Catalog cache heap full: Number of times that an insert into the catalog cache failed due to a heapfull condition in the database heap (database heap too small). The package cache quality should be >= 95%. The catalog cache quality should be >= 90%. (C) SAP AG BC535 10-12 Sorting Area Considerations Database performance analysis: DB2 for NT database overview DB analysis Goto Monitor System ?   Help     Refresh Detail analysis menu Sorts Total sort heap size Sort heap allocated Total sorts KB KB 2048 0 32757 Sort overflows Active sorts Total sort time 44 0 424665 ms  SAP AG 1999      Total sort heap size: The maximum size for the sort heap used to sort data indexes or data pages. Sort heap allocated: The total number of allocated pages of sort heap space for all sorts at the level chosen and at the time the snapshot was taken. Sort overflows: The total number of sorts ran out of sort heap and may have required disk space for temporary storage. Monitor the relation between Total sorts and Sort overflows to find out if the sort heap is too small for your system. Sort overflows should not exceed 1% of total sorts. Use the database manager snapshot to monitor the piped sorts and the post threshold sorts. To do this, use the command db2 get snapshot for database manager. Monitor the following entries:  Post threshold sorts: Number of sorts that have required heaps after the sort heap threshold has been reached.  Piped sorts requested: Number of piped sorts that have been requested.  Piped sorts accepted: Number of piped sorts that have been accepted. (C) SAP AG BC535 10-13 Understanding Overflow Sorts DB2 UDB SELECT * FROM MARA WHERE MANDT=001 AND MTART LIKE .... ORDER BY STOFF R/3 work process DB2 agent Agent private memory Sort heap DB2 instance Agent private memory private Agent memory private Agent Sort heap memory Agent Sort heap private memory Sort heap Sort heap Sort heap threshold  SAP AG 1999 Buffer pools(s) Database PSAPTEMP  If the information being sorted is larger than the sort heap that is allocated within the agent private memory, a sort overflow occurs, and a temporary table is created. In case of small buffer pools, this table might even spill over onto disk storage of the PSAPTEMP tablespace. If the result of a sort cannot return directly, a temporary table is used to store the final sorted data. (non piped sort). The maximum size of the sort heap is configured in the DB2 parameter SORTHEAP The total amount of memory for sorting available in the DB2 instance is configured in the DB2 instance parameter SHEAPTHRES (sort heap threshold). This parameter represents a soft limit; that is, if this parameter is reached, new sort heap requests will receive only small amounts of memory.    (C) SAP AG BC535 10-14 Lock List Considerations Database performance analysis: DB2 for NT database overview DB analysis Goto Monitor System ?   Help     Refresh Detail analysis menu Locks and Deadlocks Lock list size Lock list in use Lock escalations Excl. lock escalations KB KB 12800 Total lock waits 9 Time waited on locks ms 0 Locks currently held =0 0 Deadlocks detected Lock timeouts 44 272048 10 0 0  SAP AG 1999       Lock list size: This indicates the amount of storage allocated to the lock list. One lock list exists on each database and contains the locks held by all applications concurrently connected to that database. Lock list in use: The total amount of lock list memory that is in use. Lock escalations: The number of times that locks have been escalated from multiple row locks to a table lock. Excl. lock escalation: The number of times that locks have been escalated from multiple exclusive row locks to an exclusive table lock. Deadlocks detected: The total number of deadlocks that have occurred. To monitor the previous lock situations, go to transaction ST04 and choose Detailed analysis menu  Performance database  More. Check the columns Deadlocks, Lock esc (Lock escalations), and X Lock Esc (exclusive lock escalations). (C) SAP AG BC535 10-15  This section covers inefficient application design, and how you can identify:  Lock wait situations  Unnecessary SQL statements  Inefficient SQL statements, which result in high database load  Poorly qualified statements that do not make use of indexes (C) SAP AG BC535 10-16 When a Lock Wait Situations Occurs 4. Work process Update Requests MARA MARA lock WAITING ... 3. Work process Update Requests MARA MARA lock WAITING! Acquires Working... MARA lock 2. Work process Update Requests WAITING! Acquires MARA MARA lock MARA lock Working... Commit 1. Work Update Acquires process MARA MARA Lock A long period Commit of processing MARA locked by WP 1 WP 2 WP 3  SAP AG 1999  A lock wait situation occurs when a work process requests a lock on an object that is already locked by another work process. In order for the database to maintain transactional consistency, the object is locked by the process that requests it first. If a user starts a logical unit of work and updates an important object, for example, the most popular material number of the company, then all other users who want to update the same material must wait until the first user has committed the changes before they can get the record. The duration of such update transactions is typically very short. A user holding a lock occupies an R/3 work process. Other users trying to apply the same lock have to wait and at the same time they occupy their own R/3 work process. As the number of lock waits increases, fewer and fewer R/3 user requests can be processed by available R/3 work processes. In the worst case (lock holders and waiters = number of R/3 work processes), a small number of users can cause the entire R/3 System to “freeze”. With DB2 database servers, several hundred thousands of row locks are transformed into a single table lock if the DB2 lock list is fully utilized. If the row locks are update-locks, the table lock is an exclusive one. The concurrency of the R/3 System is heavily impacted.    (C) SAP AG BC535 10-17 Identifying a Lock Wait Situation with R/3 31.03.1999 13:43:13 TC1 twdfm401 Exclusive session-lock situations Lock-Holder Agenthdl. Lock-Waiters Agenthdl. 91 158 453 84 Agent PID Appl. Name db2bp.exe db2bp.exe Client Lock Lock Tableschema Tablename Mode PID Type Lock Mode requested 431 Table X SAPR3 SVERS 462 Internal S LW Start Time Waittime (sec.) Mar 31 13:43:05 1999 7 DB2 agent, application  SAP AG 1999    In this example, the lock wait situation was created manually using the DB2 CLP. To identify exclusive lock wait situations, use the Exclusive Lockwait Monitor (transaction DB01) and check the lock holder, number of lock waiters, lock mode, and lock type. To find the DB2 agents involved in the lock wait situation, call transaction ST04 and choose Detailed Analysis Menu  DB2 Applications. Check the entry in the column DB2 agent. The last column SQL statement contains the SQL statement processed by the DB2 agent. For each database object (table or row), the initial lock size for one lock in the lock list is 64 bytes. For additional locks on the same object, 32 bytes is consumed in the lock list.  (C) SAP AG BC535 10-18 Reducing Exclusive Lockwaits  Redesign the application to reduce the locking period by:    Increasing the commit frequency in the application Not allowing a single process to hold a lock for a long period Locking the object as late as possible  Adjust the job scheduling cycle so that lock situations do not occur  SAP AG 1999  Exclusive lock waits usually occur because:  A user holds the lock too long - For example, a user may be processing large amounts of data in the background. Only explicitly committing the changes on the updated records would enable update access for other users. The solution here would be to analyze the application and determine whether more commits can be safely built into the application.  Many users want the same record in high-volume processing - For example, in mass loading of FI documents, users may all want to update the same general ledger account. Though each individual lock wait may not take long, the sum of all lock waits can significantly reduce the speed of the mass load. Here, a possible solution would be to sort the data to mix up the accesses to GL accounts. (C) SAP AG BC535 10-19 Application Problems: Unnecessary Statements SELECT * FROM MARA WHERE MANDT=001 AND MTART LIKE .... R/3 work process DB2 UDB Buffer pools(s) Package cache DB2 agent Parsed SQL statements and execution path Catalog cache dd information about database objects Optimizer Database SQL Trace Tables MARA Indexes MARA_0 MARA_1 ... System  SAP AG 1999    Unnecessary SQL statements are statements that are executed repeatedly with exactly the same WHERE clause. To avoid this problem, you can build internal tables to buffer the data whenever possible. To identify unnecessary SQL statements, you can use the SQL Trace tool. The SQL Trace tool is part of the database interface and records all commands sent to the database and their results. (C) SAP AG BC535 10-20 Identifying Unnecessary SQL Statements System - Utilities - SQL Trace  ? Detail DDIC info  Explain SQL PID= 0000017643 Client= 900 User= WRKL0 Operator REOPEN FETCH CLOSE REOPEN FETCH CLOSE REOPEN FETCH CLOSE REOPEN FETCH SELECT WHERE "MANDT" = 900 AND "MATNR" = 0010 Records: 1 Returncode: +0 SELECT WHERE "MANDT" = 900 AND "MATNR" = 0010 Records: 1 Returncode: +0 SELECT WHERE "MANDT" = 900 AND "MATNR" = 0010 Records: 1 Returncode: +0 Statement SELECT WHERE "MANDT" = 900 AND "MATNR" = 0010 Records: 1 Returncode: +0 Transaction/Report= XY01 Duration 104 1.056 1.411 106 1.048 1.411 102 1.113 1.411 104 1.009 T D D D D D D D D D D D Table MARA MARA MARA MARA MARA MARA MARA MARA MARA MARA MARA ...  SAP AG 1999  This example shows SQL Trace output when the same SELECT statement was executed repeatedly. (C) SAP AG BC535      10-21 Eliminating Unnecessary SQL Statements WHILE.. Select * from MARA where. ENDWHILE 1 Select * from MARA where.... Store output into Internal Memory Structure WHILE PROCESSING 2 ENDWHILE BUFFER TABLE MARA in R/3 Buffer by allowing buffering for MARA table  SAP AG 1999  There are two basics solutions to this problem:  Change the application program to keep track of the information it has already read in its own program memory (that is, build internal tables)  Use the SAP mechanisms for buffering tables, but you must consider the following: - Table size: Only small tables can be buffered - Technical settings: Check whether the technical settings allow buffering (use transaction SE12) - Update frequency: Only tables with a small number of updates can be buffered (C) SAP AG BC535 10-22 Application Problems: Poorly Qualified Statements SELECT * FROM MARA WHERE MATERIAL = 10001 Full table scan O(n) Index scan O(log n) TABLE MARA Index MARA~O Transaction = Duration 122.823 Object DD04T PID = 38300 P type DIA Client = 100 User = BS101 DB op REOPEN Rec RC 0 SQL statement SELECT WHERE“ROLLNAME”=“VHIART”  SAP AG 1999   Indexes are used to access data efficiently. A poorly qualified SQL statement exists if an index is not used correctly. For example, poorly qualified statements occur because:  No appropriate index is associated with the table being accessed  A secondary index is needed for the query being performed  The wrong index is used  An index is used unnecessarily. A full scan is more effective, for example, if: - Small tables are accessed - A high number of records is retrieved  The index used was defined incorrectly  To avoid poorly qualified statements, try not to use "SELECT * FROM ..." statements wherever possible. Do not change the standard R/3 index design. This should only be performed by SAP experts. Create a customer message on SAPNet for a problem caused by an R/3 report. For more information about these statements, run transaction SE30 and choose Tips&Tricks.   (C) SAP AG BC535 10-23 Analyzing a Poorly Qualified Statement M System catalog information Only one index column is used  SAP AG 1999  By executing an Explain plan on an SQL statement, you can determine if a index is being used to access the data. To get the Explain plan, mark the appropriate line in the SQL Trace and choose Explain. Use the system catalog info to obtain DB2‟s statistical information about the table or the index. The statistical information provides information about the number of rows (card) stored in the table. For each index column, a distinct value is displayed. Use this information to judge if the column is selective. Use the firstXkeycard information of the index statistics to check if the SQL where list columns reach a sufficient selectivity. The SQL statement can be identified as belonging to a program through the WHERE-USED list option in the Data Dictionary (transaction SE12). Using the SQL Trace, the ABAP-display option takes you directly to the ABAP report.   (C) SAP AG BC535 10-24 Performing an Explain Plan: Details  SAP AG 1999   To display more information about the optimizer strategy, from the Explain plan, choose Details. The Details screen shows the information about the following:  Index scan: For each index scan operator, information is shown about: - The index columns being used - Which columns of the index referenced directly by using the where-list-values - For which columns of the index a range scan is performed - Which where-list-values are used as a start and stop predicate for delimiting a range scan (Look for columns followed by “(A)” for a range scan or for returning a range of values)  Prefetching: For each operator in the detail report, information about if the CBO used prefetching or not is shown. (Look for: Arguments: PREFETCH: SEQUENTIAL or LIST or NONE)  Input/Output Streams: For each operator in the detail report, information about the input/output data stream is shown. Use this information to follow the data processing flow of the access plan. (C) SAP AG BC535 10-25 Identifying Missing Indexes in Database  Database Performance Tables and Indexes Menu Tables and indexes Total number Total size/KB Missing on database Missing in R/3-DDIC Tables 13.056 3.730.039 0 1 Indexes 15.317 2.354.458 0 0 Detailed analysis Missing indexes Space statistics Missing indexes test from 18.05.1999 07:00:20 Indexes missing from the database Primary indexes Secondary indexes DB indexes 0 0 0 0 Unknown indexes in the Data Dictionary Optional indexes Too many indexes created  SAP AG 1999  Poorly qualified SQL statements can be caused when an index is defined in the R/3 Data Dictionary but is missing in the database. Missing database indexes can be discovered using the Tables and Indexes Monitor (transaction DB02). Common reasons for missing indexes are:  Indexes that are defined in the Data Dictionary but not activated  Indexes that are manually dropped for tests     The report on missing indexes is created as part of the Performance Collector background job. The check on missing indexes should be performed once a week. If necessary, you can also check for the index by querying the DB2 Data Dictionary using the DB2 CLP. Indexes can be created, redefined, or dropped. (C) SAP AG BC535 10-26 Dynamic SQL Cache Analysis Date of last SQL Cache Output stored in R/3 Get new SQL cache output Display SQL cache output stored in R/3  SAP AG 1999  The Dynamic SQL Cache Analysis contains information about the runtime of all dynamic SQL statements in an R/3 System. To perform this analysis, call transaction ST04 and choose Detailed Analysis Menu  DB2-SQL Cache. The first screen displayed does not contain any SQL statements. Before you display the SQL Cache consider the following input criteria:  Last snapshot: Shows the timestamp of the SQL cache output, which is stored in R/3.  Display: Displays the output of the SQL cache, which is stored in R/3. Display does not get the latest SQL cache from DB2.  Refresh: Displays the latest SQL cache from DB2 and stores this in an R/3 table. Refresh does not display the SQL cache output on the screen.    To check the timestamp of the last SQL cache snapshot, you can either choose Display or get a new SQL cache snapshot by choosing Refresh. Note: To show the SQL statements on the screen, always choose Display. (C) SAP AG BC535 10-27 Analyzing the Dynamic SQL Cache Explain the statement you are going to analyze Export SQL cache output in a spread sheet format Start to analyze SQL statements that have a greater share on the total response than ~ 5% Mark the statement you are going to explain Use # Executions and Total Execution Time to determine the average execution time per statement (single statement execution time sufficient?)  SAP AG 1999   When analyzing the dynamic SQL cache, only consider the SQL statements that have a greater share on the total response time greater than 5%. To determine the average execution time per statement, use columns #Executions and Total Execution Time. Use this value to determine if the statement has a large share of the Total Execution Time because:  The single statement execution is sufficient, and the high number of executions are the reason why the share on Total Execution Time is high (possibly an unnecessary statement).  The single execution is not sufficient, but together with the number of executions, this is the reason why the share on Total Execution Time is high (possibly a poorly qualified statement).  Use the system catalog info to obtain DB2‟s statistical information about the table or the index. The statistical information provides information about the number of rows (card) stored in the table. For each index column, a distinct value is displayed. Use this information to judge if the column is selective. Use the firstXkeycard information of the index statistics to check if the SQL where list columns reach a sufficient selectivity. (C) SAP AG BC535 10-28 Analyzing SQL Sorts Sort columns “SQL Sorts” descending  Start to analyze SQL statements that have a high number of SQL sorts  Check if a proper index could avoid sort operation  SAP AG 1999   Sort the SQL Sorts column in descending order. Analyze the statements that have a high number of SQL sorts (as a rule of thumb, check the statements that have more than 5% of the total sorts). Use the Explain plan to find out if a proper index design could avoid the sort operations. (C) SAP AG BC535 10-29 Understanding DB2's FETCH Statements A high number of records is selected by the previous SQL statement Only one FETCH entry is displayed for getting all the data to the R/3 work process  SAP AG 1999   This example shows SQL Trace output where an array fetch occurs. As of R/3 Release 4.6B (for DB2 UDB on UNIX and NT), the SQL Trace output for fetches has changed. The output display now contains one fetch entry for each call that retrieves data (a fetch) from the application layer to the database layer within the R/3 work process. The fetch entry is no longer used for each call from the database layer within the R/3 work process to the database server to retrieve data. For each single fetch between an ABAP SELECT .... ENDSELECT statement, one fetch operator is displayed.  (C) SAP AG BC535 10-30  This section describes how to:  Refresh the statistics used by the Cost-Based Optimizer.  Check if the update statistic jobs finished successful.  Modify the standard procedure used for refreshing the optimizer statistics. (C) SAP AG BC535 10-31 Refreshing the Object Statistics  Is a daily update statistic job scheduled?  Is a full update statistic job necessary?  Is update statistic only performed by dmdb6srp?  SAP AG 1999  To ensure that DB2‟s Cost-Based-Optimizer decisions are based upon current statistic, you must schedule two kind of update statistics jobs:  Daily update statistic jobs - Updates only those tables that have an active TODO flag in control table DBSTATC - Should be scheduled on a daily basis using the DBA Planning Calendar or by scheduling SAP‟s executable dmdb6srp at the operating system level.  Full update statistic jobs - Updates all tables but follows exceptions in the control table DBSTATC - Should be scheduled on a as needed basis using the DBA Planning Calendar or by scheduling SAP‟s executable dmdb6srp at the operating system level. (C) SAP AG BC535 10-32 Database Job Monitor (Transaction DB24) Mark and display details for more job information Monitor only statistic jobs Check if job finished successfully  SAP AG 1999 The function ID and the name of the program identify the kind of statistic job  Use the Database Job Monitor (transaction DB24) to monitor all update statistics jobs:  Check if RSDB6RSTATS runs successfully on a daily basis.  Check if the daily and weekly runstats jobs finished successfully.      Choose Performance to display only the jobs that are relevant for the Cost-Based Optimizer. Choose Display Details to see all the available job information. Check the column Status, the possible values are STARTED, RUNNING, or COMPLETED. Check the light in the column RC for error situations. Columns Program and FID identify the program name and the function ID of the jobs run:  DMDB6SRP and dbu: Database update statistics on all tables (weekly runstats)  DMDB6SRP and stu: dbstatc update statistics (daily runstats)  RSDB6RSTATS and stc: dbstatc check step (determines candidates for the daily runstats) (C) SAP AG BC535 10-33 Modifying the Algorithm to Update the Statistics - ... CBO Control Panel x  SAP AG 1999    To modify the standard procedure used for refreshing the optimizer statistics, you can use the CBO Control Panel (transaction DB21). You can increase the precision of the statistics for one table (including index and table columns). Set the TODO flag, so the next time the statistics are refreshed, new statistics will be created for the newly defined entries. (C) SAP AG BC535 10-34  Severe performance problems can also be caused by:  Incorrect statistical information  Incorrect assumptions about the data distribution within the object   Performance problems regarding incorrect optimizer assumptions are normally fixed by adding additional indexes, changing index definition or R/3 access methods to the data (rsdb/...) Use only R/3 tools to refresh the statistics of the R/3 tables. R/3 tools ensure that the update is done using the method and option defined for this object using the control table (DBSTATC). Every update of the statistics not done by the R/3 tools can create severe performance problems. If incorrect CBO assumptions are made, you can fix the problem with a “patch” of the DB2 Statistics Information. To do this, you must open a customer message in SAPNet.  (C) SAP AG BC535 10-35  This section describes how to identify an I/O contention problem caused by the physical and logical layout of the database. (C) SAP AG BC535 10-36   I/O contention means high I/O wait times for processes accessing the database. I/O contention occurs under the following circumstances:  Inefficient application design such as expensive, unnecessary, and poorly qualified statements  Data unevenly distributed across many disk cylinders  Disk not fast enough to handle high I/O activity  Heavily accessed tables or indexes are not distributed or striped across many disks  Incorrect hardware configuration such as many disks on few controllers   When numerous DB2 threads or processes access the same disks, I/O contention is likely to occur. Note: Often, I/O contention is caused by application design problems that must be checked first. (C) SAP AG BC535 10-37  To check for I/O contention, use the Database Performance Monitor (transaction ST04) and choose Detailed analysis menu  Tablespaces. Select Reset and - after a short period - Since Reset. Sort by Physical reads. Check the average Read time/ read and the average Write time/ write per tablespace to determine if the average number for a tablespace are significantly higher than for the others. Average numbers may indicate an I/O bottleneck but may not always point to the bottleneck. Look for tablespaces with high read or write figures. Call transaction DB02 and choose Tablespaces  Detailed Analysis  Containers. Note: Due to different hardware configurations and disk speeds, the values may deviate significantly from system to system. Your hardware vendor can provide more specific numbers. Use operating system-specific disk monitoring tools to determine if all file systems and disks that are in use by the most active tablespaces can cope with the workload.     (C) SAP AG BC535 10-38 Solving I/O Contention Total per tablespace  SAP AG 1999  Once you have identified I/O contention, use the following methods to solve the problem:  Distribute I/O (for example, containers) evenly over the available disks  Use faster disks  Move hotspot tables or indexes into own tablespaces on own disks  Create dedicated buffer pools for specific tablespaces    By breaking down the total I/O requests per file system (choose Total Per Device), the bottlenecked tablespace and data file can be identified and moved to another physical disk within the system. Note: Different hardware platforms may have bottlenecks in disk controller ports, motherboards, and backplanes. Refer to your hardware vendor for I/O distribution guidelines. R/3‟s monitors are limited to check the distribution of the container on the actual available disks. Use operating system commands for further analysis. (for example, with AIX use: lspv, or on Windows use: Disk Administrator). (C) SAP AG BC535 10-39 Optimize I/O on RAID Devices Prefetch size equals stripe size times number of disks db2pfchr Stripe size = Extent size RAID “Disk” Extents should not overlap with stripe sets (DB2_STRIPED_CONTAINERS)  SAP AG 1999  When data is placed on redundant array of independent disks (RAID) devices, specific tasks must be performed in order to optimize performance. Perform the following for each tablespace that uses a RAID device:  Define a single container for the table space (using the RAID device).  Make the EXTENTSIZE of the table space equal to(or a multiple of) the RAID stripe size.  Ensure that the PREFETCHSIZE of the tablespace is: - The RAID stripe size multiplied by the number of RAID parallel devices (or a whole multiple of this product), and - A multiple of the EXTENTSIZE.  Use the DB2_PARALLEL_IO registry variable to enable parallel I/O for the table space: db2set DB2_PARALLEL_IO=*  Use the DB2_STRIPED_CONTAINERS registry variable to ensure extent boundaries are aligned in the table space during tablespace creation : db2set DB2_STRIPED_CONTAINERS = ON; db2stop; db2start  For more information about these registry variables, see the README files for UDB 5.2. (C) SAP AG BC535 10-40 Solving Performance Problems SAP Notes -SAPNet Entry: SAP Note Searchx Search Criteria: Tables and Indexes Monitor - ... Database performance: Tables and Indexes x Database Checks Performance - Database Performance Analysis Monitor Database Performance Monitor: DB2 Database Overview x Refresh Detail analysis menu Tablespaces Tables/Indexes Run Update Statistics regularly CCMS Planning Calendar Planning Goto Listing Help System MON TUE WED THU FRI SAT SUN MON TUE WED THU FRI SAT SUN MON TUE WED THU FRI SAT SUN Buffer pool Size Overall buffer quality Sync. buffer quality Av. phys. read time Av. phys. write time Av. sync. read time Database files closed KB 40000 % 91,78 % 95,62 ms 5,44 ms 0,68 ms 0,78 0 Data Logical reads Physical reads Physical writes Index Logical reads Physical reads Physical writes Data Synchronous writes Data Synchronous reads 68123 8760 31 67541 2389 0 31 3547 Database Job Monitor Database Job -DB Operation Goto Details Monitor Setup System RC Status Date Time Complete 06.03.200 Complete 07.03.200 16:42:56 STC 16:42:56 STC Help MON TUE WED THU FRI SAT SUN DB20 Cardinality: Current Old value Deviation 2.470 2.519 2 % x Program Description DB2 Dynamic SQL -SQL Snapshot - Goto Setup Help Cache SQL text select * fro Select * from Select * from # execution Total executions % Total execution time 1438 1723 1443 19856 10172 8627 8.440 4.324 3.667 FID Object Runtime 01:00:00 RSDB6RSTATS dbstatc ch 01:00:00 RSDB6RSTATS dbstatc ch  SAP AG 1999  For general performance problems, you should check:  Whether the statistics are up to date. To do this, check the cardinality of a certain table in transaction DB20.  The status of the update statistics jobs, using the Database Job Monitor.  The buffer qualities, using transaction ST04.  In case of performance problems running an SQL statement, check:  Whether the statistics of all tables accessed by the SQL statement are up to date with the correct precision. Check the Tables and Indexes Monitor (Transaction DB02  Detailed Analysis).  If there is an SAP Note related to the problem.   Important: If you cannot find a solution, create a customer message in SAPNet. Use the dynamic SQL Cache to find the SQL statements that have the largest share on the total response time. (C) SAP AG BC535 10-41 Unit Summary  Now you are able to:  Monitor key performance indicators for DB2 UDB  Recognize poorly qualified and unnecessary SQL statements  Use the DB2 Dynamic SQL Cache Analysis  Identify I/O Contention in the database  SAP AG 1999 (C) SAP AG BC535 10-42 Unit Actions ?  Do the exercises  Solutions for the exercises  SAP AG 1999 (C) SAP AG BC535 10-43 Performance Monitoring: Exercises No. 1 Exercise Calculate the buffer pool data hit ratio and the buffer pool index hit ratio for your system. Compare those values to the overall buffer quality. 2 Check whether lock or exclusive lock escalations have occurred since the startup of the database. Check whether lock or exclusive lock escalations have occurred recently. 3 4 5 6 Check if page cleaners have been triggered because dirty page cleaning was needed. Which are the top 5 tables regarding read/write access? Check these tables also for overflow accesses. Which tablespace has the most physical reads/logical reads? Use the Dynamic SQL Cache to find out:    7 Which is the most used statement? Which statement has the largest share in the total DB response time? Which statement has the most sort operations? Verify the access plan of the statement that has the most sort operations and review the proper use of indexes. (C) SAP AG BC535 10-44 Performance Monitoring: Solutions No. 1 Solution Call transaction ST04 and use the logical and physical read values in the section Buffer Pool to calculate the following: Buffer pool data hit ratio: ((data logical reads-data physical reads)/ data logical reads) * 100. Buffer pool index hit ratio: ((index logical reads-index physical reads)/ index logical reads) * 100. 2 To check the lock or exclusive lock situation, call transaction ST04, and look at the information in section Locks and Deadlocks. To check if locks or exclusive locks have occurred recently, call transaction ST04 and choose Detail analysis menu  Performance Database  More. Check columns xlockesc and lockesc. 3 To check if page cleaners have been triggered, call transaction ST04 and choose Detail analysis menu  Snapshot structures. Choose database snapshot. Search for the entry Dirty page steal cleaner. To check which are the top 5 tables regarding read/write access, call transaction ST04 and choose Detail analysis menu  Table activity. (Sort the columns Read and Write) To check which tablespace has the most physical or logical reads, call transaction ST04 and choose Detail analysis menu  Tablespaces. Start the Dynamic SQL Cache Analysis, call transaction ST04, and choose Detail analysis menu  DB2 SQL Cache. Note: Only use the Display button, do not refresh the SQL Cache. Sort by column # Executions. Sort by column % Total. Sort by column SQL sorts. 4 5 6 7 To verify the access plan of the statement that has the most sort operations, sort column SQL sorts. Mark the top statement and choose Explain SQL Statement. Verify if a proper index could avoid sorting. (C) SAP AG BC535 10-45 (C) SAP AG BC535 11-1 Troubleshooting Contents:  Key monitoring transactions  Diagnostic tools  DB2 logging user exit maintenance  CBO performance maintenance  React to the most common error situations Objectives: At the end of this unit you will be able to:  Perform the most important duties of a DB2 DBA for R/3  Assess what can and must be fixed  SAP AG 1999 (C) SAP AG BC535 11-2 Begin Your Daily Work with Monitoring Tablespaces Tablespaces Performance Performance Backup Backup and archive and archive Directories Directories log_dir log_dir log_archive log_archive  SAP AG 1999  At the beginning of each workday, obtain an overview on the condition of your database in order to:  Recognize current problems or error conditions and remove them  Solve problems before they become critical  Include the following areas in your daily monitoring:  Tablespaces: Check if there is enough space in each tablespace. Consider how rapidly the objects (tables and indexes) expand in the tablespaces.  Backup and archive: Check if the last backup and archive of offline log files were successful.  Directory log_archive: Check if there is enough space in the log_archive directory for offline archived logs until the next planned archive run.  Performance: Check the setup of performance-related parameters of the database. Good database performance ensures faster response times of the R/3 System. (C) SAP AG BC535 11-3  Because of data expansion, the database objects will grow (allocate new extents). These extents are located within tablespaces with fixed sizes and with freespace that is reduced by extent allocation. To avoid system errors, as a result of tablespace full condition, you should monitor the tablespace freespace on a daily basis. To obtain an overview of the tablespace freespace, use the CCMS DBA Planning Calendar (transaction DB13). Choose Tools  CCMS Control Monitoring  Alert Monitoring  (or call transaction RZ20). Then choose SAP CCMS Monitor Templates  Database. Expand DB2 Universal Database NT/UNIX  Space management  DMS managed tablespaces. The status of the used size of a tablespace is displayed. The status is represented by a color:  Green means the status is OK: % used size < 90%.  Yellow means the “% used size” is >= 90% but < 95%.  Red means the “% used size” >= 95%.   The threshold values, which determine the status of a tablespace, can be changed using the properties of the related Monitoring Tree Element class element of the tablespaces. (C) SAP AG BC535 11-4 Daily DB Monitoring: Tablespace Growth  Analyze the history of critical tablespaces Tablespace PSAPES45AD PSAPDOCUD PSAPPOOLI Type Used size (KB) Free size (KB) 269376 6016 99360 %-Used 85,97 84,94 80,13 Container 4 1 2 Status Normal Normal Normal DMS 1650368 DMS DMS 33920 400608  Sort the column % Used  If an extension is needed, the following is required:   The path and number of next container The container size  Determine if there is enough freespace on the device or file system  SAP AG 1999  To monitor tablespace growth, use transaction DB02, or choose Tools  Administration  Monitor  Performance  Database  Tables/Indexes, and then choose Tablespaces  Detailed analysis menu. To display detailed information about critical tablespaces, mark the column %-Used and choose Sort. To display the recent sizes and growth of a tablespace, double-click a tablespace name.  Note: Since DB2 distributes data across all the containers, the containers of a tablespace must be the same size.   Ensure that there is enough freespace on the file system or device for the new container(s). (C) SAP AG BC535 11-5 DB Monitoring: Last Backup and Archive Results Overview of Backup Status ... ... ... ? Refresh DB12 Check if the backup and archive were successful Mon Tue Database backups Last successful database backup Overview of all database backups 21.2.1999 07:49:39 Tue Wed Thu Fri  Sat Sun Sat Sun Sat Sat Sun Sun Logs Status of log directory Log files to be archived Overview ofarchived logfiles Freespace in kB: 887.237 Mon Tue Wed Thu Fri Mon Mon Tue Tue Wed Wed Thu Thu Fri Fri CCMS DBA Calendar Log Info: Backup/Recovery Planning Goto Listing Help System x DB24 DB13 Completed Error Completed Completed 20000101 20000102 20000103 20000104 12:34:56 14:34:56 13:34:56 12:34:56 Monitor daily  SAP AG 1999    Current and consistent database backups and offline archived log files are crucial in case of recovery. Therefore, you must check if the last overnight backup was successful every day. Errors or problems might be caused by a defective tape or drive, a tape that is too small, or a SCSI attachment defect. To check the result of the last backup or archive run, use the CCMS DBA Planning Calendar (transaction DB13). From the CCMS, choose DB Administration  Time Scheduling. Check the Job log for the respective day. To display extensive information about backup or archive runs, use the DB Backup Monitor. From the CCMS choose DB Administration  Logs (or call transaction DB12). The date and time of the last successful backup is displayed. You will also see how much freespace is available in the log_archive directory and how many log files in the log_archive directory have not yet been saved to tape. Last successful database backup displays a list of the tablespaces that were written to tape during successful backups, as well as the log files that are needed to get the backup into a consistent state. Overview of all database backup logs displays all backups, type (online/offline), stop times, and further information belonging to the backup run. Status of log directory displays the location of the log_archive directory and the available freespace. Status of most recent logs displays the log file numbers for the last offline archived log written to the log_archive directory.      (C) SAP AG BC535 11-6 DB Monitoring: Backup Log Overview of Backup Status ... ... ... ? Refresh DB12 Check if the backup was successful.  is0005 20:30:08 Database backups Last successful database backup Overview of all database backups 21.01.1999 20:30:08 System BUD Database, DB server DB6 Day, Time 21.01.1999 Logs Status of log directory Log files to be archived Overview ofarchived logfiles Freespace in kB: 887.237 Operation Type: First Logfile: Last Logfile: No.of Tablespaces: Tablespaces: Location: ONLINE S0000903.LOG S0000906.LOG 21 SYSCATSPACE PSAPBTABD ... PSAPUSER1I /db2/BUD/sqllib/lib\ /libxbsa.a Monitor daily  SAP AG 1999  Choose Last Successful Database Backup to display a detailed log about the recent backup, which includes the:  Date and time  Type Offline/Online  Log files needed to get the online backup into a consistent state  Names of the tablespaces included in the backup  The backup location (for example, to disk or tape)  Note: In this example, the backup log shows the log of a DB2 backup into a vendor dll. In this case, it is the Legato Networker. (C) SAP AG BC535 11-7  Check if enough freespace is available in directory log_dir. To do this, call transaction ST04 and choose Detail Analysis Menu  Logging Overview. The size of directory log_archive should be approximately three to four times as large as the average daily yield of offline archived log files. Remember that unusually high database activity generally leads to an unusually high log file yield.   (C) SAP AG BC535 11-8  If the DB2 logging user exit fails to copy log files to the offline log directory, it will quietly fail. Once the online log directory in log_dir has reached its capacity, transactions will be rolled back. In this case, both the database and the R/3 System are blocked. Thus, you cannot resolve this error using the CCMS. Instead, intervention at the operating system level is required. The only location you can view that the user exit has failed is in the file db2uext2.err. To solve a log_dir full situation, you must create space in the following directory: /db2//log_archive//NODE0000. To do this, you must save offline archived log files to tape and then erase them. This can be done using DB2 Control Center, which in turn calls BRARCHIVE. You can also save the log files to tape directly using BRARCHIVE. For DB2 on UNIX, the syslog tools can be configured to log failures of the database server using the standard UNIX syslog tools. Using a filter program, which only selects errors of the user exit, you can configure the tools to notify remote administrators using e-mail in case of a failure.     (C) SAP AG BC535 11-9 Solving Problems with DB2 Logging User Exit db2diag.log: 1999-01-21-11.23.05.750000 Instance:DB2BKK Node:000 PID:171(db2syscs.exe) TID:213 Appid:none data_protection sqlpgart Probe:190 DIA9999E An internal error occurred. Report the following error code : "User Exit returned error on ARCHIVE H: h:\db2\BKK\log_dir\ S0000022.LOG BKK 39". ALERT :5 u db2 g ed a call ext2 ain  SAP AG 1999    As mentioned on the previous page, if the DB2 logging user exit fails to copy log files to the offline log directory, it will quietly fail. This example shows a typical entry for this situation. Through regular monitoring of the db2diag.log, you will be able to prevent system downtime well in advance. The DB2 logging user exit (db2uext2) is in case of an error called again due to the DB2 database. After solving the problem (that is, after solving freespace problems) this prevents you from invoking the DB2 logging user exit manually. (C) SAP AG BC535 11-10 Solving Problems with DB2 Logging User Exit db2uext2.log: ****************************************************************************** Time of Error: Tue Mar 22 13:39:39 1998 Action: ARCHIVE Database Name: TC2 Log File Path: F:\db2\TC2\log_dir\ Log File Name: S0000008.LOG Audit Log File: H:\db2\TC2\db2dump\db2uext2.log Media Type: Disk User Exit RC: 36 > Error isolation: Error opening file: F:\db2\TC2\log_dir\S0000008.LOG Mode: rb Error code: 2 Error message: The named file does not exist or the File Descriptor parameter points to an empty string.  SAP AG 1999    Check if there is an entry for db2uext2.log. If there is, a problem with the DB2 logging user exit occurred. The entries in db2uext2.log provide a detailed description of the error situation. This example shows a typical entry for this error situation. The db2usext2.err file contains more information about the user exit failure. (C) SAP AG BC535 11-11 DB Monitoring: Missing Indexes Tables have “lost” their index DB02 Database Performance: Tables and Indexes ... ... ... ... ... ... ? ... Database system Checks ... Tables and indexes Database Checks Installation checks Missing indexes ... Database < >ABAP/4 dictionary ... ...  SAP AG 1999  Missing indexes are indexes that are defined in the R/3 Data Dictionary but do not exist in the database. With DB2 UDB, missing indexes can be the result of intentional deleting or maintenance errors, but not due to reorganizations. You can use the DB Storage Monitor to determine if there are any missing database indexes. From the CCMS choose Control  Performance  Database  Tables/Indexes (or call transaction DB02). Then choose Missing indexes. Missing indexes can considerably impair system performance. After checking the reason for a missing index, recreate the index using ABAP Workbench (transaction SE12). Indexes are also considered missing if they are in the database indexes but not yet entered in the R/3 Data Dictionary. To find database indexes that have not been entered into the R/3 Data Dictionary, use the CCMS. Choose Control  Performance  Database Tables/Indexes (or call transaction DB02). Then choose Checks  Database < -> ABAP Dictionary to perform the consistency check. Any missing indexes are displayed in the section Tables and Indexes. If there are any indexes missing, enter them into the R/3 Data Dictionary.    (C) SAP AG BC535 11-12 DB Monitoring: Runstats Activity Database Administration Calendar DB2 Universal Database Unix/NT Mon 12 Tue 13 Wed 14 Thu 15 Fri 16 Sat 17 success success success success success Sun 18 Mon 19 success Tue 20 success Wed 21 success Thu 22 success Fri 23 2:00 error Mon 26 Tue 27 Wed 28  Sat 24 Sun 25 Once a week schedule Update Statistics All Tables & Reorgcheck Sat 31 Sun 01 Thu 29 Fri 30 0:00 Online_dev 5:00 Init Tape 0:00 Online_dev 5:00 Init Tape 0:00 Online_dev 5:00 Init Tape 05:00 Init Tape 5:00 Init Tape 5:05 Arlog_tape 5:00 Init Tape 5:05 Arlog_tape 5:00 Init Tape 5:05 Arlog_tape 05:05 Arlog_tape 5:05 Arlog_tape 5:05 Arlog_tape 5:05 Arlog_tape 22:00 Runstat_all Mon 02 Tue 03 Wed 04 Thu 05 0:00 Online_dev0:00 Backup 0:00 Online_dev 5:00 Init Tape 0:00 Online_dev 5:00 Init Tape 9:00 Archive 5:00 Init Tape 5:05 Arlog_tape 5:00 Init Tape Check 5:05 Arlog_tape the job log 5:05 Arlog_tape 5:05 Arlog_tape i Fri 06 Sat 07 Sun 08 for the previous day  SAP AG 1999     Ensure that Update Statistics are scheduled on all tables on a regular basis. Since all table data is read into the buffer pool(s) for analysis, you should schedule this activity during periods of low system activity (such as on the weekends). Note: Your buffer quality is not optimal for a short period of time after the Update Statistics task is run. All activities planned in the CCMS DBA Planning Calendar write a job log for their run. Ensure that you check the job log of the previous day on a daily basis. (C) SAP AG BC535 11-13 Database Job Monitor: Runstats Activity Mark and display details for more job information Monitor only statistic jobs DB24 Check if job finished successfully  SAP AG 1999 The function ID and the name of the program identify the kind of statistic job  Use the Database Job Monitor (transaction DB24) to monitor all update statistics jobs:  Check if RSDB6RSTATS runs successfully on a daily basis.  Check if the daily and weekly runstats jobs finished successfully.      Choose Performance to display only the jobs that are relevant for the Cost-Based Optimizer. Choose Display Details to see all the available job information. Check the column Status, the possible values are STARTED, RUNNING, or COMPLETED. Check the light in the column RC for error situations. Columns Program and FID identify the program name and the function ID of the jobs run:  DMDB6SRP and dbu: Database update statistics on all tables (weekly runstats)  DMDB6SRP and stu: dbstatc update statistics (daily runstats)  RSDB6RSTATS and stc: dbstatc check step (determines candidates for the daily runstats)  Use transaction DB02 to check the runstats timestamp of a specific table. DB02 also provides the information of the oldest runstats timestamp in your DB2 database. (C) SAP AG BC535 11-14 DB Monitoring: Mirroring the Administration Database Select Background Jobs ... ... ... ? SM37 Job name: User name: Job Status ... DB_Admin_Mirror * Check if the administration database was successfully copied to the R/3 database ... X Finished  SAP AG 1999  To ensure that the administration database was successfully copied to the R/3 database, select the background jobs that execute the executable sddb6mir. Check the job logs for the status of the mirror jobs. Note: sddb6mir is used to mirror the administration database and is used to restore the administration database from the R/3 database.  (C) SAP AG BC535 11-15 Review db2diag.log db2diag.log: 1999-01-17-19.59.52.802707 Instance:db2prd Node:000 PID:19672(db2agent (PRD)) Appid:*LOCAL.db2prd.990118010003 database_monitor sqld_log_ev_err Probe:1 Database:PRD DiagData ffff 8e2c String Title:Successfully rebuilt indexes PID:51308 Node:000 Table=SAPR3 .MCSHIERBT (13;6930). Thu Feb 12 14:14:35 1998 db2p01 pid(28102) process (db2agent (P01)) database_utilities sqludrsa Probe:0 Database (P01) Starting a full database restore. Thu Feb 12 15:24:52 1998 db2p01 pid(28102) process (db2agent (P01)) database_utilities sqludrsa Probe:0 Database (P01) Restore Complete .  SAP AG 1999  Check whether the scheduled DB2 jobs have been finished successfully:  Backups completed  reorg successfully  Check whether error situations occurred. Search for the words in chevrons:  TABLESPACE X(PSAP*) is >>full<<  Reorg table >>failed<<  Abnormal connect >>termination<<  >>sqlcode<<: -XXX ...  >>crash recovery<< required  backup >>terminated<< (or other related bad backup news)  >>Error<<  >>FFFFD121<< Tablespace full condition  >>FFFFD60C<< File system full condition  The database manager configuration parameters DIAGLEVEL and DIAGPATH are used to specify the amount of logging and the location of the db2diag.log file. (C) SAP AG BC535 11-16 Monitoring Tools: Overview SAP CCMS Monitor Database ... ... ... ... ... ? ... Space management DMS managed tablespace PSAPBTABD PSAPSTABI PSAPBTABI PSAPCLUD 63% green 13.03.2000 70% green 13.03.2000 90% yellow 13.03.2000 95% red 13.03.2000 Overview of Backup Status ... ... ... ? Database backups Database Performance: DB2 Database ... ... ... ... ... ... ? Database Tablespaces Logs Tables and Indexes CCMS Monitor Templates (RZ20) Log Info: Backup/Recovery Planning Goto Listing Help System R/3 DB Backup CCMS DBA Monitor (DB12) (DB13) SysLog ... ... ... ... ... R/3 DB Storage Monitor (DB02) ... ... ... ... ... ... ... ? x ? ... ... ... SysLog 12:34:56 12:34:56 14:34:56 14:34:56 13:34:56 13:34:56 12:34:56 12:34:56 Database performance analysis Buffer Pool IOServer and IOCleaner Completed Completed Error Completed Completed Completed Completed 20000101 20000102 20000103 20000104 Locks and Deadlocks Calls R/3 SysLog (SM21) Control Center Sorts Caching R/3 DB Performance Monitor (ST04) ?/db2dump/*: db2diag.log DB2 dumps SAP DB2Admin Database Job Monitor (DB24)  SAP AG 1999  From the R/3 System, you can use the following tools for monitoring the database:  DB Alert Monitor (transaction AL02) provides a quick overview on the condition of the database.  DB Backup Monitor (transaction DB12) displays detailed information about the data backups (backup and archive) and information about the backup status of the database.  DB Storage Monitor (transaction DB02) provides information about the state of the database on disk and the condition of its objects.  SysLog (transaction SM21) contains status messages, warnings, and error messages of the R/3 System, which also refer to the database.  DB Performance Monitor (transaction ST04) displays capacity and performance-relevant database setups.  CCMS DBA Planning Calendar (transaction DB13) provides an overview of the executed DBA jobs.  Transaction AL11 provides an overview of the db2diag.log file.  You can use the following tools to monitor the database externally from the R/3 System:  DB2 Control Center and the SAP DB2Admin can be used for starting and stopping the database, tablespace administration, reorganizing tables/indexes and tablespaces, backup and archive, restore and recovery. (C) SAP AG BC535 11-17 SAP System Administration Assistant (SSAA) Use transaction SSAA to check periodic database administration and monitoring tasks  SAP AG 1999  The System Administration Assistant helps you with the regular database administration tasks of your R/3 System. You can access the System Administration Assistant by choosing Tools  Administration  Monitor  System Administration Assistant (SAA). Or use transaction SSAA. All periodic database administrative tasks (and the R/3 administrative tasks) are presented in one tool. You can see different tasks listed in the categories Daily, Weekly, Monthly, Yearly and Unscheduled/Occasional. You do not need to navigate to a different menu.  (C) SAP AG BC535 11-18 DB2 Diagnostic Files DIAGLEVEL specifies the level of diagnostic information db2diag.log: 1999-01-17-19.59.52.802707 Instance:db2prd Node:000 PID:19672(db2agent (PRD)) Appid:*LOCAL.db2prd.990118010003 database_monitor sqld_log_ev_err Probe:1 Database:PRD DiagData ffff 8e2c String Title:Successfully rebuilt indexes PID:51308 Node:000 Table=SAPR3 .MCSHIERBT (13;6930). Thu Feb 12 14:14:35 1998 db2p01 pid(28102) process (db2agent (P01)) database_utilities sqludrsa Probe:0 Database (P01) Starting a full database restore. Thu Feb 12 15:24:52 1998 db2p01 pid(28102) process (db2agent (P01)) database_utilities sqludrsa Probe:0 Database (P01) Restore Complete. DIAGPATH specifies the fully qualified path where DB2 writes its diagnostic information Dump Files: c56772.000 c58978.000 Node number where process was running on Process ID that is related to the dump or trap file Trace Files: t56772.000 t58978.000  SAP AG 1999       db2diag.log: When an error occurs, the db2diag.log file is updated with information about the error. Dump files: For some error conditions, extra information is logged in external binary dump files named after the failing process ID. Trap files: The database manager generates a trap file if it cannot continue processing because of a trap, segmentation violation, or exception. DIAGLEVEL: The default value for DIAGLEVEL is 3. Change it to 4 during initial setup and when you are experiencing database problems. DIAGPATH: This directory contains dump, error log, and alert log files. To change these configuration parameters, use the following commands:  db2 “update database manager configuration using diaglevel 4”  db2 “update database manager configuration using diagpath /tmp/errors” (C) SAP AG BC535 11-19 Interpreting the db2diag.log file db2diag.log: 1999-01-17-19.59.52.802707 1 Instance:db2prd Node:000 PID:19672(db2agent (PRD)) 3 Appid:*LOCAL.db2prd.990118010003 4 database_monitor 5 sqld_log_ev_err Probe:1 Database:PRD 6 DiagData 7 ffff 8e2c 8 String Title:Successfully rebuilt indexes PID:51308 Node:000 Table=SAPR3 .MCSHIERBT (13;6930). Thu Feb 12 14:14:35 1998 db2p01 pid(28102) process (db2agent (P01)) database_utilities sqludrsa Probe:0 Database (P01) Starting a full database restore. Thu Feb 12 15:24:52 1998 db2p01 pid(28102) process (db2agent (P01)) database_utilities sqludrsa Probe:0 Database (P01) Restore Complete 2 .  SAP AG 1999       A timestamp for the message. (1) Name of instance generating the message. The node generating the message. The database on which the error occurred. (2) Identification of the process generating the message. (3) Identification of the application for which the process is working. To view a list of application IDs, use command db2 “list applications” or db2 “get snapshot for application”. (4) The DB2 component that is writing the message. (5) The name of the function that is providing the message. The fourth letter of its name is related to the type of activity it identifies, for example, b - buffer pools, d - data management, e - engine processes. (6) Diagnostic message and the hexadecimal representation of an internal return code. (7 and 8)  (C) SAP AG BC535 11-20 Decoding TechTalk in db2diag.log  The db2diag.log contains support information:  {p:m ; o: n; ....} Look-Up the table name in SYSCAT.TABLES with m as TBSPACEID and n as TABLEID  Interpreting hexadecimal codes   Hex codes in form ffff nnnn are meaningful Hex codes in form nnnn ffff must be byte-reversed before they are meaningful, for example, 0ae6 ffff -> ffff e60a Convert hex code to a decimal format, search for it in:    DB2 message reference (it is then an SQL code, use command db2 “? SQL”) DB2 Troubleshooting Guide, Appendix D, DB2 Internal Return Codes  SAP AG 1999   If you want to quickly assess the problem reported in db2diag.log, use the above information as a starting point. The decimal format representation of an hexadecimal code might be an SQL code and can be retrieved using command db2 “? sql”. But the hex code might also be an internal return code representation, and therefore can only be found in DB2‟s Troubleshooting Guide. An “EDU” is a DB2 Engine Dispatchable Unit (probably a db2agent).   (C) SAP AG BC535 11-21 Tracing Database Malfunctions  Start the trace with db2trc on -s -l  Where specifies the maximum size of the trace area in shared memory (in bytes) If the space is not sufficient, “wrap around” is written   Reproduce the error  Write the dump file db2trc dump  Deactivate the trace with db2trc off  The trace must be formatted with the commands:   db2trc fmt > dump.fmt db2trc flw > dump.flw  SAP AG 1999  The DB2 trace tool (command db2trc) lets you trace events, dump the trace data to a file, and format the data into a readable form. You may be requested by SAP DB2 Support to perform a trace if the db2diag.log file does not provide enough information to diagnose a problem. Use this tool only when error conditions are predictable and reproducible, and only when it is explicitly requested. After the trace file is dumped to a binary file, confirm that the trace was successful by formatting it into an ASCII file (check first output line of db2trc fmt|flw for: “Trace wrapped: NO”). Use either option flw, or option fmt. For either option, you must specify the name of the dump file and you should specify the name of an output file that will be generated.  Use flw to sort the output file by process or thread  Use fmt to list the output file chronologically by events  (C) SAP AG BC535 11-22 Preventative Maintenance DB2 Database server Have you installed the latest kernel patches? R/3 Application server Have you applied the latest R/3 DB2 tools? DB2 Database R/3 work process Have you installed the latest DB2 FixPak?  SAP AG 1999    SAP Note 19466 contains information about the latest kernel patch that is available for each R/3 platform. SAP Note 101809 contains information about all available FixPaks supported by SAP for DB2 UDB on UNIX/NT. SAP Note 124268 contains information about the new Explain plan function for all R/3 Releases. (C) SAP AG BC535 11-23 Database Utilities  R/3 work processes cannot connect to DB2  Manually connect to DB2 as user sapr3 using r3trans -d  Some R/3 DB2 transactions do not work  Manually connect to DB2 as user adm using dmdb6srp -n -t sapr3.svers Use dscdb6up (or DB2 CC R/3 password management) to synchronize passwords of adm and sapr3   Problems checking the status of R/3 processes with the SAP GUI  Check status of R/3 work processes manually using dpmon pf=  Monitor lockwait situations using DB2 CLP  Use db2 “get snapshot for all applications”  SAP AG 1999  Use command r3trans -d to manually check if the connection to DB2 can be established. If the connection is refused by DB2, try to synchronize the passwords stored in file dscdb6.conf and the passwords stored in the operating system for the users adm and sapr3. To change the operating system password and simultaneously the password in file dscdb6.conf, use command dscdb6up or use the DB2 Control Center R/3 Password Management. Use command dpmon to monitor the status of the R/3 work processes in cases where no SAP GUI logon is possible. To monitor a lockwait situation using the DB2 CLP use the command db2 “get snapshot for all applications”.  Look for the application status Lock-wait to identify the waiting agents. - Identify the lock holder using the information in section “Subsection waiting for lock”; the entry ID of agent holding lock contains the agent ID of the lock holder. The entry Dynamic SQL statement text contains the SQL statement that requested the lock.  Search for lock holder using the agent ID. Use the entry Dynamic SQL statement text to identify the SQL statement that holds the lock.   (C) SAP AG BC535 11-24 Roadmap for Start Problems Startup problems for DB2  Check the DB2 diagnostic file: db2diag.log  Check the correct database connection    Use R3trans –d Set the password for sapr3 and adm with dscdb6up Manually start DB2 with the db2start and db2 connect commands, check the output of the commands Check if all DB2 processes are running (UNIX) Check if all DB2 services are started (NT) Check the freespace in the online and offline log directories     Check if DB2 is still in backup pending mode  Check if DB2 is still performing a restart recovery  SAP AG 1999    Use this roadmap for problems in case the startup of your R/3 System fails because DB2 does not start. The goal of the manual operations is to find the reason why DB2 cannot start or why the R/3 work processes cannot connect to DB2. Check the output of the db2 commands carefully for additional information about the problem. (C) SAP AG BC535 11-25 Roadmap Stop Problems  Check application connections to DB2 using db2 list applications  Check file db2diag.log for shutdown errors or any other errors preventing DB2 to finish write operations  Check if there is enough freespace on the DB2 file systems  Check the DB activity  Check the output of the following commands for any additional information     db2 get db cfg for db2 connect to db2 list tablespaces  Check the list for active DB2 processes or threads That is, check if DB2 user exit is still active or if the DB2 page cleaner is still writing  SAP AG 1999    Use this roadmap for problems in case the stopping of your R/3 System fails because DB2 does not stop. The goal of the manual operations is to find the reason why DB2 cannot stop. Check the output of the db2 commands carefully for additional information about the problem. (C) SAP AG BC535 11-26 Files Needed for SAP DB2 Database Hotline  R/3 support tools for DB2 UDB:   UNIX: r3db6hst.ksh Windows NT: sapntchk.exe SAP‟s DB2 Support will ask you:   For specific files To run certain dialog programs  SAP AG 1999    SAP‟s DB2 support can help you very quickly. For the first offline analysis of most problems, the DB2 expert will ask you to provide files or run programs that collect data. For up-to-date information about r3db6hst.ksh, see SAP Note 83819. For up-to-date information about sapntchk.exe, see SAP Note 65761. (C) SAP AG BC535 11-27 Unit Summary  Now you are able to:  Monitor the key elements of your DB2 database server  Maintain the CBO performance using Update Statistics (transaction DB13)  Interpret DB2‟s db2diag.log  React to the most common error situations  Plan preventive measures to avoid the occurrence of the problems  Provide the initial set of files for SAP DB2 Support  SAP AG 1999 (C) SAP AG BC535 11-28 Unit Actions ?  Do the exercises  Solutions for the exercises  SAP AG 1999 (C) SAP AG BC535 11-29 Troubleshooting: Exercises No. 1 2 Exercise Which tablespace has the highest growth in the past few months? Assume you find the following hexadecimal representation of an SQL error: FFFF E60A in the DB2DIAG.LOG file. Determine if this is an SQL code or an internal return code. 3 Assume you have scheduled the online backups of your R/3 System using transaction DB13. Where would you check for the success of the jobs in transaction DB13? 4 5 6 Where is the information about the status of the daily check step displayed? Where is the information about the status of the most recent DB2 backup displayed? Although this problem is not common to DB2 UDB database servers, assume you have “lost” and index. Where do you check for missing indexes? How do you re-generate the index again using R/3? 7 Which is the official and only supported SAP tool to ensure that the most important tables receive daily update on the statistics? How often should this job be scheduled? (C) SAP AG BC535 11-30 Troubleshooting: Solutions No. 1 Solution To check which tablespace has the highest growth, call transaction DB02. In the Database system section, choose Space statistics. The history of the database is displayed. To display the tablespace history, choose Tablespaces. Choose Months or Weeks to determine which tablespace has the highest growth. Transform E60A into decimal format: 58890 To test if you can retrieve a SQL message, issue command db2 “? SQL58890”. To determine if this is an SQL code, either check DB2’s Troubleshooting Guide, Appendix D. DB2 Internal Return Codes, or check IBM's homepage at www.ibm.com, then choose Products , Software  DB2  Library  DB2 Universal Database. 3 To check the success of the jobs, call transaction DB13, select the day you want to review, then choose Job Logs. Double-click on the job log you want to see. To check the information about the status of the daily check, call transaction DB24 and choose Performance to monitor only statistic jobs. Check the columns FID for the entry stc and check the column status for COMPLETED. 5 6 To check the information about the status of the most recent DB2 backup, call transaction DB12 and choose Last Successful Backup. To check for missing indexes, call transaction DB02, and choose Missing Indexes in the Tables and Indexes section. To re-generate the index, select the missing index in the above list and choose Create on Database. 7 The CCMS DBA Planning Calendar (transaction DB13) is the only official SAP tool for ensuring the most important tables receive their daily statistical update. Note: You can also use the executable dmdb6srp. You should schedule the update statistics job daily. To do this, call transaction DB13 and choose Planning  Planning Patterns, and select Upd.Statistics & REORG check on DBSTATC (daily). 2 4 (C) SAP AG BC535 11-31
premium docs
Other docs by Wu tang clan
Undivided Heart
Views: 180  |  Downloads: 0
Child custody and maintenance
Views: 863  |  Downloads: 20
Model furniture lease disclosure
Views: 314  |  Downloads: 5
cr118
Views: 136  |  Downloads: 0
We Praise Thee O God
Views: 223  |  Downloads: 1
dv125
Views: 152  |  Downloads: 0
Food Chemistry Experiments
Views: 1725  |  Downloads: 66
World History Standards Test
Views: 386  |  Downloads: 3
dv125c
Views: 133  |  Downloads: 0
English Chinese Translation Glossary
Views: 918  |  Downloads: 28
Written claims on final settlement
Views: 186  |  Downloads: 3
Property Outline -- Knapland
Views: 515  |  Downloads: 30
dv200k
Views: 98  |  Downloads: 0
Magnificat
Views: 300  |  Downloads: 4
Shout Hallelujah
Views: 514  |  Downloads: 9