Что такое pdb и cdb oracle
17 Introduction to the Multitenant Architecture
This chapter contains information specific to the Oracle Multitenant option.
It includes the following topics:
About the Multitenant Architecture
The multitenant architecture enables an Oracle database to function as a multitenant container database (CDB).
About Containers in a CDB
A container is either a PDB or the root. The root container is a collection of schemas, schema objects, and nonschema objects to which all PDBs belong.
Every CDB has the following containers:
Zero or more user-created PDBs
A PDB is a user-created entity that contains the data and code required for a specific set of features. For example, a PDB can support a specific application, such as a human resources or sales application. No PDBs exist at creation of the CDB. You add PDBs based on your business requirements.
The following figure shows a CDB with four containers: the root, seed, and two PDBs. Each PDB has its own dedicated application. A different PDB administrator manages each PDB. A common user exists across a CDB with a single identity. In this example, common user SYS can manage the root and every PDB. At the physical level, this CDB has a database instance and database files, just as a non-CDB does.
Figure 17-1 CDB with Two PDBs
Description of «Figure 17-1 CDB with Two PDBs»
Oracle Database Administrator’s Guide for an introduction to the multitenant architecture
About User Interfaces for the Multitenant Architecture
You can use the same administration tools for both CDBs and non-CDBs.
For example, you can use the following tools in a multitenant environment:
SQL*Plus is a command-line program that you use to submit SQL and PL/SQL statements to an Oracle database.
SQL Developer provides another GUI for accessing your Oracle database. SQL Developer supports PDB provisioning.
Oracle Enterprise Manager Cloud Control (Cloud Control)
Cloud Control is an Oracle Database administration tool that provides a graphical user interface (GUI). Cloud Control supports Oracle Database 12 c targets, including PDBs, CDBs, and non-CDBs.
See Oracle Database Administrator’s Guide to learn more about Cloud Control.
Oracle Enterprise Manager Database Express (EM Express)
EM Express is a web-based management product built into the Oracle database. EM Express enables you to provision and manage PDBs, including the following operations:
Creating and dropping PDBs
Plugging in and unplugging and PDBs
Setting resource limits for PDBs
See Oracle Database 2 Day DBA to learn more about using EM Express for managing CDBs and PDBs.
Oracle Database Configuration Assistant (DBCA)
DBCA enables you to create CDBs or non-CDBs, and create, plug, and unplug PDBs. See Oracle Database 2 Day DBA and Oracle Database Administrator’s Guide for more information about DBCA.
Oracle Multitenant Self-Service Provisioning application
This application enables the self-service provisioning of PDBs. CDB administrators control access to this self-service application and manage quotas on PDBs.
For more information about the application or to download the software, use any browser to access the OTN page for the application:
Benefits of the Multitenant Architecture
The multitenant architecture solves a number of problems posed by the traditional non-CDB architecture.
Challenges for a Non-CDB Architecture
Large enterprises may use hundreds or thousands of databases. Often these databases run on different platforms on multiple physical servers.
Because of improvements in hardware technology, especially the increase in the number of CPUs, servers are able to handle heavier workloads than before. A database may use only a fraction of the server hardware capacity. This approach wastes both hardware and human resources.
For example, 100 servers may have one database each, with each database using 10% of hardware resources and 10% of an administrator’s time. A team of DBAs must manage the SGA, database files, accounts, security, and so on of each database separately, while system administrators must maintain 100 different computers.
To show the problem in reduced scale, Figure 17-2 depicts 11 databases, each with its own application and server. A head DBA oversees a team of four DBAs, each of whom is responsible for two or three databases.
Figure 17-2 Database Environment Before Database Consolidation
Description of «Figure 17-2 Database Environment Before Database Consolidation»
Typical responses include:
Use virtual machines (VMs).
In this model, you replicate the operating infrastructure of the physical server—operating system and database—in a virtual machine. VMs are agile, but use technical resources inefficiently, and require individual management. Virtual sprawl, which is just as expensive to manage, replaces the existing physical sprawl.
Place multiple databases on each server.
Separate databases eliminate operating system replication, but do not share background processes, system and process memory, or Oracle metadata. The databases require individual management.
Separate the data logically into schemas or virtual private databases (VPDs).
This technique uses technical resources efficiently. You can manage multiple schemas or VPDs as one. However, this model is less agile than its alternatives, requiring more effort to manage, secure, and transport. Also, the logical model typically requires extensive application changes, which discourages adoption.
Benefits of the Multitenant Architecture for Database Consolidation
The PDB/non-CDB compatibility guarantee means that a PDB behaves the same as a non-CDB as seen from a client connecting with Oracle Net. The installation scheme for an application back end that runs against a non-CDB runs the same against a PDB and produces the same result. Also, the run-time behavior of client code that connects to the PDB containing the application back end is identical to the behavior of client code that connected to the non-CDB containing this back end.
Operations that act on an entire non-CDB act in the same way on an entire CDB, for example, when using Oracle Data Guard and database backup and recovery. Thus, the users, administrators, and developers of a non-CDB have substantially the same experience after the database has been consolidated.
The following figure depicts the databases in Figure 17-2 after consolidation onto one computer. The DBA team is reduced from five to three, with one CDB administrator managing the CDB while two PDB administrators split management of the PDBs.
Figure 17-3 Single CDB
Description of «Figure 17-3 Single CDB»
Using the multitenant architecture for database consolidation has the following benefits:
By consolidating hardware and database infrastructure to a single set of background processes, and efficiently sharing computational and memory resources, you reduce costs for hardware and maintenance. For example, 100 PDBs on a single server share one database instance.
Easier and more rapid movement of data and code
By design, you can plug a PDB into a CDB, unplug the PDB from the CDB, and then plug this PDB into a different CDB. The implementation technique for plugging and unplugging is similar to the transportable tablespace technique.
Easier management and monitoring of the physical database
The CDB administrator can manage the environment as an aggregate by executing a single operation, such as patching or performing an RMAN backup, for all hosted tenants and the CDB root. Backup strategies and disaster recovery are simplified.
Separation of data and code
Although consolidated into a single physical database, PDBs mimic the behavior of non-CDBs. For example, a PDB administrator can flush the shared pool or buffer cache in the context of a PDB without affecting other PDBs in the CDB.
Secure separation of administrative duties
A user account is common, which means that it can connect to any container on which it has privileges, or local, which means that it is restricted to a specific PDB. A CDB administrator can use a common user account to manage the CDB. A PDB administrator uses a local account to manage an individual PDB. Because a privilege is contained within the container in which it is granted, a local user on one PDB does not have privileges on other PDBs within the same CDB.
Ease of performance tuning
It is easier to collect performance metrics for a single database than for multiple databases. It is easier to size one SGA than 100 SGAs.
Support for Oracle Database Resource Manager
In any shared resource environment, administrators must manage system resources to provide a predictable environment for users and address unexpected or transient resource contention. To address these issues, and to provide resource usage monitoring, you can use Oracle Database Resource Manager.
Fewer database patches and upgrades
It is easier to apply a patch to one database than to 100 databases, and to upgrade one database than to upgrade 100 databases.
Benefits of the Multitenant Architecture for Manageability
The multitenant architecture has benefits beyond database consolidation. These benefits derive from storing the data and data dictionary metadata specific to a PDB in the PDB itself rather than storing all dictionary metadata in one place. By storing its own dictionary metadata, a PDB becomes easier to manage as a distinct unit, even when only one PDB resides in a CDB.
Benefits of data dictionary separation include the following:
Easier migration of data and code
For example, instead of upgrading a CDB from one database release to another, you can unplug a PDB from the existing CDB, and then plug it into a newly created CDB from a higher release.
Easier testing of applications
You can develop an application on a test PDB and, when it is ready for deployment, plug this PDB into the production CDB.
Path to Database Consolidation
For the duration of its existence, a database is either a CDB or a non-CDB. You cannot transform a non-CDB into a CDB, or a CDB into a non-CDB. You must define a database as a CDB at creation, and then create PDBs and application containers within this CDB.
The basic path to database consolidation is:
Creation of a CDB
Along with the root container ( CDB$ROOT ), Oracle Database automatically creates a seed PDB ( PDB$SEED ). The following graphic shows a newly created CDB:
Figure 17-4 CDB with Seed PDB
Description of «Figure 17-4 CDB with Seed PDB»
Example 17-1 Determining Whether a Database Is a CDB
The following simple query determines whether the database to which an administrative user is currently connected is a non-CDB, or a container in a CDB:
Oracle Database Administrator’s Guide to learn how to create a CDB using DBCA or the CREATE DATABASE statement
Oracle Database SQL Language Reference for more information about specifying the clauses and parameter values for the CREATE DATABASE statement
Creation of a PDB
The CREATE PLUGGABLE DATABASE SQL statement creates a PDB. This PDB automatically includes a full data dictionary including metadata and internal links to system-supplied objects in the root. You can only create a PDB in a CDB and not within another PDB.
The following figure depicts the options for creating a PDB.
Figure 17-5 Options for Creating a PDB
Description of «Figure 17-5 Options for Creating a PDB»
Figure 17-6 CDB with Six PDBs
Description of «Figure 17-6 CDB with Six PDBs»
The following sections describe the different techniques for creating PDBs.
Creation of a PDB from Seed
The following figure illustrates creation from the seed.
Figure 17-7 Creation of a PDB from the Seed PDB
Description of «Figure 17-7 Creation of a PDB from the Seed PDB»
The following SQL statement creates a PDB named hrpdb from the seed using Oracle Managed Files:
Creation of a PDB by Cloning a PDB or a Non-CDB
You can use the CREATE PLUGGABLE DATABASE statement to clone a source PDB or non-CDB and plug the clone into the CDB.
The source can be a PDB in a local or remote CDB, or starting in Oracle Database 12 c Release 1 (12.1.0.2), it can also be a remote non-CDB. This technique copies the files associated with the source PDB or non-CDB to a new location and associates the copied files with the new PDB.
The following graphic illustrates cloning a PDB from an existing PDB in the same CDB.
Figure 17-8 Cloning a PDB from a PDB in the Same CDB
Description of «Figure 17-8 Cloning a PDB from a PDB in the Same CDB»
If the underlying file system of a PDB supports storage snapshots, then you may specify the SNAPSHOT COPY clause to clone a PDB using storage snapshots. In this case, Oracle Database does not make a complete copy of source data files, but creates a storage-level snapshot of the underlying file system, and uses it to create PDB clones. Snapshot copies make cloning almost instantaneous.
The following SQL statement clones a PDB named salespdb from the plugged-in PDB named hrpdb :
Oracle Database Administrator’s Guide to learn how to create a PDB by cloning an existing PDB or non-CDB
Creation of a PDB by Plugging In an Unplugged PDB
In its unplugged state, a PDB is a self-contained set of data files and an XML metadata file. This technique uses the XML metadata file that describes the PDB and the files associated with the PDB to associate it with the CDB.
The following figure illustrates plugging in an unplugged PDB.
Figure 17-9 Plugging In an Unplugged PDB
Description of «Figure 17-9 Plugging In an Unplugged PDB»
The following SQL statement plugs in a PDB named financepdb based on the metadata stored in the named XML file, and specifies NOCOPY because the files of the unplugged PDB do not need to be renamed:
Oracle Database Administrator’s Guide to learn how to perform this technique
Creation of a PDB from a Non-CDB
You can move a non-CDB into a PDB.
You can accomplish this task in the following ways:
Executing DBMS_PDB.DESCRIBE on a non-CDB in Oracle Database 12 c
See Oracle Database Administrator’s Guide to learn how to perform this technique.
Using Oracle Data Pump with or without transportable tablespaces
See Oracle Database Administrator’s Guide to learn how to perform this technique.
Using Oracle GoldenGate replication
You replicate the data from the non-CDB to a PDB. When the PDB becomes current with the non-CDB, you switch over to the PDB.
See Oracle Database Administrator’s Guide to learn how to perform this technique.
The following figure illustrates running the DBMS_PDB.DESCRIBE function on a non-CDB, and then creating a PDB using the non-CDB files.
Figure 17-10 Creating a PDB from a Non-CDB
Description of «Figure 17-10 Creating a PDB from a Non-CDB»
Oracle Database Administrator’s Guide for an overview of how to create PDBs
Oracle 12c Multitenant Architecture. Новые возможности для разработки и тестирования
Самым крупным нововведением недавно вышедшего Oracle 12c безусловно является Multitenant Architecture. Сам Oracle преподносит эту возможность в основном как средство консолидации и снижения расходов.
Суть технологии состоит в возможности запустить несколько независимых баз (pluggable database, PDB) в рамках одного инстанса (container database, CDB). Каждая база имеет свой набор схем и табличных пространств, но при этом у них общая SGA и один набор серверных процессов. Есть возможность клонировать pluggable database, как в рамках одного контейнера, так и между контейнерами. Вот эту возможность и будем использовать для создания копий тестовых баз и экономии ресурсов.
Задача — имеем большую систему, с большой базой. Нужно проводить тестирование изменений, причем изменений разрушительных — удаление/модификация таблиц. Как это делается сейчас — создаем новую базу, заливаем в нее минимально возможный набор схем и данных и проводим тестирование. Процесс сам по себе не быстрый, трудоемкий и всегда есть возможность ошибиться. Да и «минимальный набор данных» может быть не таким уж и маленьким.
Эксперимент проводился в среде Oracle Virtualbox 4.2.14. Я не буду подробно описывать инсталляцию, она хорошо освещена в документации, буду останавливаться только на важных моментах.
Инсталляция
Ставим Oracle linux 6.4 c апдейтами, зависимости для oracle и поддержку ASM:
конфигурируем ASM и создаем ASM disk:
Подключаемся к инстансу ASM и меняем режим совместимости:
В результате получаем базу-контейнер и с seed database (модельная база для создания pluggable database).
Проверяем что все получилось:
Работа с клонами
Создаем каталог на ACFS /data/oradata, и меняем владельца на oracle. Меняем параметр db_create_file_dest на /data/oradata. Cоздаем клон который будет изображать тестовую базу:
На ACFS должен появиться каталог с буквенно-цифровым именем (случайным), содержащий наш PDB:
PDB после создания или рестарта контейнера нужно открывать:
Имитируем создание тестовой базы — создадим tablespace test размером 2G:
Убеждаемся что файл данных есть и размер его 2 гигабайта:
Ради чего все это затевалось
Мы имеем тестовую базу большого объема и хотим протестировать особо крупное изменение, затрагивающее структуру таблиц и требующее для проверки всех данных.
Клонируем тестовую базу в режиме snapshot:
И смотрим что произошло на файловой системе:
Файлы данных всех табличных пространств кроме TEMP это ссылки на ACFS снапшот, и место на диске они не занимают. Узнать сколько реально занял снапшот можно так:
Чего и добивались — 286МB против более 3GB
Естественно, если активно начать изменять блоки клона со снапшотами, занимаемое им место вырастет.
После того как провели тестирование, удаляем ненужный клон:
Убеждаемся что место освободилось:
Результат
В результате нам удалось сэкономить время и ресурсы. И не только дисковые, напомню, что все базы PDB используют один комплект процессов и одну SGA.
PS. Статья не претендует на полное описание Oracle Multitenant Architecture, рассмотрен лишь частный случай применительно к конкретной задаче.
Что такое pdb и cdb oracle
С выходом новой версии Oracle 12c пользователи этой БД приобрели принципиально новую возможность – облачные экземпляры базы данных. С ними можно выполнять массу различных действий – клонирование, перенос, извлечение и пр. Но для начала необходимо научиться самомму простому дейсвию – запуск и остановка БД.
В данном случае мы имеем дело с двумя принципиально разными видами БД: контейнерная (CDB) – она является основной “платформой”, на которой размещаются БД второго вида – подключаемые (PDB). Каждый экземпляр обоих видов БД необходимо запускать отдельно. В последующих обновлениях была добавлена возможность автоматического старта всех PDB во время запуска CDB. В первой же версии такая возможность отсутствует, поэтому придется запускать все вручную или добавить специальный триггер ON STARTUP, где во время запуска CDB будут запущены и необходимые PDB.
Запуск CDB ничем не отличается от БД предыдущих версий:
После этой операции все подключаемые базы данных (PDB) оказываются смонтированными, но неоткрытыми. Проверить состояние всех БД можно простым запросом.
Из БД, являющейся контейнером, можно открыть любую подключаемую БД или все сразу:
Все операции с выбранной PDB можно делать находясь непосредственно в контексте подключаемой БД. Сначала проверим где мы находимся сейчас, затем перейдем в MYPDB, остановим ее и запустим заново:
Вышеописанные команды запуска подключаемых БД можно добавить в триггер. Тогда желаемые PDB будут открываться автоматически.
Русские Блоги
Запустить и закрыть CDB, PDB
1. Инструмент подключения
sqlplus, pl / sql developer, TOAD и т. д.
Обычно DBA Oracle является sqlplus, процесс входа в систему выглядит следующим образом:
Имя созданного экземпляра: oracs133
2. PDB и CDB
В Oracle 12c была добавлена концепция сменной базы данных, PDB, позволяющая Один контейнер базы данных (CDB) содержит несколько подключаемых баз данных (PDB) 。
CDB называется Database Container, китайский переводится в контейнер базы данных, PDB называется Pluggable Database, вы можете подключить базу данных.
До ORACLE 12C экземпляры и базы данных находились в отношении «один к одному» или «многие к одному» (RAC): то есть экземпляр мог быть связан только с одной базой данных, и база данных могла загружаться несколькими экземплярами. Отношения между экземпляром и базой данных не могут быть однозначными. После ввода ORACLE 12C экземпляр и база данных могут иметь отношение один ко многим.
Ниже приводится официальный документ об отношениях между CDB и PDB.
Три, запустить и остановить базу данных
(1) Запустить базу данных
Запуск CDB
12c pass » sqlplus / as sysdba «Логин для подключения CDB Сейчас подключен root container 。
Процесс реализации выглядит следующим образом:
Возможны следующие варианты запуска:
Запуск PDB
Конкретный процесс заключается в следующем:
(2) Закройте базу данных
Чтобы продолжить вышеуказанную операцию, в настоящее время в pdb1, если вы хотите выйти из Oracle, вам сначала нужно закрыть PDB1, а затем закрыть базу данных.
После выбора CDB выполните отключение базы данных.
Процесс реализации выглядит следующим образом:
Заключительные шаги также могут быть разбиты:
Закройте файл данных, файл журнала и т. Д. Последовательно ( close ), контрольный файл ( dismount ) и, наконец, закройте экземпляр ( shutdown )。
Вы также можете закрыть базу данных за один шаг:
Прежде чем закрыть CDB, PDB не закрывается, поэтому эта операция также закроет PDB.
2. Несколько параметров и значение ОТКЛЮЧЕНИЯ
После выхода из базы данных состояние подключения самих данных не изменилось.
НОРМАЛЬНОЕ ОТКЛЮЧЕНИЕ: метод выключения по умолчанию: а) не разрешает новые подключения к базе данных; б) может быть закрыт только после отключения всех соединений, что менее эффективно
SHUTDOWN IMMIDIATE : Общий способ завершения работы: а) не разрешается создавать новые подключения; б) созданные подключения, если есть незавершенные операторы SQL, ждут их завершения, если не сразу отключены; в. Откат всех незафиксированных транзакций
ОТКЛЮЧЕНИЕ ТРАНЗАКЦИОННОГО: Очень низкое использование
ОТКЛЮЧЕНИЕ АБОРТА: а) незафиксированные транзакции не откатываются; б) завершают все операции SQL; в) все соединения отключаются. База данных быстро закрывается, но в следующий раз, когда ее необходимо восстановить, она запускается медленно, и данные сегмента отката и файла данных могут быть несовместимыми.
Резюме утверждений об открытии и закрытии базы данных (последовательное выполнение, с контекстом):
// Открыть базу данных
// Закрыть базу данных