Diagnostic Connection for Database Administrators SQL Server provides a special diagnostic connection for administrators when standard connections to the server are not possible. This diagnostic connection allows an administrator to access SQL Server to execute diagnostic queries and troubleshoot problems even when SQL Server is not responding to standard connection requests. This dedicated administrator connection (DAC) supports encryption and other security features of SQL Server. The DAC only allows changing the user context to another admin user. SQL Server makes every attempt to make DAC connect successfully, but under extreme situations it may not be successful.

Connecting with DAC
By default, the connection is only allowed from a client running on the server. Network connections are not permitted unless they are configured by using the sp_configure stored procedure with the remote admin connections option. Only members of the SQL Server sysadmin role can connect using the DAC. The DAC is available and supported through the sqlcmd command-prompt utility using a special administrator switch (-A). For more information about using sqlcmd, see Use sqlcmd with Scripting Variables. You can also connect prefixing admin: to the instance name in the format sqlcmd -Sadmin:<instance_name>. You can also initiate a DAC from a SQL Server Management Studio Query Editor by connecting to admin:<instance_name>.

Restrictions
Because the DAC exists solely for diagnosing server problems in rare circumstances, there are some restrictions on the connection: To guarantee that there are resources available for the connection, only one DAC is allowed per instance of SQL Server. If a DAC connection is already active, any new request to connect through the DAC is denied with error 17810. To conserve resources, SQL Server Express does not listen on the DAC port unless started with a trace flag 7806. The DAC initially attempts to connect to the default database associated with the login. After it is successfully connected, you can connect to the master database. If the default database is offline or otherwise not available, the connection will return error 4060. However, it will succeed if you override the default database to connect to the master database instead using the following command: sqlcmd –A –d master We recommend that you connect to the master database with the DAC because master is guaranteed to be available if the instance of the Database Engine is started. SQL Server prohibits running parallel queries or commands with the DAC. For example, error 3637 is generated if you execute either of the following statements with the DAC: Only limited resources are guaranteed to be available with the DAC. Do not use the DAC to run resource-intensive queries (for example. a complex join on large table) or queries that may block. This helps prevent the DAC from compounding any existing server problems. To avoid potential blocking scenarios, if you have to run queries that may block, run the query under snapshot-based isolation levels if possible; otherwise, set the transaction isolation level to READ UNCOMMITTED and set the LOCK_TIMEOUT value to a short value such as 2000 milliseconds, or both. This will prevent the DAC session from getting blocked. However, depending on the state that the SQL Server is in, the DAC session might get blocked on a latch. You might be able to terminate the DAC session using CNTRL-C but it is not guaranteed. In that case, your only option may be to restart SQL Server. To guarantee connectivity and troubleshooting with the DAC, SQL Server reserves limited resources to process commands run on the DAC. These resources are typically only enough for simple diagnostic and troubleshooting functions, such as those listed below.
Although you can theoretically run any Transact-SQL statement that does not have to execute in parallel on the DAC, we strongly recommend that you restrict usage to the following diagnostic and troubleshooting commands: Querying dynamic management views for basic diagnostics such as sys.dm_tran_locks for the locking status, sys.dm_os_memory_cache_counters to check the health of caches, and sys.dm_exec_requests and sys.dm_exec_sessions for active sessions and requests. Avoid dynamic management views that are resource intensive (for example, sys.dm_tran_version_store scans the full version store and can cause extensive I/O) or that use complex joins. For information about performance implications, see the documentation for the specific dynamic management view. Querying catalog views. Basic DBCC commands such as DBCC FREEPROCCACHE, DBCC FREESYSTEMCACHE, DBCC DROPCLEANBUFFERS, and DBCC SQLPERF. Do not run resource-intensive commands such as DBCC CHECKDB, DBCC DBREINDEX, or DBCC SHRINKDATABASE. Transact-SQL KILL <spid> command. Depending on the state of SQL Server, the KILL command might not always succeed; then the only option may be to restart SQL Server. The following are some general guidelines: Verify that the SPID was actually killed by querying SELECT * FROM sys.dm_exec_sessions WHERE session_id = <spid>. If it returns no rows, it means the session was killed. If the session is still there, verify whether there are tasks assigned to this session by running the query SELECT * FROM sys.dm_os_tasks WHERE session_id = <spid>. If you see the task there, most likely your session is currently being killed. Note that this may take considerable amount of time and may not succeed at all. If there are no tasks in the sys.dm_os_tasks associated with this session, but the session remains in sys.dm_exec_sessions after executing the KILL command, it means that you do not have a worker available. Select one of the currently running tasks (a task listed in the sys.dm_os_tasks view with a sessions_id <> NULL), and kill the session associated with it to free up the worker. Note that it may not be enough to kill a single session: you may have to kill multiple ones.

DAC Port
SQL Server listens for the DAC on TCP port 1434 if available or a TCP port dynamically assigned upon Database Engine startup. The error log contains the port number the DAC is listening on. By default the DAC listener accepts connection on only the local port. For a code sample that activates remote administration connections, see remote admin connections Server Configuration Option. After the remote administration connection is configured, the DAC listener is enabled without requiring a restart of SQL Server and a client can now connect to the DAC remotely. You can enable the DAC listener to accept connections remotely even if SQL Server is unresponsive by first connecting to SQL Server using the DAC locally, and then executing the sp_configure stored procedure to accept connection from remote connections. On cluster configurations, the DAC will be off by default. Users can execute the remote admin connection option of sp_configure to enable the DAC listener to access a remote connection. If SQL Server is unresponsive and the DAC listener is not enabled, you might have to restart SQL Server to connect with the DAC. Therefore, we recommend that you enable the remote admin connections configuration option on clustered systems. The DAC port is assigned dynamically by SQL Server during startup. When connecting to the default instance, the DAC avoids using a SQL Server Resolution Protocol (SSRP) request to the SQL Server Browser Service when connecting. It first connects over TCP port 1434. If that fails, it makes an SSRP call to get the port. If SQL Server Browser is not listening for SSRP requests, the connection request returns an error. Refer to the error log to find the port number DAC is listening on. If SQL Server is configured to accept remote administration connections, the DAC must be initiated with an explicit port number: sqlcmd –Stcp:<server>,<port> The SQL Server error log lists the port number for the DAC, which is 1434 by default. If SQL Server is configured to accept local DAC connections only, connect using the loopback adapter using the following command: sqlcmd –S127.0.0.1,1434

Example
In this example, an administrator notices that server URAN123 is not responding and wants to diagnose the problem. To do this, the user activates the sqlcmd command prompt utility and connects to server URAN123 using -A to indicate the DAC. sqlcmd -S URAN123 -U sa -P <xxx> –A The administrator can now execute queries to diagnose the problem and possibly terminate the unresponsive sessions.

Related Content
|
Conexión de diagnóstico para administradores de bases de datos SQL Server proporciona una conexión de diagnóstico especial para los administradores cuando no son posibles las conexiones estándar con el servidor. La conexión de diagnóstico permite a un administrador tener acceso a SQL Server para ejecutar consultas de diagnóstico y solucionar problemas, incluso cuando SQL Server no responde a las solicitudes de conexión estándar. Esta conexión de administrador dedicada (DAC) admite la característica de cifrado y otras características de seguridad de SQL Server. La DAC solo permite cambiar el contexto de usuario a otro usuario de administración. SQL Server hace lo posible para que la conexión de administrador dedicada (DAC) sea correcta, pero, en situaciones extremas, es posible que no lo logre.

Conectar con DAC
De forma predeterminada, solo se permite la conexión desde un cliente que se ejecute en el servidor. Las conexiones de red no están permitidas, a menos que se configuren mediante el procedimiento almacenado sp_configure con la opción remote admin connections. Solo los miembros del rol sysadmin de SQL Server pueden conectarse usando la DAC. La DAC está disponible y permitida a través de la utilidad del símbolo del sistema sqlcmd mediante un modificador de administrador especial (-A). Para obtener más información acerca de cómo usar sqlcmd, vea Usar sqlcmd con variables de script. También se puede conectar agregando el prefijo admin: al nombre de la instancia en el formato sqlcmd -Sadmin:<instance_name>.. También puede iniciar una DAC desde un Editor de Consultas SQL Server Management Studio conectando a admin:<instance_name>.

Restricciones
Dado que la DAC existe únicamente para el diagnóstico de problemas de servidor en raras circunstancias, hay algunas restricciones en la conexión: Para asegurarse de que haya recursos disponibles para la conexión, solo se permite una DAC por cada instancia de SQL Server. Si ya hay una conexión DAC activa, cualquier solicitud nueva de conexión a través de la DAC se denegará con el error 17810. Para ahorrar recursos, SQL Server Express no escucha en el puerto DAC a menos que se inicie con la marca de seguimiento 7806. Inicialmente la DAC intenta conectarse a la base de datos predeterminada asociada al inicio de sesión. Una vez conectada correctamente, el usuario podrá conectarse a la base de datos master. Si la base de datos predeterminada está sin conexión o no disponible por la razón que sea, la conexión devolverá el error 4060. Con todo, se realizará correctamente si invalida la base de datos predeterminada para conectarse a la base de datos master usando el comando siguiente: sqlcmd –A –d maestra Se recomienda conectarse a la base de datos master con la DAC porque la disponibilidad de master está garantizada si se ha iniciado la instancia de Motor de base de datos. SQL Server prohíbe la ejecución de comandos o consultas paralelas con la DAC. Por ejemplo, se genera el error 3637 si se ejecuta una de las instrucciones siguientes con la DAC: Con la DAC solo está garantizada la disponibilidad de recursos limitados. No use la DAC para ejecutar consultas que consuman muchos recursos (por ejemplo, una combinación compleja en una tabla grande) o consultas que se puedan bloquear. Así se evita que la DAC agrave cualquier problema de servidor ya existente. Para evitar posibles escenarios de bloqueo, si debe ejecutar consultas que se pueden bloquear, ejecútelas con niveles de aislamiento basado en instantáneas siempre que sea posible; de lo contrario, establezca el nivel de aislamiento de transacción en READ UNCOMMITTED y establezca un valor pequeño, como 2000 milisegundos, para LOCK_TIMEOUT, o ambos. Esto evitará que la sesión de la DAC se bloquee. Sin embargo, dependiendo del estado en el que esté SQL Server, puede ser que la sesión de la DAC se bloquee en un bloqueo temporal. Es posible que pueda finalizar la sesión de la DAC mediante CTRL-C, pero esto no está garantizado. En tal caso, la única alternativa puede ser reiniciar SQL Server. Para asegurarse de la conectividad y la solución de problemas con la DAC, SQL Server reserva recursos limitados para procesar los comandos ejecutados en la DAC. Estos recursos solo suelen ser suficientes para funciones sencillas de diagnóstico y solución de problemas, como las que se mencionan más adelante.
Aunque teóricamente es posible ejecutar cualquier instrucción Transact-SQL que no se tenga que ejecutar en paralelo en la DAC, se recomienda encarecidamente limitar el uso a los siguientes comandos de diagnóstico y solución de problemas: Consultar las vistas de administración dinámica para realizar diagnósticos básicos como sys.dm_tran_locks del estado de bloqueo, sys.dm_os_memory_cache_counters para comprobar el estado de cachés, y sys.dm_exec_requests y sys.dm_exec_sessions en las sesiones y solicitudes activas. Evite las vistas de administración dinámica que consumen muchos recursos (por ejemplo, sys.dm_tran_version_store examina el almacén de versiones completo y puede causar numerosas E/S) o que utilizan combinaciones complejas. Para obtener información acerca de las implicaciones para el rendimiento, vea la documentación específica para la vista de administración dinámica. Consultas en vistas de catálogo. Comandos DBCC básicos como DBCC FREEPROCCACHE, DBCC FREESYSTEMCACHE, DBCC DROPCLEANBUFFERS, y DBCC SQLPERF. No ejecute comandos que consumen muchos recursos, como DBCC CHECKDB, DBCC DBREINDEX o DBCC SHRINKDATABASE. Transact-SQL KILL <spid> comando. Dependiendo del estado de SQL Server, es posible que el comando KILL no siempre se ejecute correctamente; en tal caso, la única opción puede ser reiniciar SQL Server. Éstas son algunas directrices generales: Compruebe que realmente se ha eliminado el SPID con la consulta SELECT * FROM sys.dm_exec_sessions WHERE session_id = <spid>. Si no devuelve ninguna fila, significa que la sesión se ha eliminado. Si la sesión todavía existe, compruebe si hay tareas asignadas a esta sesión ejecutando la consulta SELECT * FROM sys.dm_os_tasks WHERE session_id = <spid>. Si ve la tarea, lo más probable es que se esté eliminando la sesión ahora. Tenga en cuenta que es posible que esto tarde bastante tiempo y que no salga correctamente. Si no hay ninguna tarea en sys.dm_os_tasks asociada a esta sesión, pero la sesión permanece en sys.dm_exec_sessions tras ejecutar el comando KILL, significa que no tiene ningún trabajo disponible. Seleccione una de las tareas que se están ejecutando (una tarea que aparece en la vista sys.dm_os_tasks con sessions_id <> NULL), y elimine la sesión que tiene asociada para liberar el trabajo. Tenga en cuenta que es posible que no sea suficiente eliminar una sola sesión: posiblemente tendrá que eliminar varias.

Puerto de la DAC
SQL Server escucha la DAC en el puerto TCP 1434 si está disponible o en un puerto asignado dinámicamente en el inicio de Motor de base de datos. El registro de errores contiene el número de puerto en el que escucha la DAC. De forma predeterminada, la escucha de la DAC solo acepta la conexión en el puerto local. Para obtener un ejemplo de código que active conexiones de administración remotas, vea remote admin connections (opción de configuración del servidor). Una vez configurada la conexión de administración remota, la escucha de la DAC se habilita sin necesidad de reiniciar SQL Server y se puede conectar un cliente a la DAC de forma remota. Puede habilitar la escucha de la DAC para que acepte las conexiones remotamente incluso si SQL Server no responde conectándose primero a SQL Server mediante la DAC de forma local y, a continuación, ejecutando el procedimiento almacenado sp_configure para aceptar la conexión desde conexiones remotas. En las configuraciones de clúster, la DAC estará desactivada de forma predeterminada. Los usuarios pueden ejecutar la opción remote admin connection de sp_configure para habilitar la escucha de la DAC para tener acceso a una conexión remota. Si SQL Server no responde y la escucha de la DAC no está habilitada, es posible que tenga que reiniciar SQL Server para conectarse a la DAC. Por esta razón, es recomendable que habilite la opción de configuración remote admin connections en los sistemas en clúster. Durante el inicio, SQL Server asigna dinámicamente el puerto de la DAC. Mientras se establece la conexión a la instancia predeterminada, la DAC evita el uso de una solicitud del protocolo de resolución de SQL Server (SSRP) al servicio SQL Server Browser. Primero se conecta a través del puerto TCP 1434. Si se produce un error, realiza una llamada SSRP para obtener el puerto. Si el Explorador de SQL Server no escucha las solicitudes SSRP, la solicitud de conexión devolverá un error. Consulte el registro de errores para ver en qué número de puerto escucha la DAC. Si SQL Server está configurado para aceptar conexiones de administración remotas, la DAC debe iniciarse con un número de puerto explícito: sqlcmd –Stcp:<server>,<port> El registro de errores de SQL Server muestra el número de puerto de la DAC, que es 1434 de forma predeterminada. Si SQL Server está configurado para aceptar solo conexiones DAC locales, conéctese mediante el adaptador de bucles invertidos con el comando siguiente: sqlcmd –S127.0.0.1,1434

Ejemplo
En este ejemplo, un administrador observa que el servidor URAN123 no responde y desea diagnosticar el problema. Para ello, el usuario activa la utilidad del símbolo del sistema sqlcmd y se conecta al servidor URAN123 mediante -A para indicar la DAC. sqlcmd -S URAN123 -U sa -P <xxx> –A Ahora el administrador puede ejecutar consultas para diagnosticar el problema y posiblemente finalizar las sesiones que no responden.

Contenido relacionado
|