1 copyright 2013, oracle and/or its affiliates. all rights reserved. · 2015. 1. 17. · title:...

1

Upload: others

Post on 16-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 1

Page 2: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 2

Oracle Database 12c: Transaction Guard и Application Continuity

Игорь Мельников

Oracle CIS

Page 3: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 3

План

Введение

Transaction Guard

Application Continuity

Заключение

Page 4: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 4

Разрыв соединения с БД может

привести к

потере данных

двойному вводу данных

необходимости перезагрузки

серверов приложений

потере пользователей

Как следствие:

жалобы пользователей

потеря их доверия к приложению

сложность обработки ошибок при

разработке приложений

Сбой БД во время выполнения транзакции Текущая ситуация

Серверы

приложений

Серверы БД

Пользователь

Page 5: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 5

Неизвестное состояние транзакции Текущая ситуация

Пользователь выбирает товар

и оплачивает его через web

Транзакция пользователя

отправляется через сервер

приложений в БД,

где создаётся транзакция БД

Серверы

приложений

Серверы БД

Пользователь

Page 6: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 6

Неизвестное состояние транзакции Текущая ситуация

Транзакция пользователя

отправляется через сервер

приложений в БД, где

создаётся транзакция БД

Транзакция фиксируется в БД

и результат возвращается

серверу приложений.

Сбой в инфраструктуре может

привести к тому, что сервер

приложений никогда не получит

ответ от БД.

Серверы

приложений

Серверы БД

Пользователь

Page 7: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 7

Неизвестное состояние транзакции Текущая ситуация

Приложение находится в

неопределённом состоянии.

Приложение возвращает

пользователю ошибку, который

может заказать товар второй

раз, или даже оплатит дважды. Серверы

приложений

Серверы БД

Пользователь

Page 8: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 8

Transparent Application Failover (TAF)

Успешно произошло подключение к СУБД

Появилась в Oracle Database Client 8.0.6

Page 9: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 9

Transparent Application Failover (TAF)

Сбой узла: приложение автоматически

переключилось на второй узел

Переключает приложение на другой узел Oracle RAC

Page 10: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 10

Возможности TAF

TAF сохраняет или восстанавливает:

– Соединение между клиентом и сервером

– Подготовленные SQL команды

– Активные курсоры (команда select), начавшие возвращать

результат выполнения

TAF не сохраняет и не защищает:

– Активные транзакции (ORA-25402 transaction must roll back)

– Серверные переменные PL/SQL пакетов

– Состояние сессии пользователя (команды alter session)

Page 11: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 11

Решения для разработчиков

Transaction Guard

Протокол и API,

которые возвращают

состояние последней

транзакции

Новое в Oracle Database 12c

Application Continuity

Попытка автоматически

повторить операции в

транзакции при

восстановлении после сбоя

Page 12: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 12

Transaction Guard

Предоставляет информацию о результате выполнения COMMIT

API , который «знает» о

каждой транзакции

Без Transaction Guard повтор

транзакции может привести к

логическим ошибкам

С Transaction Guard

приложение корректно

обрабатывает ситуацию

возникновения ошибки

Прозрачно используется для

Application Continuity

Серверы

приложений

Серверы БД

Пользователь

Page 13: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 13

Application Continuity Маскирует запланированное/незапланированное отключение

Повторяет все вызовы к БД

Маскирует большинство ошибок

ПО, систем хранения,

сети,«железа»

Не требуется трудоёмкая

разработка обработки ошибок

приложения

Транзакция

повторяется

Серверы

приложений

Серверы БД

Пользователь

Page 14: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 14

План

Введение

Transaction Guard

Application Continuity

Заключение

Page 15: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 15

Что такое Transaction Guard? Технология для получения надежной информации о фиксации

последней (до сбоя) транзакции

Transaction Guard включает в себя поддержку как с стороны сервера, так и стороны клиента:

Клиент должен быть версии 12.1 и выше!

API доступен в всех интерфейсах программирования: OCI/OCCI, JDBC Thin, ODP.Net

Без Transaction Guard практически невозможно определить факт успешной фиксации транзакции – требуется сложное программирование, и автоматический повтор может привести к нарушению логической целостности данных

TG прозрачно используется в Application Continuity, но может быть использован и независимо от AC

Page 16: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 16

Transaction Guard API для разработчиков

Транзакция

Client Driver

Start

Transaction

Database

Commit? Commit

SQL, PL/SQL или RPC

Resultset

SQL, PL/SQL или RPC

Communication failed

Время

Page 17: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 17

public class transactionGuardExample

{ ...

OracleConnection oconn = (OracleConnection) ods.getConnection();

// Получаем LTXID первой транзакции после подключения

LogicalTransactionId firstLtxid = oconn.getLogicalTransactionId();

// Обновление LTXID происходит вызовом нашего callback-а

oconn.addLogicalTransactionIdEventListener(this);

}

public class LtxidListenerImpl implements LogicalTransactionIdEventListener

{

...

public void onLogicalTransactionIdEvent(LogicalTransactionIdEvent ltxidEvent)

{

LogicalTransactionId newLtxid = ltxidEvent.getLogicalTransactionId();

// Запоминаем newLtxid в глобальной переменной ....

}

}

Transaction Guard for Java

Page 18: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 18

Transaction Guard – server side API Пакет DBMS_APP_CONT

Процедура GET_LTXID_OUTCOME

– GET_LTXID_OUTCOME (client_ltxid IN RAW,

committed OUT BOOLEAN, user_call_completed OUT BOOLEAN)

где:

committed – TRUE, если транзакция с номером client_ltxid была зафиксирована, FALSE – НЕ была зафиксирована

user_call_completed – была ли вся информация после фиксации передана клиенту (например: число строк после autocommit)

Page 19: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 19

Получаем событие FAN об отказе узла

Если можно восстановиться после ошибки:

Получаем LTXID последней транзакции в “погибшей” сесcии с помощью вызова getLogicalTransactionId

Открываем новую сессиию

Определяем факт фиксации с помощью вызова DBMS_APP_CONT.GET_LTXID_OUTCOME

Если транзакция успела зафиксироваться

Возвращаем управление: приложение может продолжать работу

eсли транзакция НЕ успела зафиксироваться

Генерируем исключение: приложение НЕ может продолжать работу

Transaction Guard Сценарий использования

Page 20: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 20

Transaction Guard for .Net (ODP.Net) class TransactionGuardDemo { static void Main(string[] args) {

string txnConStr = "user id=hr;password=hr;data source=oracle";

OracleConnection txnCon = new OracleConnection(txnConStr); txnCon.Open();

byte[] logicalTransactionId = txnCon.LogicalTransactionId;

try {

OracleTransaction txn = txnCon.BeginTransaction();

OracleCommand cmd = new OracleCommand(

"update employees set salary=salary+10 where employee_id=100", txnCon);

cmd.ExecuteNonQuery();

txn.Commit();

}

finally

{

string statusConStr = "user id=hr;password=hr;data source=oracle";

OracleConnection statusCon = new OracleConnection(statusConStr); statusCon.Open();

OracleLogicalTransactionStatus status =

statusCon.GetLogicalTransactionStatus(logicalTransactionId);

Console.WriteLine("Has the transaction been committed? " + status.Committed);

Console.WriteLine("Has the user call been completed? " + status.UserCallCompleted); } } }

•В ODP.Net инкапсулирует

вызов DBMS_APP_CONT.

GET_LTXID_OUTCOME

Page 21: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 21

Transaction Guard Поддержка широкого спектра технологий в СУБД

• На стороне клиента

– JDBC-thin, OCI, OCCI, ODP.net

• На стороне сервера СУБД

– Используется логический номер транзакции (logical transaction ID - LTXID)

– Поддерживаются все виды фиксаций (commit-а)

• Локальный commit (вызов команды COMMIT)

• Auto-commit,

• Commit внутри PL/SQL-объекта

• DDL, DCL, Parallel DDL

• Remote, Distributed

• Не работает: в процедурах использующих XA-интерфейс и dblinks на read/write c ADG-базы

Page 22: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 22

Transaction Guard Настройка

Добавлены два новых атрибута сервиса:

COMMIT_OUTCOME

Значения: TRUE and FALSE

По умолчанию: FALSE

Применяется к всем сессиям подключенным к данному сервису

RETENTION_TIMEOUT

Единица измерения – секунды

По умолчанию – 24 часа (86400 сек.)

Максимальное значение – 30 дней (2592000 сек.)

Пользователь должен иметь привилегию на выполнение пакета DBMS_APP_CONT

Page 23: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 23

Transaction Guard Настройка – пример

Новые параметры в утилите srvctl:

srvctl add service -d racdb -s OLTP -commit_outcome TRUE -

retention 604800 -notification TRUE … …

Через пакет DBMS_SERVICE (для single-instance БД): declare

v_xParams dbms_service.svc_parameter_array;

begin

v_xParams(‘COMMIT_OUTCOME') := 'true';

v_xParams(‘RETENTION_TIMEOUT‘) := 604800;

dbms_service.create_service('oltp',‘oltp',v_xParams);

commit;

end;

Page 24: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 24 Source: Gartner Top Five Trends for Private Cloud Computing, February 2012, Thomas J Bittman

Transaction Guard Оптимизация производительности

История транзакций (значения LXID) сохраняется в таблице

LTXID_TRANS

– Расположена в табличном пространстве SYSAUX

– Секционирована по номеру узла, при добавлении нового узла

добавляется новая секция (ее storage-параметры берутся из

последней секции)

– При больших нагрузках рекомендуется перенести ее в табличное

пространство на быстром носителе:

ALTER TABLE ltxid_trans MOVE PARTITION ltxid_trans_4

TABLESPACE ssd_tbs

STORAGE (INITIAL 25G NEXT 50G);

Page 25: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 25

Transaction Guard Особенности программирования

Вызов GET_LTXID_OUTCOME для текущей сессии будет

возвращать ошибку

Вызов GET_LTXID_OUTCOME для “живой” сессии будет

блокировать ее фиксацию

Вызов GET_LTXID_OUTCOME для другого пользователя будет

возвращать ошибку

GET_LTXID_OUTCOME должен вызываться только для “погибшей”

сессии!

Page 26: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 26

План

Введение

Transaction Guard

Application Continuity

Заключение

Page 27: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 27

Application Continuity Скрывает плановые и внеплановые простои

Повторяет транзакции

восстанавливая приложение от

ошибки

Когда это возможно: маскирует

ошибки железа, ПО, систем

хранения

Освобождает от трудоемкого

программирования перехвата

ошибок

Повышает продуктивность работы

пользователей

5. Ответ

приложению

1. Транзакция

2. Вызовы к БД

Oracle Database 12c

4. Повтор операций

3. Ошибка

Page 28: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 28

На стороне клиента

– Пока только JDBC-Thin драйвер поддерживает Application Continuity

– UCP, WebLogic Server, любые приложения сторонних разработчиков

– Перехват JDBC-вызовов, сохранение вызов в очереди повтора

На стороне сервера БД

– Поддерживаются все виды вызовов - SQL, PL/SQL, JDBC RPC

Select, ALTER SESSION, DML, DDL, COMMIT/ROLLBACK/SAVEPOINT

– Поддерживаются все типы транзакций

Local, Parallel, Remote, Distributed

– Cохранение результатов недетерминированных функций (sysdate,

sequence, sys_giud)

Application Continuity Поддержка как на стороне клиента, так и сервера СУБД

Page 29: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 29

Application Continuity Как работает AC

Call 1

Application Proxy 1

Proxy 2

RDBMS

Instance1

Instance2

Instance3

Call 2

Connection

Replay Context

JDBC Driver

Page 30: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 30

Application Continuity Фазы работы

1-Захват 2-Переподключение 3-Повтор

• Определение границ

перехвата вызовов

• Перехват вызов к БД

(proxy calls)

• Сохранение

оригинальных вызовов к

БД и bind-переменных в

буфере на клиенте

• Проверка что повтор

разрешен

• Открытие нового

соединения

• Соблюдение timeout на инициализацию повтора

• Проверка статуса

фиксации (COMMIT)

последней транзакции

• Повтор сохраненных

вызовов

• Продолжение повтора,

если результат запроса

НЕ изменился

• Продолжение работы

приложения

Page 31: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 31

Включение Application Continuity для сервиса Настройка – пример

2. Модифицируем атрибуты сервиса:

srvctl modify service -d racdb -s demo_ac -failovertype

TRANSACTION -replay_init_time 1800 -failoverdelay 10 -

failoverretry 30

1. Включаем для сервиса Transaction Guard

Page 32: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 32

Внутренняя архитектура Application Continuity

Page 33: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 33

Включение Application Continuity Изменить тип соединения

Без поддержки Application Continuity (как до Oracle Database 12с)

PoolDataSource pds = PoolDataSourceFactory.getPoolDataSource();

pds.setConnectionFactoryClassName(oracle.jdbc.pool.OracleDataSource);

Включить Application Continuity (только в Oracle Database 12с)

pds.setConnectionFactoryClassName(oracle.jdbc.replay.OracleDataSource

Impl);

Page 34: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 34

Единица работы - “Database Request” Пул соединений: неявное определение границ повтора

Блок работы; обычно заканчивается COMMIT

PoolDataSource pds = GetPoolDataSource();

Connection conn = getConnection(pds);

PreparedStatement pstmt = …

SQL, PL/SQL, local calls, RPC

conn.commit();

conn.close();

Конец

Начало

Page 35: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 35

Единица работы - “Database Request” Явное определение границ повтора c помощью AC API

Блок работы определен явно

((oracle.jdbc.replay.ReplayableConnection) conn).beginRequest();

PreparedStatement pstmt = …

SQL, PL/SQL, local calls

conn.commit();

((oracle.jdbc.replay.ReplayableConnection) conn).endRequest();

… Конец

Начало

Для non-pool соединений нужно явно выставлять границы повтора

Для пулов соединений – опционально

Page 36: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 36

Application Continuity Три типа ограничений, для которых AC не поддерживается

Глобальные Вызовы Тип БД

• Используются XA-источники данных

• Сервис по умолчанию (архитектурно!) – и в nonCDB, и в PDB

• JAVA Concrete classes

• Cистемные команды:

– Alter System

– Alter Database

•DBLinks на запись с StandBy

(Active Data Guard) на

Primary-БД

• Если БД - это реплика

– Logical Standby

– Golden Gate

Page 37: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 37

Application Continuity Возможные побочные эффекты (side-effects)

Когда повтор включен, некоторые вызовы могут быть повторены,

а для некоторых вызовов нужно отключать автоматический

повтор:

Вызовы с автономными транзакциями

Обращения к пакетам

– UTL_HTTP – обращение к веб-cерверу по HTTP

– UTL_URL –

– UTL_FILE, UTL_FILE_TRANSFER – работа с файлами

– UTL_SMPT, UTL_TCP, UTL_MAIL – отправка сообщений по email

– DBMS_PIPE – интеграция с внешними системами

– DBMS_ALERT

Page 38: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 38

Отключение повтора Отключение повтора для нетранзакционных вызовов

Отключение повтора для группы операций

PreparedStatement pstmt = …

((oracle.jdbc.replay.ReplayableConnection)

conn).disableReplay();

… вызов UTL_FILE

((oracle.jdbc.replay.ReplayableConnection)

conn).enableReplay();

conn.commit;

conn.close();

Для небезопасных вызовов повтор явно отключается: при ошибке

исключение не перехватывается, а “пробрасывается” приложению

После прохождения соотв. части кода – снова включается

Page 39: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 39

Владелец последовательности просто выполняет

либо:

Application Continuity – sequence, sysdate, sysguid Сохранение результата недетерминированных функций для повтора

SQL> GRANT [KEEP DATE TIME | KEEP SYSGUID].. [to USER]

SQL> GRANT KEEP SEQUENCE.. [to USER] on [sequence object];

SQL> REVOKE KEEP SEQUENCE [from USER] on [sequence object];

SQL> ALTER SEQUENCE.. [sequence object] [KEEP|NOKEEP];

SQL> CREATE SEQUENCE.. [sequence object] [KEEP|NOKEEP];

Page 40: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 40

Согласованное состояние сессии Session State Consistency

Выполнение вызова может зависеть от НЕтранзакционого

контекста:

NLS-установки

Значение в application context (SYS_CONTEXT)

Глобальные переменные в PL/SQL-пакетах

Временные таблицы

Сообщения в очереди AQ

Page 41: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 41

Согласованное состояние сессии Динамическое или статическое

Dynamic

Вызовы меняют нетранзакционный контекст (Напр: меняют

значение глобальной переменной в PL/SQL-пакета)

Невозможно безопасно повторить вызов – нужно восстановить

контекст, который был сформирован предыдущими вызовами

Static

Контекст постоянный для всех request-ов

Весь контекст необходимый для сессии может быть восстановлен

как часть инициализации в request-е

Вызовы не меняют этот контекст для других request-ов

Page 42: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 42

Согласованное состояние сессии Новый атрибут сервиса - SESSION_STATE_CONSISTENCY

SESSION_STATE_CONSISTENCY

По умолчанию имеет значение DYNAMIC

Невозможно безопасно повторить вызов – нужно

восстановить контекст, который был сформирован

предыдущими вызовами

В утилите srvctl добавлен новый параметр

-session_state {STATIC | DYNAMIC}

В пакете DBMS_SERVICE добавлен атрибут

session_state_consistency для Parameter_Array

Page 43: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 43

Функция установки контекста Connection Inizialization Callback

PoolDataSource pds = GetPoolDataSource();

pds.registerConnectionInitializationCallback(cbk);

Connection conn = getConnection(pds);

PreparedStatement pstmt = …

SQL, PL/SQL, local calls, RPC

conn.commit();

conn.close();

Регистрация функции обратного

вызова, которая отвечает за

инициализацию контекста

Интегрирован с UCP Labeling

Для однократного “разогрева” соединения

Page 44: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 44

Ограничения Когда повтор не работает?

Фаза захвата Фаза

переподключения

Фаза повтора

• Последняя фиксации была в dynamic mode

• Был вызов для которого повтор невозможен (Напр: alter system)

• Повтор был явно выключен с помощью disableReplay API

• Ошибка при повторе

• Невозможно переподключиться

• БД не соответствует для повтора (напр: Dataguard-реплика)

• Проверка результата для

курсора вернула другую

контрольную сумму

Page 45: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 45

Практика использования AC

Decide What to do

Границы бизнес-тран. Определить границы бизнес-транзакций, если приложение не

использует пул соединений

JDBC Concrete Classes Заменить конкретные Java-классы на Java-интерфейсы

Побочные эффекты Использовать disable API если вызовы нельзя безопасно

повторить

Callback-и для

контекста

Если для сессии нужен контекст, нужно разработать и

зарегистрировать callback-функцию

Мутирующие функции Выдать Grant Keep для недерминированных функций (sysdate,

sequence, sys_guid)

Page 46: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 46

Как правильно “убить” сессию

alter system kill session 'sid, serial#, @inst' noreplay;

alter system disconnect session 'sid, serial#, @inst'noreplay;

В процедуре DBMS_SERVICE.DISCONNECT_SESSION

Опция NOREPLAY в параметре disconnect_option

Page 47: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 47

RAC

Node 1

Listener

FAN

RAC

Node 3

Listener

FAN

RAC

Node 2

Listener

FAN

RAC Cluster

Generic, Active GridLink Data Source

WebLogic Server

Application

1. Request 7. Response

2. Request 6. Response 3. Node 1

Down 4. New

Connection

WebLogic Server с Application Continuity

Улучшение в доступности

Простая конфигурация.

Тесты показывают доп. ~5%

нагрузки CPU на клиенте и нет

увеличения время отклика на

клиенте при использовании AC

Интеграция с Transaction Guard

дает непрерывность работы

Преимущество: маскирование

ошибок отказа узла RAC

5. Replay

Page 48: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 48

TAF и Application Continuity В чем различие между TAF и Application Continuity?

TAF

– OCI, OCCI, JDBC Thin/OCI

– Повторяет только

операторы SELECT

– Для контекста нужно

определять callback

– Все проверки и действия

происходят только на

клиенте

Application Continuity

– Пока только в JDBC Thin

– Повторяет все виды запросов (SQL,

PL/SQL)

– Интегрирован с Transaction Guard

– Для контекста нужно определять

callback

– Сохранение результатов

недерминированных функций для

безопасного повтора

Page 49: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 49

Page 50: 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. · 2015. 1. 17. · Title: Openworld 2012 Keynote Author: W Hardie Subject: Oracle Database 12c Created Date:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 50