Tns oracle что это
Здесь клиентом является утилита SQL*Plus. scott/tiger — имя пользователя и пароль, а ora816.us.oracle.com — имя службы TNS. TNS — сокращение от Transparent Network Substrate (прозрачная сетевая среда), которое обозначает базовое программное обеспечение, встроенное в клиент Oracle и обеспечивающее удаленное подключение (двухточечное взаимодействие клиента и сервера). Строка подключения TNS указывает программному обеспечению Oracle, как подключаться к удаленной базе данных. В общем случае клиентское программное обеспечение обращается к файлу TNSNAMES.ORA. Это обычный текстовый файл конфигурации, обычно находящийся в каталоге [ORACLE HOME]\network\admin и содержащий записи вида:
(ADDRESS = (PROTOCOL = TCP) (HOST = aria.us.oracle.com)(PORT = 1521))
(ORACLE SID = ora816)
Именно эти параметры конфигурации позволяют клиентскому ПО Oracle преобразовать строку ora816.us.oracle.com в необходимые для подключения данные: имя хоста; порт на этом хосте, прослушиваемый процессом, который принимает подключения; идентификатор SID (Site IDentifier) базы данных на хосте, к которой необходимо подключиться, и т.д. Эта строка, ora816.us.oracle.com, может преобразовываться в необходимые данные и по-другому. Например, она может преобразовываться с помощью службы Oracle Names — распределенного сервера имен для СУБД, аналогичного по назначению службе DNS, используемой для преобразования имен хостов в IP-адреса. Однако в большинстве небольших и средних серверов, где количество копий конфигурационных файлов невелико, чаще всего используется именно файл TNSNAMES.ORA.
Теперь, когда клиентскому ПО известно, куда подключаться, оно открывает соединение через сокет TCP/IP к порту 1521 машины aria.us.oracle.com. Если администратор базы данных соответствующего сервера настроил службу Net8 и запустил процесс прослушивания, это подключение может быть принято. В сетевой среде на сервере работает процесс TNS Listener. Это процесс прослушивания, обеспечивающий физическое подключение к базе данных. Получив запрос на подключение, он проверяет его, используя собственные файлы конфигурации, и либо отвечает отказом (например, не существует запрашиваемой базы данных или IP-адрес подключающегося содержится в списке тех, кому не разрешено подключение к хосту), либо обеспечивает подключение клиента.
При подключении к выделенному серверу процесс прослушивания автоматически запустит выделенный сервер. В ОС UNIX это делается с помощью системных вызовов fork() и ехес() (единственный способ создать новый процесс после инициализации ОС UNIX — использовать системный вызов iork()). Теперь мы физически подключены к базе данных. В Windows процесс прослушивания требует от серверного процесса создания нового потока для подключения. После создания этого потока клиент перенаправ-
ляется на него, и тем самым обеспечивается физическое подключение. В случае ОС UNIX это можно представить следующей схемой:
В режиме MTS процесс прослушивания работает иначе. Ему известно, какие процессы-диспетчеры работают в составе экземпляра. При получении запроса на подключение процесс прослушивания выбирает процесс-диспетчер из пула доступных диспетчеров. Затем он посылает клиенту информацию, позволяющую подключиться к процессу-диспетчеру. Это необходимо, поскольку процесс прослушивания работает на известном порту соответствующего хоста, а вот диспетчеры будут принимать подключения через произвольно выделенные порты. Процессу прослушивания известны эти выделенные порты, поэтому он автоматически выбирает свободный диспетчер. Затем клиент отключается от процесса прослушивания и подключается непосредственно к диспетчеру. В результате устанавливается физическое соединение с СУБД. Графически это можно представить так:
Итак, обзор архитектуры Oracle закончен. Мы описали, что такое экземпляр Oracle, что такое база данных и как можно подключиться к базе данных через выделенный и разделяемый сервер. На следующей схеме показано взаимодействие с сервером Oracle клиента, подключенного к разделяемому серверу, и клиента, работающего с выделенным серверным процессом. Один экземпляр Oracle может поддерживать оба типа подключений одновременно:
Теперь подробно рассмотрим процессы, образующие сервер, их назначение и взаимодействие друг с другом, а также содержимое области SGA и назначение ее компонентов. Но начнем мы с описания различных типов файлов, которые сервер Oracle использует для управления данными.
В состав базы данных и экземпляра входит шесть типов файлов. С экземпляром связаны файлы параметров. По этим файлам экземпляр при запуске определяет свои характеристики, например размер структур в памяти и местонахождение управляющих файлов.
Базу данных образуют следующие файлы.
Файл1 данн1х. Собственно данные (в этих файлах хранятся таблицы, индексы и
все остальные сегменты).
Файл1 журнала повторного в1полнения. Журналы транзакций.
Управляющие файл1. Определяют местонахождение файлов данных и содержат другую необходимую информацию о состоянии базы данных.
Временн1е файл1. Используются при сортировке больших объемов данных и для хранения временных объектов.
Файл1 паролей. Используются для аутентификации пользователей, выполняющих
администрирование удаленно, по сети. Мы не будем их подробно рассматривать.
Наиболее важны первые два типа файлов, поскольку именно в них хранятся накопленные данные. В случае потери остальных файлов хранящиеся данные не пострадают. Если будут потеряны файлы журнала повторного выполнения, некоторые данные могут быть потеряны. Если же будут потеряны файлы данных и все их резервные копии, данные, безусловно, будут потеряны навсегда.
What is a TNS:listener in the Context of Oracle?
Borderline ServerFault question, but figured I’d try here first since I’ve had luck with Oracle questions in the past.
I’m trying to connect to an oracle database from PHP, and I’m getting the following error.
This is the error that PHP reports, and the error that shows up in Oracle’s listener.log.
My immediate problem is fixing this error. The larger question I’d like answered is how does Oracle connection model work?
This is in a development environment that’s running on my local windows machine and has been working up until now. Unfortunately, the environment was handed to me (I didn’t set it up) and the people who did set it up are unavailable to help me debug it.
If I was getting a similar error with MySQL or PostgreSQL (two systems I’m more familiar with), I’d check to ensure that a database process was running, and then attempt to connect manually to the database using the username/password/connection string. Unfortunately, I’m not familiar with the Oracle tools on windows (other than SQL Developer) and I don’t know what a TNS:listener or SID are in the context of Oracle (I have vague ideas, but vague ideas rarely help when you’re debugging something like this)
Any general advice would be appreciated.
Updates per Comments:
There’s a number of entires in my tnsnames.ora file, the relevant entry being
This is not reflected in the list of instances when I run
So I think my next question is, how do I attempt to manually start up the OBS2 instance?
Transparent Network Substrate (tns) и другие уровни Net8
Программное средство Net8, выполняемое в сети Oracleкак на станциях клиентов, так и на серверах, состоит из трех различных уровней: уровняNet, уровня TNS и адаптера протокола.
Уровень Netна станции клиента разрешает приложению прозрачный доступ к удаленной базе данных при помощиSQL, как если бы база данных была на том же компьютере, что и клиент. УровеньNetна сервере позволяет ему получать и посылать данные в ответ на SQL-запросы клиентов, как если бы клиент работал на той же машине, что и север.
Уровень Transparent Network Substrate (TNS—прозрачный сетевой субстрат) —это программное средство, которое предоставляет клиентам и серверам простой прикладной программный интерфейс для всех сетевых протоколов, удовлетворяющих промышленным стандартам. Встраивая сетевые адаптеры протоколов в TNS, клиенты и серверы могут взаимодействовать при помощи любого сетевого протокола.
Адаптер протокола (protocol adapter)Oracleнеобходим для преобразования функциональных средств TNS в вид, понятный конкретному сетевому коммуникационному протоколу. В Net8 имеются адаптеры для всех широко распространенных сетевых протоколов, в том числеTCP/IP,IPX/SPX,DecNet,LU6.2 и др.).
Когда приложение клиента выполняет SQL-оператор, этот оператор проходит через каждый уровень Net8 на станции клиента, затем упаковывается и посылается по сети. Net8 на сервере открывает сетевой пакет и передает запрос через различные уровни (в обратном порядке) серверу базы данных, как если бы этот SQL-оператор был выдан локальным приложением. После обработки оператора сервер возвращает клиенту результаты через Net8 (в обратном порядке) и сеть.
Соединения, инициаторы и адресаты tns
TNS-соединение(TNS connection) —это устойчивая коммуникационная магистраль, соединяющая два узла сети, по которой данные пересылаются с одного компонента TNS на другой. В каждом соединении TNS один узел является инициатором(initiator)соединения, или просто инициатором, а другой — адресатом(destination).Как правило, инициатор в TNS-соединении — это клиент, а адресат — сервер базы данныхOracle. Однако в системе распределенной базы данных с помощью TNS-соединений могут взаимодействовать между собой и серверы. Более подробно о системах распределенных баз данных рассказано позже.
Пулинг соединений
Соединения обеспечивают работу приложений, которые большую часть времени бездействуют. Например, работая с приложением по вводу заказов при заполнении экранного бланка, продавец не посылает и не принимает какую-либо информацию через TNS-соединение.
Чтобы ограничить число физических сетевых соединений и более эффективно использовать ресурсы сети, Net8 может выполнять пулинг(pooling),или создавать пул(pool),состоящий из предварительно заданного числа TNS-соединений. Основные концепции пулинга соединений представлены на рис. 11.
При пулинге соединений простаивающий сеанс может временно разрешать другому сеансу использовать свое физическое TNS-соединение, а позже, когда первому сеансу вновь понадобится связь с сервером, его соединение восстанавливается. Поэтому пулинг соединений позволяет множеству сеансов взаимодействовать с сервером базы данных, совместно используя предварительно установленное число доступных TNS-соединений. При этом для обеспечения работы приложений расходуется меньше ресурсов, что повышает производительность сервера.
Сервер не начинает пулинг TNS-соединений до тех пор, пока не будет открыто заданное число физических сетевых соединений. Чтобы открыть следующее TNS-соединение, сервер базы данных должен сначала найти простаивающий сеанс, а затем логически переназначить соединение такого сеанса новому соединению. Предельное число физических сетевых соединений можно установить до запуска сервера при помощи соответствующего параметра конфигурации.
6 Local Naming Parameters (tnsnames.ora)
This chapter provides a complete listing of the tnsnames.ora file configuration parameters.
This chapter contains the following topics:
Overview of Local Naming Parameters
This tnsnames.ora file is a configuration file that contains net service name s mapped to connect descriptor s for the local naming method, or net service names mapped to listener protocol addresses.
A net service name is an alias mapped to a database network address contained in a connect descriptor. A connect descriptor contains the location of the listener through a protocol address and the service name of the database to which to connect. Clients and database servers (that are clients of other database servers) use the net service name when making a connection with an application.
By default, the tnsnames.ora file is located in the ORACLE_HOME/network/admin directory. Oracle Net will check the other directories for the configuration files. For example, the order checking the tnsnames.ora file is as follows:
The directory specified by the TNS_ADMIN environment variable. If the file is not found in the directory specified, then it is assumed that the file does not exist.
If the TNS_ADMIN environment variable is not set, then Oracle Net will check the ORACLE_HOME/network/admin directory.
On Microsoft Windows, the TNS_ADMIN environment variable is used if it is set in the environment of the process. If the TNS_ADMIN environment variable is not defined in the environment, or the process is a service which does not have an environment, then Microsoft Windows scans the registry for a TNS_ADMIN parameter.
Oracle operating system-specific documentation
General Syntax of tnsnames.ora
The basic syntax for a tnsnames.ora file is shown in Example 6-1.
Example 6-1 Basic Format of tnsnames.ora File
In the preceding example, DESCRIPTION contains the connect descriptor, ADDRESS contains the protocol address, and CONNECT_DATA contains the database service identification information.
Multiple Descriptions in tnsnames.ora
A tnsnames.ora file can contain net service names with one or more connect descriptors. Each connect descriptor can contain one or more protocol addresses. Example 6-2 shows two connect descriptors with multiple addresses. DESCRIPTION_LIST defines a list of connect descriptors.
Example 6-2 Net Service Name with Multiple Connect Descriptors in tnsnames.ora
Oracle Net Manager does not support the creation of multiple connect descriptors for a net service name when using Oracle Connection Manager.
Multiple Address Lists in tnsnames.ora
The tnsnames.ora file also supports connect descriptors with multiple lists of addresses, each with its own characteristics. In Example 6-3, two address lists are presented. The first address list features client load balancing and no connect-time failover , affecting only those protocol addresses within the ADDRESS_LIST . The second protocol address list features connect-time failover and no client load loading balancing, affecting only those protocol addresses within the ADDRESS_LIST . The client first tries the first or second protocol address at random, then tries protocol addresses three and four sequentially.
Example 6-3 Multiple Address Lists in tnsnames.ora
Oracle Net Manager supports only the creation of one protocol address list for a connect descriptor.
Connect-Time Failover and Client Load Balancing with Oracle Connection Managers
When a connect descriptor in a tnsnames.ora file contains at least two protocol addresses for Oracle Connection Manager , parameters for connect-time failover and load balancing can be included in the file.
Example 6-4 illustrates failover of multiple Oracle Connection Manager protocol addresses.
Example 6-4 Multiple Oracle Connection Manager Addresses in tnsnames.ora
In Example 6-4, the syntax does the following:
The client is instructed to connect to an protocol address of the first Oracle Connection Manager, as indicated by:
The first Oracle Connection Manager is instructed to connect to the first protocol address of another Oracle Connection Manager. If the first protocol address fails, then it tries the second protocol address. This sequence is specified with the following configuration:
The Oracle Connection Manager connects to the database service using the following protocol address:
Example 6-5 illustrates client load balancing among two Oracle Connection Managers and two protocol addresses:
Example 6-5 Client Load Balancing in tnsnames.ora
In Example 6-5, the syntax does the following:
The client is instructed to pick an ADDRESS_LIST at random and to failover to the other if the chosen ADDRESS_LIST fails. This is indicated by the LOAD_BALANCE and FAILOVER parameters being set to on .
When an ADDRESS_LIST is chosen, the client first connects to the Oracle Connection Manager, using the Oracle Connection Manager protocol address that uses port 1630 indicated for the ADDRESS_LIST .
The Oracle Connection Manager then connects to the database service, using the protocol address indicated for the ADDRESS_LIST .
Connect Descriptor Descriptions
Each connect descriptor is contained within the DESCRIPTION parameter. Multiple connect descriptors are characterized by the DESCRIPTION_LIST parameter. These parameters are described in this section.
DESCRIPTION
To specify a container for a connect descriptor. Put this parameter under the DESCRIPTION_LIST parameter.
DESCRIPTION_LIST
To define a list of connect descriptors for a particular net service name.
Protocol Address Section
The protocol address section of the tnsnames.ora file specifies the protocol addresses of the listener. If there is only one listener protocol address, then use the ADDRESS parameter. If there is more than one address, then use the ADDRESS_LIST parameter.
ADDRESS
To define a single listener protocol address. Put this parameter under either the ADDRESS_LIST parameter or the DESCRIPTION parameter.
Chapter 4, «Protocol Address Configuration» for descriptions of the correct parameters to use for each protocol
ADDRESS_LIST
To define a list of protocol addresses. If there is only one listener protocol address, then ADDRESS_LIST is not necessary. Put this parameter under either the DESCRIPTION parameter or the DESCRIPTION_LIST parameter.
Optional Parameters for Address Lists
For multiple addresses, the following parameters are available:
ENABLE
The keepalive feature on the supported TCP transports can be enabled for a net service client by putting (ENABLE=broken) under the DESCRIPTION parameter in the connect string. The keepalive feature allows the caller to detect a terminated remote server, although typically it takes 2 hours or more to notice. On the client side, the default for tcp_keepalive is off . Operating system TCP configurables, which vary by platform, define the actual keepalive timing details.
FAILOVER
To enable or disable connect-time failover for multiple protocol addresses.
When you set the parameter to on , yes , or true , Oracle Net, at connect time, fails over to a different address if the first protocol address fails. When you set the parameter to off , no , or false , Oracle Net tries one protocol address.
Put this parameter under the DESCRIPTION_LIST parameter, the DESCRIPTION parameter, or the ADDRESS_LIST parameter.
Do not set the GLOBAL_DBNAME parameter in the SID_LIST_ listener_name section of the listener.ora . A statically configured global database name disables connect-time failover.
on for DESCRIPTION_LIST , DESCRIPTION , and ADDRESS_LIST .
LOAD_BALANCE
To enable or disable client load balancing for multiple protocol addresses.
When you set the parameter to on , yes , or true , Oracle Net progresses the list of addresses in a random sequence, balancing the load on the various listener or Oracle Connection Manager protocol addresses. When you set the parameter to off , no , or false , Oracle Net tries the first address in the address list. If the connection fails and the failover parameter is enabled, then Oracle Net tries the addresses sequentially until one succeeds.
Put this parameter under either the DESCRIPTION_LIST parameter, the DESCRIPTION parameter, or the ADDRESS_LIST parameter.
on for DESCRIPTION_LIST
RECV_BUF_SIZE
To specify, in bytes, the buffer space for receive operations of sessions. This parameter is supported by the TCP/IP, TCP/IP with SSL, and SDP protocols.
Put this parameter under the DESCRIPTION parameter or at the end of the protocol address.
Additional protocols might support this parameter on certain operating systems. Refer to the operating system-specific documentation for additional information about additional protocols.
The default value for this parameter is specific to the operating system.
Setting this parameter in the connect descriptor for a client overrides the RECV_BUF_SIZE parameter at the client-side sqlnet.ora file.
Oracle Database Net Services Administrator’s Guide for additional information about configuring this parameter
To instruct Oracle Net to optimize the transfer rate of data packets being sent across the network with a specified session data unit (SDU) size.
Put this parameter under the DESCRIPTION parameter.
8192 bytes (8 KB).
512 to 65535 bytes.
Setting this parameter in the connect descriptor for a client overrides the DEFAULT_SDU_SIZE parameter at client-side sqlnet.ora file.
Oracle Database Net Services Administrator’s Guide for complete SDU usage and configuration information
SEND_BUF_SIZE
To specify, in bytes, the buffer space for send operations of sessions. This parameter is supported by the TCP/IP, TCP/IP with SSL, and SDP protocols.
Additional protocols might support this parameter on certain operating systems. Refer to the operating system-specific documentation for additional information about additional protocols.
Put this parameter under the DESCRIPTION parameter or at the end of the protocol address.
The default value for this parameter is operating system-specific.
Setting this parameter in the connect descriptor for a client overrides the SEND_BUF_SIZE parameter at the client-side sqlnet.ora file.
Oracle Database Net Services Administrator’s Guide for additional information about configuring this parameter
SOURCE_ROUTE
To enable routing through multiple protocol addresses.
When you set to on or yes , Oracle Net uses each address in order until the destination is reached.
To use Oracle Connection Manager, an initial connection from the client to Oracle Connection Manager is required, and a second connection from Oracle Connection Manager to the listener is required.
Put this parameter under either the DESCRIPTION_LIST parameter, the DESCRIPTION parameter, or the ADDRESS_LIST parameter.