23 febrero, 2010

Diagnóstico de problemas de conexión a SQL Server 2005/2008, Parte 2

/*
Este post muestra cómo diagnosticar problemas de conexión a SQL Server usando cliente SNAC, según sea el mensaje de error obtenido. El post original en inglés fué realizado por Ming Lu y publicado en http://blogs.msdn.com/sql_protocols/archive/2005/10/22/483684.aspx

He realizado la traducción a español y algunas aclaraciones mínimas para dar mayor claridad.
*/

En este artículo mostraremos cómo diagnosticar problemas de conexión a SQL Server 2005/2008, usando el cliente SNAC (SQL Server Native Client) y según sea el mensaje de error recibido. Este artículo es la continuación de:

Diagnóstico de problemas de conexión a SQL Server 2005/2008, Parte 1
http://ascii164.blogspot.com/2009/10/diagnostico-de-problemas-de-conexion.html

En la Parte 1 se mostró como diagnosticar problemas generales de conexión, especialmente desde el punto de vista de red.

En esta parte, vamos a considerar los mensajes de error en inglés (brindados por un SQL Server en dicho idioma) y según sea la biblioteca cliente que se esté usando para conectarse. Antes de comenzar, es muy importante entender qué biblioteca cliente se está usando para conectarse al SQL Server. Tenemos entonces:

- SNAC (SQL Server Native Client): Es una API que es usada tanto por ODBC como OLEDB. Esta tecnología de acceso a datos apareció con SQL Server 2005.

- MDAC ( Microsoft Data Access Component): Contiene los componentes de acceso a datos fundamentales, como son el proveedor OLEDB y ODBC.

- SqlClient: Acceso a datos desde un objeto de base de datos CLR usando el proveedor de .NET (.NET Framework Data Provider for SQL Server).

Empezaremos viendo el caso de SNAC y en próximos artículos veremos los otros.


1. FALLAS DE CONEXION USANDO SNAC

Si la aplicación usa ODBC para conectarse, ejecutar osql.exe para simular el string de conexión de la aplicación y diagnosticar rápidamente. Si la aplicación usa OLEDB, usar sqlcmd.exe

Tanto osql.exe como sqlcmd.exe están en la carpeta %SYSTEMDRIVE%\%ProgramFiles%\Microsoft Sql Server\90\tools\binn.

osql(sqlcmd) /S servidor /E
osql(sqlcmd) /S servidor\instancia /E

Los mensajes posibles de error a analizar son:

1.1. MENSAJE 1: No se pudo abrir conexión (estado 53)

[SQL Native Client]Named Pipes Provider: Could not open a connection to SQL Server [53].
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
-o-
HResult 0x35, Level 16, State 1
Named Pipes Provider: Could not open a connection to SQL Server [53].
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

El servidor SQL no puede ser accedido o no existe. Intente usar: PING nombreservidor ó PING ipservidor. Si los pings tienen un timeout u otra falla, es posible que el nombre del servidor no está siendo bien resuelto por el DNS o hay algún problema de red o de ruteo a resolver. Obviamente, hay un problema de red si el ping falla cuando se especifica simplemente la dirección IP del servidor.

1.2. MENSAJE 2: No se pudo abrir conexión (estado 2)

[SQL Native Client]Named Pipes Provider: Could not open a connection to SQL Server [2].
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
-o-
HResult 0x2, Level 16, State 1
Named Pipes Provider: Could not open a connection to SQL Server [2].
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

Este error significa que el servicio SQL no está iniciado, o que el servidor no fue encontrado, o que no se puede hacer una conexión namedpipe usando el nombre especificado por el cliente. Para verificar esto, hacer lo siguiente:

1. Abrir una línea de comandos.

2. Revisar si la instancia SQL está presente, ejecutando:

sc query mssqlserver
-o-
sc query mssql$nombreinstancia


3. Abrir el SQL Server Configuration Manager y revisar el estado del servicio SQL. Si no ha iniciado, hacerlo. Si falla al iniciarlo, revisar el log de eventos de Windows o el log de errores de SQL para ver cuál ha sido el problema.

4. Si el servicio SQL está iniciado OK y están habilitados los protocolos Shared Memory/Named Pipe, intentar una conexión a la instancia local por omisión:

osql /Snp:\\.\pipe\sql\query
-o-
osql /Snp:\\.\pipe\mssql$nombreinstancia\sql\query


5. Si sigue el mismo error, asegurarse (una vez más) que el servidor está iniciado y escuchando en el namedpipe (si se ha habilitado NP). Para esto revisar el log de errores de SQL Server buscando las palabras:

Server named pipe provider is ready to accept connection on [ \\.\pipe\sql\query ] or [\\.\pipe\mssql$instancia\sql\query]

Observar que "sql\query" es el NP por omisión, por lo que se necesita saber exactamente en cuál NP está escuchando el servidor, si se cambió el valor por omisión.

6. Revisar el string de conexión. Ver si explícitamente se especificó en el string de conexión un NP y si coincide con el que el servidor tiene definido para escuchar. En el cliente usar el SQL Server Configuration Manager, click en las propiedades de Named Pipe del cliente, revisar si el NP coincide con el que usa el servidor SQL.

1.3. MENSAJE 3: No se pudo abrir conexión (estado 233)

[SQL Native Client]Named Pipes Provider: Could not open a connection to SQL Server [233].
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
-o-
HResult 0xE9, Level 16, State 1
Named Pipes Provider: Could not open a connection to SQL Server [233].
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

Para resolver esto, la primera manera consiste en reemplazar el nombre del servidor por el nombre de máquina, o ".", o "(local)", o "nombremaquina" y la conexión deberá funcionar si el servidor está escuhando a través de Shared Memory. La segunda manera consiste en habilitar Named Pipe en el servidor (usar el Configuration Manager y reiniciar el servicio).

1.4. MENSAJE 4: No hay proceso

[SQL Native Client]Named Pipes Provider: No process is on the other end of the pipe.
[SQL Native Client]Communication link failure
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
-o-
HResult 0xE9, Level 16, State 1
Named Pipes Provider: No process is on the other end of the pipe.
Error: Microsoft SQL Native Client : Communication link failure.
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections..

Diagnóstico:

Si el error se produce al hacer una conexión local, especificar en el string de conexión el nombre del servidor usando 127.0.0.1 o la dirección IP y usar Named Pipe. Para resolver el problema, o bien usar Named Pipe o bien usar el nombre de máquina en el string de conexión al identificar el servidor.

Si el error se produce al hacer una conexión remota a otro servidor, posiblemente el servidor no está escuchando en Named Pipe. Para resolver el problema, habilitar NP en el servidor remoto y reiniciar el servicio remoto.

1.5. MENSAJE 5: Protocolo no soportado

[SQL Native Client]SQL Network Interfaces: Server doesn't support requested protocol [xFFFFFFFF].
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
-o-
HResult 0xFFFFFFFF, Level 16, State 1
SQL Network Interfaces: Server doesn't support requested protocol [xFFFFFFFF].
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections..
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

Si el error se produce al hacer una conexión local, posiblemente se especificó en el string de conexión el prefijo de protocolo "np:" intentando conectar a una instancia con nombre y NP no está habilitado. Si el error se produce al hacer una conexión remota a otro servidor, el servidor remoto tiene NP no habilitado.

Para resolver el problema habilitar NP en la instancia (local o remota) a la que se desea conectar.
1.6. MENSAJE 6: Error al localizar el servidor

[SQL Native Client]SQL Network Interfaces: Error Locating Server/Instance Specified [0xFFFFFFFF].
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remot the connections.
-o-
HResult 0xFFFFFFFF, Level 16, State 1
SQL Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections..
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

Se intentó conectar a una instancia especificando explícitamente los prefijos de protocolo “tcp:” o “np:” en el string de conexión, pero el servicio SQLBrowser no está iniciado. Para resolver esto, iniciar el servicio SqlBrowser en el servidor al que se desea conectar.

Usar el comando de línea NET START, con permisos de Administrator:

net start sqlbrowser

También se puede usar el SQL Server Configuration Manager, seleccionar el servicio sqlBrowser, click en Propiedades, Advanced, Active. Verificar que el servicio está iniciado y también activo.

1.7. MENSAJE 7: Error 2 del proveedor Shared Memory

[SQL Native Client]Shared Memory Provider: Could not open a connection to SQLServer [2].
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
-o-
HResult 0x2, Level 16, State 1
Shared Memory Provider: Could not open a connection to SQL Server [2].
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections..
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

Posiblemente en el string de conexión se especificó "." "(local)" "localhost", se está usando protocolo Shared Memory y el servidor no está escuchando en Shared Memory. Para resolver este error habilitar el protocolo Shared Memory en el servidor y reniciar el servicio SQL.

1.8. MENSAJE 8: Error 87 del proveedor Shared Memory

[SQL Native Client]SQL Network Interfaces: Cannot open a Shared Memory connection to a remote SQL server [87].
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
-o-
HResult 0x57, Level 16, State 1
SQL Network Interfaces: Cannot open a Shared Memory connection to a remote SQL server [87].
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

La razón de este error es similar a la del Mensaje 6.

1.9. MENSAJE 9: Específico a TCP

[SQL Native Client]TCP Provider: No connection could be made because the target machine actively refused it.
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
-o-
HResult 0x274D, Level 16, State 1
TCP Provider: No connection could be made because the target machine actively refused it.
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

La razón es que el servidor SQL no está escuchando sobre TCP. Posiblemente el protocolo TCP no está habilitado para el servicio SQL.

1.10. MENSAJE 10: No completa el proceso de login

[SQL Native Client]Unable to complete login process due to delay in opening server connection.

Diagnóstico:

Revisar en el string de conexión si hay espacios en blanco después del nombre de instancia, por ejemplo:

osql /S"nombremaquina\nombreinstancia " /E

De ser eso, simplemente quitar los espacios en blanco: "nombremaquina\nombreinstancia".

Otra posibilidad es que se esté intentando una conexión remota indicando el nombre de un servidor y WINS está inhabilitado en la máquina cliente. Para resolver esto, habilitar en la máquina cliente la opción “File and Printer Sharing” y usar explícitamente el protocolo NP. Otra posibilidad es aumentar el timeout de conexión a unos 30 segundos.

1.11. MENSAJE 11: Relativo al firewall

HResult 0x274C, Level 16, State 1
An error has occurred while establishing a connection to the server. When connectiong to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.(provider:TCP Provider, errror:0-A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
-o-
Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections..
Error: Microsoft SQL Native Client : Login timeout expired.

Diagnóstico:

Este error ocurre cuando la conexión es bloqueada por algún firewall. Para resolver el problema hacer lo siguiente:

1. Habilitar el servicio SqlBrowser (ver Mensaje 4). Además agregar a sqlbrowser.exe como excepción en el firewall.

2. Agregar el puerto tcp (normalmente es el 1433) como excepción en el firewall. Por ejemplo: Name-1433:TCP, Value-1433:TCP:*:Enabled:Tcp 1433.

/* Los detalles acerca de cómo configurar un firewall escapan al alcance de este artículo. */


1.12. MENSAJE 12: No se puede generar contexto SSPI

Este mensaje de error suele darse al conectarse a SQL Server, con mecanismo de autenticación integrada a Windows y delegando la seguridad usando Kerberos. El mensaje en inglés, según el cliente usado es:

[SNAC] “[SQL Native Client]SQL Network Interfaces: The Local Security Authority cannot be contacted.[SQL Native Client]Cannot generate SSPI context”
[MDAC] “Cannot generate SSPI context”;
[.Net1.0/2.0]” Failed System.Data.SqlClient.SqlException: Cannot generate SSPI context”

Este error, su diagnóstico y formas de solucionarlo puede leerse en:

Cómo solucionar el mensaje de error "No se puede generar contexto SSPI"
http://support.microsoft.com/?id=811889

How to troubleshoot the "Cannot generate SSPI context" error message
http://support.microsoft.com/kb/811889/en-us





2 comentarios:

  1. Muchas gracias por todas las explicaciones que muestras. Me ha servido de gran ayuda.

    Un saludo

    ResponderEliminar
  2. Error al inicio de sesión del usuario "SA"
    El usuario no esta asociado do a una conexión de sql server de confianza

    ResponderEliminar

Nota: solo los miembros de este blog pueden publicar comentarios.