Exemplo n.º 1
0
        /// <summary>Connect method invoked by WinCs. </summary>
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="connectionParameterSets">List of credential sets</param>
        /// <param name="tftpDispatcher">Tftp Listener</param>
        /// <returns>Operation results.</returns>
        public ConnectionScriptResults Connect(
            long taskId,
            IDictionary <string, string>[] connectionParameterSets,
            ITftpDispatcher tftpDispatcher)
        {
            string taskIdString            = taskId.ToString();
            ConnectionScriptResults result = null;
            Stopwatch executionTimer       = Stopwatch.StartNew();

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Connection script SAPGuiConnectionScript.",
                                  taskIdString);

            if (connectionParameterSets == null)
            {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Null credential set passed to SAPGuiConnectionScript.",
                                      taskIdString);
                result = new ConnectionScriptResults(null, ResultCodes.RC_NULL_PARAMETER_SET, 0, -1);
            }
            else
            {
                try {
                    Lib.Logger.TraceEvent(TraceEventType.Information,
                                          0,
                                          "Task Id {0}: Executing SAPGuiConnectionScript with {1} credential sets.",
                                          taskIdString,
                                          connectionParameterSets.Length.ToString());

                    //
                    // Loop to process credential sets until a successful
                    // connection is made.
                    bool bConnectSuccess = false;
                    for (int i = 0; i < connectionParameterSets.Length && !bConnectSuccess; i++)
                    {
                        Dictionary <string, object> connectionDic = new Dictionary <string, object>();
                        foreach (KeyValuePair <string, string> kvp in connectionParameterSets[i])
                        {
                            connectionDic.Add(kvp.Key, kvp.Value);
                        }
                        string strSAPUserName       = connectionParameterSets[i][@"sapUserName"] as string;
                        string strSAPUserPassword   = connectionParameterSets[i][@"sapUserPassword"] as string;
                        string strApplicationServer = connectionParameterSets[i][@"address"] as string;
                        string strInstanceNumber    = connectionParameterSets[i][@"systemNumber"] as string;
                        if (strInstanceNumber.Length != 2)
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Invalid System number <{1}>.\nSystem Number should always be two digits even if the number is 00.",
                                                  taskIdString,
                                                  strInstanceNumber);
                            break;
                        }
                        string strConnectionString = @"/H/" + strApplicationServer.Trim() + @"/S/32" + strInstanceNumber.Trim();

                        if (!string.IsNullOrEmpty(strApplicationServer) && !string.IsNullOrEmpty(strSAPUserName) && !string.IsNullOrEmpty(strSAPUserPassword))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Processing credential set {1}:\nConnecting to remote machine using {2}, SAP user name {3}.",
                                                  taskIdString,
                                                  i.ToString(),
                                                  strConnectionString,
                                                  strSAPUserName);

                            using (SAPGuiConnection oConn = new SAPGuiConnection()) {
                                Stopwatch sw = Stopwatch.StartNew();
                                oConn.Connect(strConnectionString, strSAPUserName.Trim(), strSAPUserPassword.Trim());
                                sw.Stop();
                                bConnectSuccess = oConn.isConnected;
                                if (oConn.isConnected)
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                          0,
                                                          "Task Id {0}: Connection to {1} with user name {2} succeeded.  Elapsed time {3}.",
                                                          taskIdString,
                                                          strApplicationServer,
                                                          strSAPUserName,
                                                          sw.Elapsed.ToString());
                                    result = new ConnectionScriptResults(connectionDic, ResultCodes.RC_SUCCESS, 0, i);
                                    break;
                                }
                                else
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                          0,
                                                          "Task Id {0}: Connection to {1} failed.  Elapsed time {2}.\n{3}",
                                                          taskIdString,
                                                          strApplicationServer,
                                                          sw.Elapsed.ToString(),
                                                          oConn.logData.ToString());
                                }
                            }
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Skipping credential set {1} which contains null credential information.",
                                                  taskIdString,
                                                  i.ToString());
                        }
                    }
                    //
                    // Connect failed after all credentials attempted.
                    if (null == result)
                    {
                        result = new ConnectionScriptResults(null, ResultCodes.RC_HOST_CONNECT_FAILED,
                                                             0, connectionParameterSets.Length);
                    }
                } catch (Exception e) {
                    Lib.LogException(taskIdString,
                                     executionTimer,
                                     "Unhandled exception in SAPGuiConnectionScript",
                                     e);

                    //
                    // This is really an unanticipated fail safe.  We're
                    // going to report that *no* credentials were tried, which
                    // actually may not be true...
                    result = new ConnectionScriptResults(null, ResultCodes.RC_PROCESSING_EXCEPTION, 0, -1);
                }
            }

            Debug.Assert(null != result);
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Connection script SAPGuiConnectionScript.  Elapsed time {1}.  Result code {2}.",
                                  taskIdString,
                                  executionTimer.Elapsed.ToString(),
                                  result.ResultCode.ToString());
            return(result);
        }
        /// <summary>Connect method invoked by WinCs. </summary>
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="connectionParameterSets">List of credential sets</param>
        /// <param name="tftpDispatcher">Tftp Listener</param>
        /// <returns>Operation results.</returns>
        public ConnectionScriptResults Connect(
            long taskId,
            IDictionary <string, string>[] connectionParameterSets,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            Stopwatch executionTimer = Stopwatch.StartNew();

            m_taskId = taskId.ToString();
            ConnectionScriptResults result = null;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Connection script WindowsOracleRemoteExecConnectionScript.",
                                  m_taskId);

            if (null == connectionParameterSets)
            {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Null credential set passed to WindowsOracleRemoteExecConnectionScript.",
                                      m_taskId);
                result = new ConnectionScriptResults(null,
                                                     ResultCodes.RC_NULL_PARAMETER_SET,
                                                     0,
                                                     -1);
            }
            else
            {
                try {
                    ResultCodes resultCode = ResultCodes.RC_HOST_CONNECT_FAILED;
                    Lib.Logger.TraceEvent(TraceEventType.Information,
                                          0,
                                          "Task Id {0}: Executing WindowsOracleRemoteExecConnectionScript with {1} credential sets.",
                                          m_taskId,
                                          connectionParameterSets.Length.ToString());

                    //
                    // Loop to process credential sets until a successful
                    // WMI connection is made.
                    for (int i = 0;
                         connectionParameterSets.Length > i;
                         ++i)
                    {
                        ConnectionOptions co = new ConnectionOptions();
                        co.Impersonation  = ImpersonationLevel.Impersonate;
                        co.Authentication = AuthenticationLevel.Packet;
                        //co.Timeout = Lib.WmiConnectTimeout;

                        string userName = connectionParameterSets[i][@"userName"];
                        string password = connectionParameterSets[i][@"password"];

                        if (null != userName && null != password && !("." == userName && "." == password))
                        {
                            co.Username = userName;
                            co.Password = password;
                        }

                        Lib.Logger.TraceEvent(TraceEventType.Information,
                                              0,
                                              "Task Id {0}: Processing credential set {1}: user=\"{2}\".",
                                              m_taskId,
                                              i.ToString(),
                                              (null == co.Username) ? String.Empty : co.Username);

                        Stopwatch      sw = new Stopwatch();
                        ManagementPath mp = null;

                        try {
                            string server = connectionParameterSets[i][@"hostName"];

                            //
                            // Create a scope for the cimv2 namespace.
                            mp               = new ManagementPath();
                            mp.Server        = server;
                            mp.NamespacePath = ManagementScopeNames.CIMV;

                            ManagementScope cimvScope = new ManagementScope(mp, co);
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Attempting connection to namespace {1}.",
                                                  m_taskId,
                                                  mp.ToString());
                            sw.Start();
                            cimvScope.Connect();
                            sw.Stop();
                            Debug.Assert(cimvScope.IsConnected);
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.",
                                                  m_taskId,
                                                  mp.ToString(),
                                                  sw.Elapsed.ToString());

                            //
                            // Create a scope for the default namespace.
                            mp               = new ManagementPath();
                            mp.Server        = server;
                            mp.NamespacePath = ManagementScopeNames.DEFAULT;

                            ManagementScope defaultScope = new ManagementScope(mp, co);
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Attempting connection to namespace {1}.",
                                                  m_taskId,
                                                  mp.ToString());
                            sw.Reset();
                            defaultScope.Connect();
                            sw.Stop();
                            Debug.Assert(defaultScope.IsConnected);
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.",
                                                  m_taskId,
                                                  mp.ToString(),
                                                  sw.Elapsed.ToString());

                            Dictionary <string, object> connectionDic = new Dictionary <string, object>();

                            foreach (KeyValuePair <string, string> kvp in connectionParameterSets[i])
                            {
                                connectionDic.Add(kvp.Key, kvp.Value);
                            }

                            connectionDic[@"cimv2"]   = cimvScope;
                            connectionDic[@"default"] = defaultScope;

                            string oracleHome     = null;
                            string schemaName     = null;
                            string schemaPassword = null;
                            string tempDir        = null;

                            resultCode = ValidateScriptParameters(connectionDic,
                                                                  ref oracleHome,
                                                                  ref schemaName,
                                                                  ref schemaPassword);

                            if (ResultCodes.RC_SUCCESS == resultCode)
                            {
                                resultCode = ValidateTemporaryDirectory(cimvScope,
                                                                        connectionParameterSets[i],
                                                                        connectionDic,
                                                                        ref tempDir);
                            }

                            if (ResultCodes.RC_SUCCESS == resultCode)
                            {
                                string batchFile = BuildBatchFile(tempDir,
                                                                  oracleHome,
                                                                  schemaName,
                                                                  schemaPassword);
                                resultCode = ExecuteRemoteProcess(cimvScope,
                                                                  batchFile,
                                                                  schemaName,
                                                                  connectionDic,
                                                                  tftpPath,
                                                                  tftpPath_login,
                                                                  tftpPath_password,
                                                                  tftpDispatcher);
                            }

                            if (ResultCodes.RC_SUCCESS == resultCode)
                            {
                                result = new ConnectionScriptResults(connectionDic,
                                                                     ResultCodes.RC_SUCCESS,
                                                                     0,
                                                                     i);
                                break;
                            }
                        } catch (ManagementException me) {
                            if (ManagementStatus.AccessDenied == me.ErrorCode)
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Connect to {1} failed.  Elapsed time {2}.\nWMI Error Code {3}",
                                                      m_taskId,
                                                      mp.ToString(),
                                                      sw.Elapsed.ToString(),
                                                      me.ErrorCode.ToString());
                                resultCode = ResultCodes.RC_LOGIN_FAILED;
                            }
                            else
                            {
                                //
                                // If we received a management exception that is *not*
                                // access denied, then there is no point in attempting
                                // additional logins with different user names/passwords.
                                Lib.LogManagementException(m_taskId,
                                                           sw,
                                                           String.Format("Connect to {0} failed.", mp.ToString()),
                                                           me);
                                break;
                            }
                        } catch (UnauthorizedAccessException uae) {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Connect to {1} failed.  Elapsed time {2}.\nMessage: {3}.",
                                                  m_taskId,
                                                  mp.ToString(),
                                                  sw.Elapsed.ToString(),
                                                  uae.Message);
                            resultCode = ResultCodes.RC_LOGIN_FAILED;
                        } catch (COMException ce) {
                            if (0x800706BA == (UInt32)ce.ErrorCode)
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Connect to {1} failed.  Elapsed time {2}.\nCOM Exception {3}.\n" +
                                                      "WMI port (135) may be closed or DCOM may not be properly configured",
                                                      m_taskId,
                                                      mp.ToString(),
                                                      sw.Elapsed.ToString(),
                                                      ce.Message);
                            }
                            else
                            {
                                Lib.LogException(m_taskId,
                                                 sw,
                                                 String.Format("Connect to {0} failed", mp.ToString()),
                                                 ce);
                            }

                            break;
                        } catch (Exception ex) {
                            Lib.LogException(m_taskId,
                                             sw,
                                             String.Format("Connect to {0} failed", mp.ToString()),
                                             ex);
                            break;
                        }
                    }

                    //
                    // Connect failed after all credentials attempted.
                    if (null == result)
                    {
                        result = new ConnectionScriptResults(null,
                                                             resultCode,
                                                             0,
                                                             connectionParameterSets.Length);
                    }
                } catch (Exception e) {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsOracleRemoteExecConnectionScript.\n{1}",
                                          m_taskId,
                                          e.ToString());

                    //
                    // This is really an unanticipated fail safe.  We're
                    // going to report that *no* credentials were tried, which
                    // actually may not be true...
                    result = new ConnectionScriptResults(null,
                                                         ResultCodes.RC_PROCESSING_EXCEPTION,
                                                         0,
                                                         -1);
                }
            }

            Debug.Assert(null != result);
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Connection script WindowsOracleRemoteExecConnectionScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  executionTimer.Elapsed.ToString(),
                                  result.ResultCode.ToString());
            return(result);
        }
Exemplo n.º 3
0
        /// <summary>Connect method invoked by WinCs. </summary>
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="connectionParameterSets">List of credential sets</param>
        /// <param name="tftpDispatcher">Tftp Listener</param>
        /// <returns>Operation results.</returns>
        public ConnectionScriptResults Connect(
            long taskId,
            IDictionary <string, string>[] connectionParameterSets,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            Stopwatch executionTimer = Stopwatch.StartNew();

            m_taskId = taskId.ToString();
            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Connection script MSSQLDbConnectionScript.",
                                  m_taskId);
            ConnectionScriptResults result = null;

            if (null == connectionParameterSets)
            {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Null credential set passed to MSSQLDbConnectionScript",
                                      m_taskId);
                result = new ConnectionScriptResults(null,
                                                     ResultCodes.RC_NULL_PARAMETER_SET,
                                                     0,
                                                     -1);
            }
            else
            {
                try {
                    Lib.Logger.TraceEvent(TraceEventType.Information,
                                          0,
                                          "Task Id {0}: Executing MSSQLDbConnectionScript with {1} credential sets.",
                                          m_taskId,
                                          connectionParameterSets.Length.ToString());

                    //
                    // Loop to process credential sets until a successful
                    // connection is made.
                    for (int i = 0;
                         connectionParameterSets.Length > i;
                         ++i)
                    {
                        try {
                            Dictionary <string, object> connectionDic = new Dictionary <string, object>();
                            foreach (KeyValuePair <string, string> kvp in connectionParameterSets[i])
                            {
                                connectionDic.Add(kvp.Key, kvp.Value);
                            }
                            ResultCodes   resultCode = ResultCodes.RC_SUCCESS;
                            StringBuilder stdoutData = new StringBuilder();

                            //
                            // Using OLEDB Connection as default provider for SQL Server connection
                            // Reason is that SQL Server provider is tune for SQL Server 7.0+ only.
                            //  Our FP should maintain compatibility with earlier releases.
                            //
                            string strDbServerName = connectionParameterSets[i][@"hostName"];
                            connectionDic[@"hostName"] = strDbServerName;
                            string strDbInstanceName = connectionParameterSets[i][@"instanceName"];
                            if (!String.IsNullOrEmpty(strDbInstanceName))
                            {
                                if (strDbInstanceName.ToUpper() != @"MSSQLSERVER")
                                {
                                    strDbServerName = strDbServerName + @"\" + strDbInstanceName;
                                }
                            }
                            string strClusterIP      = connectionParameterSets[i][@"clusterIP"];
                            string strClusterName    = connectionParameterSets[i][@"clusterName"];
                            string strDbUserName     = connectionParameterSets[i][@"dbUserName"];
                            string strDbUserPassword = connectionParameterSets[i][@"dbUserPassword"];
                            if (strDbUserPassword == "NO_PASSWORD_SPECIFIED")
                            {
                                strDbUserPassword = "";
                            }
                            string strOsAuthentication = connectionParameterSets[i][@"OSAuthentication"];
                            if (strDbUserName == "NO_NAME_SPECIFIED")
                            {
                                strOsAuthentication = @"1";
                            }

                            ConnectionState enumConnState = ConnectionState.Closed;
                            DbConnection    dbConnection  = null;
                            if (strDbUserName != @"NO_NAME_SPECIFIED")
                            {
                                if (strClusterName != @"N/A")
                                {
                                    enumConnState = connectToDatabase
                                                        (out dbConnection, s_defaultSqlConnectionProvider,
                                                        strClusterName, strDbUserName, strDbUserPassword, s_InitialCatalog);
                                    if (enumConnState != ConnectionState.Open)
                                    {
                                        foreach (String line in strClusterIP.Split(' '))
                                        {
                                            enumConnState = connectToDatabase
                                                                (out dbConnection, s_defaultSqlConnectionProvider,
                                                                line, strDbUserName, strDbUserPassword, s_InitialCatalog);
                                            if (enumConnState == ConnectionState.Open)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    enumConnState = connectToDatabase
                                                        (out dbConnection, s_defaultSqlConnectionProvider,
                                                        strDbServerName, strDbUserName, strDbUserPassword, s_InitialCatalog);
                                }
                            }

                            if (resultCode == ResultCodes.RC_SUCCESS && enumConnState == ConnectionState.Open)
                            {
                                connectionDic[@"dbConnection"] = dbConnection;
                                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                      0,
                                                      "Task Id {0}: SQL connection creation using credential at index {1}.\n{2}",
                                                      m_taskId,
                                                      i.ToString(),
                                                      strDbUserName);
                                result = new ConnectionScriptResults(connectionDic,
                                                                     ResultCodes.RC_SUCCESS,
                                                                     0,
                                                                     i);
                                break;
                            }
                            else if (strOsAuthentication == @"1")
                            {
                                if (strClusterName != @"N/A")
                                {
                                    enumConnState = connectToDatabase
                                                        (out dbConnection, s_defaultSqlConnectionProvider,
                                                        strClusterName, strDbUserName, strDbUserPassword, s_InitialCatalog);
                                    if (enumConnState != ConnectionState.Open)
                                    {
                                        foreach (String line in strClusterIP.Split(' '))
                                        {
                                            enumConnState = connectToDatabase
                                                                (out dbConnection, s_defaultSqlConnectionProvider,
                                                                line, strDbUserName, strDbUserPassword, s_InitialCatalog);
                                            if (enumConnState == ConnectionState.Open)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    enumConnState = connectToDatabase
                                                        (out dbConnection, s_defaultSqlConnectionProvider, strDbServerName, s_InitialCatalog);
                                }
                                if (resultCode == ResultCodes.RC_SUCCESS && enumConnState == ConnectionState.Open)
                                {
                                    connectionDic[@"dbConnection"] = dbConnection;
                                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                          0,
                                                          "Task Id {0}: SQL connection creation using pass-thru security .\n",
                                                          m_taskId);

                                    result = new ConnectionScriptResults(connectionDic,
                                                                         ResultCodes.RC_SUCCESS,
                                                                         0,
                                                                         i);
                                    break;
                                }
                            }
                        } catch (Exception ex) {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Attempting SQL connection using credential at index {1} resulted in an exception:\n{2}",
                                                  m_taskId,
                                                  i.ToString(),
                                                  ex.ToString());
                        }
                    }

                    //
                    // Connect failed after all credentials attempted.
                    if (null == result)
                    {
                        result = new ConnectionScriptResults(null,
                                                             ResultCodes.RC_HOST_CONNECT_FAILED,
                                                             0,
                                                             connectionParameterSets.Length);
                    }
                } catch (Exception e) {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in MSSQLDbConnectionScript.\n{1}",
                                          m_taskId,
                                          e.ToString());

                    //
                    // This is really an unanticipated fail safe.  We're
                    // going to report that *no* credentials were tried, which
                    // actually may not be true...
                    result = new ConnectionScriptResults(null,
                                                         ResultCodes.RC_LOGIN_FAILED,
                                                         0,
                                                         -1);
                }
            }

            Debug.Assert(null != result);
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Connection script MSSQLDbConnectionScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  executionTimer.Elapsed.ToString(),
                                  result.ResultCode.ToString());
            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Connect method invoked by WinCs.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="connectionParameterSets">List of credential sets to use for connecting to the
        ///     remote database server.</param>
        /// <param name="tftpDispatcher">TFTP transfer request listener for dispatching TFTP transfer
        ///     requests.</param>
        ///
        /// <returns>Operation results.</returns>
        public ConnectionScriptResults Connect(
            long taskId,
            IDictionary <string, string>[]   connectionParameterSets,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            Stopwatch executionTimer = Stopwatch.StartNew();
            string    taskIdString   = taskId.ToString();

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Connection script ConnWincsScript.",
                                  taskIdString);
            ConnectionScriptResults result = null;

            if (null == connectionParameterSets)
            {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Null credential set passed to ConnWincsScript",
                                      taskIdString);
                result = new ConnectionScriptResults(null,
                                                     ResultCodes.RC_NULL_PARAMETER_SET,
                                                     0,
                                                     -1);
            }
            else
            {
                try {
                    ResultCodes resultCode = ResultCodes.RC_HOST_CONNECT_FAILED;
                    Lib.Logger.TraceEvent(TraceEventType.Information,
                                          0,
                                          "Task Id {0}: Executing ConnWincsScript with {1} credential sets.",
                                          taskIdString,
                                          connectionParameterSets.Length.ToString());
                    //IDictionary<string, string>[] orderedConnectionParameterSets = this.reorderCredentials(connectionParameterSets);
                    List <int> orderedConnections = this.reorderCredentials(connectionParameterSets);
                    //
                    // Loop to process credential sets until a successful
                    // WMI connection is made.
                    for (int j = 0;
                         orderedConnections.Count > j;
                         ++j)
                    {
                        ConnectionOptions co = new ConnectionOptions();
                        co.Impersonation    = ImpersonationLevel.Impersonate;
                        co.Authentication   = AuthenticationLevel.Packet;
                        co.Timeout          = Lib.WmiConnectTimeout;
                        co.EnablePrivileges = true;  // @todo configuration

                        int    i        = orderedConnections[j];
                        string userName = connectionParameterSets[i][@"userName"];
                        string password = connectionParameterSets[i][@"password"];

                        if (null != userName && null != password && !("." == userName && "." == password))
                        {
                            co.Username = userName;
                            co.Password = password;
                        }

                        Lib.Logger.TraceEvent(TraceEventType.Information,
                                              0,
                                              "Task Id {0}: Processing credential set {1}: user=\"{2}\".",
                                              taskIdString,
                                              i.ToString(),
                                              userName);

                        if (string.IsNullOrEmpty(userName))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Unexpected Error: Receiving null username at Credential set {1}: user=\"{2}\".",
                                                  taskIdString,
                                                  i.ToString(),
                                                  userName);
                            continue;
                        }

                        Stopwatch      sw = new Stopwatch();
                        ManagementPath mp = null;

                        try {
                            string server = connectionParameterSets[i][@"address"];
                            string domain = string.Empty;
                            if (connectionParameterSets[i].ContainsKey(@"osWkgrpDomain"))
                            {
                                domain = connectionParameterSets[i][@"osWkgrpDomain"];
                                if (domain == @"__BDNA_DEFAULT__")
                                {
                                    domain = "";
                                }
                            }
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Attempting connection to computer in domain {1}.",
                                                  taskIdString,
                                                  domain);

                            //
                            // Create a scope for the cimv2 namespace.
                            mp               = new ManagementPath();
                            mp.Server        = server;
                            mp.NamespacePath = ManagementScopeNames.CIMV;

                            ManagementScope cimvScope = new ManagementScope(mp, co);
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Attempting connection to namespace {1}.",
                                                  taskIdString,
                                                  mp.ToString());
                            sw.Start();
                            cimvScope.Connect();
                            sw.Stop();
                            Debug.Assert(cimvScope.IsConnected);
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.",
                                                  taskIdString,
                                                  mp.ToString(),
                                                  sw.Elapsed.ToString());

                            //
                            // Create a scope for the default namespace.
                            mp               = new ManagementPath();
                            mp.Server        = server;
                            mp.NamespacePath = ManagementScopeNames.DEFAULT;

                            ManagementScope defaultScope = new ManagementScope(mp, co);
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Attempting connection to namespace {1}.",
                                                  taskIdString,
                                                  mp.ToString());
                            sw.Reset();
                            defaultScope.Connect();
                            sw.Stop();
                            Debug.Assert(defaultScope.IsConnected);
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.",
                                                  taskIdString,
                                                  mp.ToString(),
                                                  sw.Elapsed.ToString());

                            ManagementScope tsScope = null;
                            try {
                                //
                                // Create a scope for the TerminalServices namespace.
                                mp                = new ManagementPath();
                                mp.Server         = server;
                                mp.NamespacePath  = @"root\CIMV2\TerminalServices";
                                co.Authentication = AuthenticationLevel.PacketPrivacy;
                                tsScope           = new ManagementScope(mp, co);
                                Lib.Logger.TraceEvent(TraceEventType.Information,
                                                      0,
                                                      "Task Id {0}: Attempting connection to namespace {1}.",
                                                      taskIdString,
                                                      mp.ToString());
                                sw.Reset();
                                tsScope.Connect();
                                sw.Stop();
                                Lib.Logger.TraceEvent(TraceEventType.Information,
                                                      0,
                                                      "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.",
                                                      taskIdString,
                                                      mp.ToString(),
                                                      sw.Elapsed.ToString());
                            } catch (Exception ex) {
                                tsScope = null;
                                Lib.LogException(taskIdString,
                                                 sw,
                                                 String.Format("Connect to {0} failed", mp.ToString()),
                                                 ex);
                            }


                            ManagementScope virtualizScope = null;
                            try   {
                                //
                                // Create a scope for the virtualization namespace.
                                mp                = new ManagementPath();
                                mp.Server         = server;
                                mp.NamespacePath  = @"root\virtualization";
                                co.Authentication = AuthenticationLevel.PacketPrivacy;
                                virtualizScope    = new ManagementScope(mp, co);
                                Lib.Logger.TraceEvent(TraceEventType.Information,
                                                      0,
                                                      "Task Id {0}: Attempting connection to namespace {1}.",
                                                      taskIdString,
                                                      mp.ToString());
                                sw.Reset();
                                virtualizScope.Connect();
                                sw.Stop();
                                Lib.Logger.TraceEvent(TraceEventType.Information,
                                                      0,
                                                      "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.",
                                                      taskIdString,
                                                      mp.ToString(),
                                                      sw.Elapsed.ToString());
                            }   catch (Exception ex)   {
                                virtualizScope = null;
                                Lib.LogException(taskIdString,
                                                 sw,
                                                 String.Format("Connect to {0} failed", mp.ToString()),
                                                 ex);
                            }

                            ManagementScope virtualizv2Scope = null;
                            try   {
                                //
                                // Create a scope for the virtualization\v2 namespace.
                                mp                = new ManagementPath();
                                mp.Server         = server;
                                mp.NamespacePath  = @"root\virtualization\v2";
                                co.Authentication = AuthenticationLevel.PacketPrivacy;
                                virtualizv2Scope  = new ManagementScope(mp, co);
                                Lib.Logger.TraceEvent(TraceEventType.Information,
                                                      0,
                                                      "Task Id {0}: Attempting connection to namespace {1}.",
                                                      taskIdString,
                                                      mp.ToString());
                                sw.Reset();
                                virtualizv2Scope.Connect();
                                sw.Stop();
                                Lib.Logger.TraceEvent(TraceEventType.Information,
                                                      0,
                                                      "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.",
                                                      taskIdString,
                                                      mp.ToString(),
                                                      sw.Elapsed.ToString());
                            }   catch (Exception ex)   {
                                virtualizv2Scope = null;
                                Lib.LogException(taskIdString,
                                                 sw,
                                                 String.Format("Connect to {0} failed", mp.ToString()),
                                                 ex);
                            }

                            //
                            // We have everything we need.  Create a dictionary
                            // to return as the "connection" and get out of
                            // loop.
                            Dictionary <string, object> connectionDic = new Dictionary <string, object>();
                            foreach (KeyValuePair <string, string> kvp in connectionParameterSets[i])
                            {
                                connectionDic.Add(kvp.Key, kvp.Value);
                            }
                            connectionDic[@"cimv2"]   = cimvScope;
                            connectionDic[@"default"] = defaultScope;
                            if (tsScope != null)
                            {
                                connectionDic[@"TerminalServices"] = tsScope;
                            }
                            if (virtualizScope != null)
                            {
                                connectionDic[@"virtualization"] = virtualizScope;
                            }
                            if (virtualizv2Scope != null)
                            {
                                connectionDic[@"v2"] = virtualizv2Scope;
                            }
                            result = new ConnectionScriptResults(connectionDic,
                                                                 ResultCodes.RC_SUCCESS,
                                                                 0,
                                                                 i);
                            break;
                        } catch (ManagementException me) {
                            if (ManagementStatus.AccessDenied == me.ErrorCode)
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Connect to {1} failed.  Elapsed time {2}.\nWMI Error Code {3}",
                                                      taskIdString,
                                                      mp.ToString(),
                                                      sw.Elapsed.ToString(),
                                                      me.ErrorCode.ToString());
                                resultCode = ResultCodes.RC_LOGIN_FAILED;
                            }
                            else
                            {
                                Lib.LogManagementException(taskIdString,
                                                           sw,
                                                           String.Format("Connect to {0} failed.", mp.ToString()),
                                                           me);
                                //break ;
                            }
                        } catch (UnauthorizedAccessException uae) {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Connect to {1} failed.  Elapsed time {2}.\nMessage: {3}.",
                                                  taskIdString,
                                                  mp.ToString(),
                                                  sw.Elapsed.ToString(),
                                                  uae.Message);
                            resultCode = ResultCodes.RC_LOGIN_FAILED;
                        } catch (COMException ce) {
                            if (0x800706BA == (UInt32)ce.ErrorCode)
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Connect to {1} failed.  Elapsed time {2}.\nCOM Exception {3}.\n" +
                                                      "WMI port (135) may be closed or DCOM may not be properly configured",
                                                      taskIdString,
                                                      mp.ToString(),
                                                      sw.Elapsed.ToString(),
                                                      ce.Message);
                            }
                            else if (0x80040154 == (UInt32)ce.ErrorCode)
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Connect to {1} failed.  Elapsed time {2}.\nCOM Exception {3}.\n" +
                                                      "WMI Management Class not registered. WMI provider not found on the remote machine.",
                                                      taskIdString,
                                                      mp.ToString(),
                                                      sw.Elapsed.ToString(),
                                                      ce.Message);
                            }
                            else
                            {
                                Lib.LogException(taskIdString,
                                                 sw,
                                                 String.Format("Connect to {0} failed", mp.ToString()),
                                                 ce);
                            }
                        } catch (Exception ex) {
                            Lib.LogException(taskIdString,
                                             sw,
                                             String.Format("Connect to {0} failed", mp.ToString()),
                                             ex);
                        }
                    }

                    //
                    // Connect failed after all credentials attempted.
                    if (null == result)
                    {
                        result = new ConnectionScriptResults(null,
                                                             resultCode,
                                                             0,
                                                             connectionParameterSets.Length);
                    }
                } catch (Exception e) {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in ConnWincsScript.\n{1}",
                                          taskIdString,
                                          e.ToString());

                    //
                    // This is really an unanticipated fail safe.  We're
                    // going to report that *no* credentials were tried, which
                    // actually may not be true...
                    result = new ConnectionScriptResults(null,
                                                         ResultCodes.RC_PROCESSING_EXCEPTION,
                                                         0,
                                                         -1);
                }
            }

            Debug.Assert(null != result);
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Connection script ConnWincsScript.  Elapsed time {1}.  Result code {2}.",
                                  taskIdString,
                                  executionTimer.Elapsed.ToString(),
                                  result.ResultCode.ToString());
            return(result);
        }
Exemplo n.º 5
0
        /// <summary>Connect method invoked by WinCs. </summary>
        /// <param name="taskId">Database assigned task id.</param>
        /// <param name="connectionParameterSets">List of credential sets</param>
        /// <param name="tftpDispatcher">Tftp Listener</param>
        /// <returns>Operation results.</returns>
        public ConnectionScriptResults Connect(
            long taskId,
            IDictionary <string, string>[] connectionParameterSets,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            Stopwatch executionTimer = Stopwatch.StartNew();

            m_taskId = taskId.ToString();
            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Connection script BBMSSQLDbConnectionScript.",
                                  m_taskId);
            ConnectionScriptResults result = null;

            if (null == connectionParameterSets)
            {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Null credential set passed to BBMSSQLDbConnectionScript",
                                      m_taskId);
                result = new ConnectionScriptResults(null,
                                                     ResultCodes.RC_NULL_PARAMETER_SET,
                                                     0,
                                                     -1);
            }
            else
            {
                try {
                    Lib.Logger.TraceEvent(TraceEventType.Information,
                                          0,
                                          "Task Id {0}: Executing MSSQLDbConnectionScript with {1} credential sets.",
                                          m_taskId,
                                          connectionParameterSets.Length.ToString());

                    //
                    // Loop to process credential sets until a successful
                    // connection is made.
                    for (int i = 0;
                         connectionParameterSets.Length > i;
                         ++i)
                    {
                        try {
                            Dictionary <string, object> connectionDic = new Dictionary <string, object>();
                            foreach (KeyValuePair <string, string> kvp in connectionParameterSets[i])
                            {
                                connectionDic.Add(kvp.Key, kvp.Value);
                            }
                            ResultCodes   resultCode = ResultCodes.RC_SUCCESS;
                            StringBuilder stdoutData = new StringBuilder();
                            string        strDbServerName = string.Empty, strDbName = string.Empty, strDomainName = string.Empty, strDbSvrDomainName = string.Empty, strDbServerNameUIDomainName = string.Empty, strDbServerNameHostDomainName = string.Empty;
                            //
                            // Using OLEDB Connection as default provider for SQL Server connection
                            // Reason is that SQL Server provider is tune for SQL Server 7.0+ only.
                            //  Our FP should maintain compatibility with earlier releases.
                            //
                            if (!connectionDic.ContainsKey("databaseServer"))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Missing script parameter \"databaseServer\".",
                                                      m_taskId);
                                resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                            }
                            else
                            {
                                strDbServerName            = connectionDic["databaseServer"].ToString().Trim();
                                connectionDic[@"hostName"] = strDbServerName;
                            }
                            strDomainName = connectionParameterSets[i][@"domainName"];

                            if (!string.IsNullOrEmpty(strDbServerName) && !string.IsNullOrEmpty(strDomainName) && !strDomainName.Equals("__NO_DOMAIN_PROVIDED__"))
                            {
                                if (!strDbServerName.Contains(@".") && !strDbServerName.Contains(@"\"))
                                {
                                    strDbServerNameUIDomainName = strDbServerName + @"." + strDomainName;
                                }
                                else if (!strDbServerName.Contains(@".") && strDbServerName.Contains(@"\"))
                                {
                                    strDbServerNameUIDomainName = strDbServerName.Replace("\\", "." + strDomainName + "\\");
                                }
                            }
                            if (!connectionDic.ContainsKey("dbSvrDomainName"))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Missing script parameter \"dbSvrDomainName\".",
                                                      m_taskId);
                                resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                            }
                            else
                            {
                                strDbSvrDomainName = connectionDic["dbSvrDomainName"].ToString().Trim();
                                if (!string.IsNullOrEmpty(strDbServerName) && !string.IsNullOrEmpty(strDbSvrDomainName) && !strDbSvrDomainName.Equals("__NO_DEFAULT_DOMAIN__"))
                                {
                                    if (!strDbServerName.Contains(@".") && !strDbServerName.Contains(@"\"))
                                    {
                                        strDbServerNameHostDomainName = strDbServerName + @"." + strDbSvrDomainName;
                                    }
                                    else if (!strDbServerName.Contains(@".") && strDbServerName.Contains(@"\"))
                                    {
                                        strDbServerNameHostDomainName = strDbServerName.Replace("\\", "." + strDbSvrDomainName + "\\");
                                    }
                                }
                            }

                            if (!connectionDic.ContainsKey("databaseName"))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Missing script parameter \"databaseName\".",
                                                      m_taskId);
                                resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                            }
                            else
                            {
                                strDbName = connectionDic["databaseName"].ToString().Trim();
                            }


                            //connectionDic[@"hostName"] = strDbServerName;
                            //string strDbInstanceName = connectionParameterSets[i][@"bbMSSQLInstanceName"];
                            //if (!String.IsNullOrEmpty(strDbInstanceName) &&
                            //    !strDbInstanceName.Equals(@"MSSQLSERVER(DEFAULT)", StringComparison.CurrentCultureIgnoreCase) &&
                            //    !strDbInstanceName.Equals(@"_")) {
                            //    strDbServerName = strDbServerName + @"\" + strDbInstanceName;
                            //}
                            string strDbUserName     = connectionParameterSets[i][@"dbUserName"];
                            string strDbUserPassword = connectionParameterSets[i][@"dbUserPassword"];
                            if (strDbUserPassword == "NO_PASSWORD_SPECIFIED")
                            {
                                strDbUserPassword = "";
                            }
                            string strOsAuthentication = connectionParameterSets[i][@"OSAuthentication"];
                            if (strDbUserName == "NO_NAME_SPECIFIED")
                            {
                                strOsAuthentication = @"1";
                            }

                            ConnectionState enumConnState = ConnectionState.Closed;
                            DbConnection    dbConnection  = null;
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Connecting to DB Server: {1}, DB Name: {2} .\n",
                                                  m_taskId,
                                                  strDbServerName,
                                                  strDbName);

                            if (strDbUserName != @"NO_NAME_SPECIFIED")
                            {
                                if (enumConnState == ConnectionState.Closed)
                                {
                                    enumConnState = connectToDatabase
                                                        (out dbConnection, s_defaultSqlConnectionProvider,
                                                        strDbServerName, strDbUserName, strDbUserPassword, strDbName);
                                    if (enumConnState == ConnectionState.Open)
                                    {
                                        connectionDic[@"databaseServer"] = strDbServerName;
                                    }
                                }
                                if (enumConnState == ConnectionState.Closed && !string.IsNullOrEmpty(strDbServerNameUIDomainName))
                                {
                                    strDbServerName = strDbServerNameUIDomainName;
                                    enumConnState   = connectToDatabase
                                                          (out dbConnection, s_defaultSqlConnectionProvider,
                                                          strDbServerName, strDbUserName, strDbUserPassword, strDbName);
                                    if (enumConnState == ConnectionState.Open)
                                    {
                                        connectionDic[@"databaseServer"] = strDbServerName;
                                    }
                                }
                                if (enumConnState == ConnectionState.Closed && !string.IsNullOrEmpty(strDbServerNameHostDomainName))
                                {
                                    strDbServerName = strDbServerNameHostDomainName;
                                    enumConnState   = connectToDatabase
                                                          (out dbConnection, s_defaultSqlConnectionProvider,
                                                          strDbServerName, strDbUserName, strDbUserPassword, strDbName);
                                    if (enumConnState == ConnectionState.Open)
                                    {
                                        connectionDic[@"databaseServer"] = strDbServerName;
                                    }
                                }
                            }
                            else
                            {
                                if (enumConnState == ConnectionState.Closed)
                                {
                                    enumConnState = connectToDatabase
                                                        (out dbConnection, s_defaultSqlConnectionProvider, strDbServerName, strDbName);
                                    if (enumConnState == ConnectionState.Open)
                                    {
                                        connectionDic[@"databaseServer"] = strDbServerName;
                                    }
                                }
                                if (enumConnState == ConnectionState.Closed && !string.IsNullOrEmpty(strDbServerNameUIDomainName))
                                {
                                    strDbServerName = strDbServerNameUIDomainName;
                                    enumConnState   = connectToDatabase
                                                          (out dbConnection, s_defaultSqlConnectionProvider, strDbServerName, strDbName);
                                    if (enumConnState == ConnectionState.Open)
                                    {
                                        connectionDic[@"databaseServer"] = strDbServerName;
                                    }
                                }
                                if (enumConnState == ConnectionState.Closed && !string.IsNullOrEmpty(strDbServerNameHostDomainName))
                                {
                                    strDbServerName = strDbServerNameHostDomainName;
                                    enumConnState   = connectToDatabase
                                                          (out dbConnection, s_defaultSqlConnectionProvider, strDbServerName, strDbName);
                                    if (enumConnState == ConnectionState.Open)
                                    {
                                        connectionDic[@"databaseServer"] = strDbServerName;
                                    }
                                }
                            }
                            if (resultCode == ResultCodes.RC_SUCCESS && enumConnState == ConnectionState.Open)
                            {
                                connectionDic[@"dbConnection"] = dbConnection;
                                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                      0,
                                                      "Task Id {0}: SQL connection creation using credential at index {1}.\n{2}",
                                                      m_taskId,
                                                      i.ToString(),
                                                      strDbUserName);
                                result = new ConnectionScriptResults(connectionDic,
                                                                     ResultCodes.RC_SUCCESS,
                                                                     0,
                                                                     i);
                                break;
                            }
                            else if (strOsAuthentication == @"1")
                            {
                                if (enumConnState == ConnectionState.Closed)
                                {
                                    if (connectionDic.ContainsKey("databaseServer"))
                                    {
                                        strDbServerName = connectionDic["databaseServer"].ToString().Trim();
                                        enumConnState   = connectToDatabase
                                                              (out dbConnection, s_defaultSqlConnectionProvider, strDbServerName, s_InitialCatalog);
                                        if (enumConnState == ConnectionState.Open)
                                        {
                                            connectionDic[@"databaseServer"] = strDbServerName;
                                        }
                                    }
                                }
                                if (enumConnState == ConnectionState.Closed && !string.IsNullOrEmpty(strDbServerNameUIDomainName))
                                {
                                    strDbServerName = strDbServerNameUIDomainName;
                                    enumConnState   = connectToDatabase
                                                          (out dbConnection, s_defaultSqlConnectionProvider, strDbServerName, s_InitialCatalog);
                                    if (enumConnState == ConnectionState.Open)
                                    {
                                        connectionDic[@"databaseServer"] = strDbServerName;
                                    }
                                }
                                if (enumConnState == ConnectionState.Closed && !string.IsNullOrEmpty(strDbServerNameHostDomainName))
                                {
                                    strDbServerName = strDbServerNameHostDomainName;
                                    enumConnState   = connectToDatabase
                                                          (out dbConnection, s_defaultSqlConnectionProvider, strDbServerName, s_InitialCatalog);
                                    if (enumConnState == ConnectionState.Open)
                                    {
                                        connectionDic[@"databaseServer"] = strDbServerName;
                                    }
                                }

                                if (resultCode == ResultCodes.RC_SUCCESS && enumConnState == ConnectionState.Open)
                                {
                                    connectionDic[@"dbConnection"] = dbConnection;
                                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                          0,
                                                          "Task Id {0}: SQL connection creation using pass-thru security .\n",
                                                          m_taskId);

                                    result = new ConnectionScriptResults(connectionDic,
                                                                         ResultCodes.RC_SUCCESS,
                                                                         0,
                                                                         i);
                                    break;
                                }
                            }
                        } catch (Exception ex) {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Attempting SQL connection using credential at index {1} resulted in an exception:\n{2}",
                                                  m_taskId,
                                                  i.ToString(),
                                                  ex.ToString());
                        }
                    }

                    //
                    // Connect failed after all credentials attempted.
                    if (null == result)
                    {
                        result = new ConnectionScriptResults(null,
                                                             ResultCodes.RC_HOST_CONNECT_FAILED,
                                                             0,
                                                             connectionParameterSets.Length);
                    }
                } catch (Exception e) {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          " Task Id {0}: Unhandled exception in MSSQLDbConnectionScript.\n{1}",
                                          m_taskId,
                                          e.ToString());

                    //
                    // This is really an unanticipated fail safe.  We're
                    // going to report that *no* credentials were tried, which
                    // actually may not be true...
                    result = new ConnectionScriptResults(null,
                                                         ResultCodes.RC_PROCESSING_EXCEPTION,
                                                         0,
                                                         -1);
                }
            }

            Debug.Assert(null != result);
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Connection script MSSQLDbConnectionScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  executionTimer.Elapsed.ToString(),
                                  result.ResultCode.ToString());
            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Connect method to connect to ESX Web Services.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="connectionParameterSets">List of credential sets to use for connecting to the
        ///     remote database server.</param>
        /// <param name="tftpDispatcher">TFTP transfer request listener for dispatching TFTP transfer
        ///     requests.</param>
        ///
        /// <returns>Operation results.</returns>
        public ConnectionScriptResults Connect(
            long taskId,
            IDictionary <string, string>[] connectionParameterSets,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            Stopwatch executionTimer = Stopwatch.StartNew();
            string    taskIdString   = taskId.ToString();

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Connection script ESXWebServicesConnectionScript.",
                                  taskIdString);
            ConnectionScriptResults result = null;

            if (null == connectionParameterSets)
            {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Null credential set passed to ESXWebServicesConnectionScript",
                                      taskIdString);
                result = new ConnectionScriptResults(null,
                                                     ResultCodes.RC_NULL_PARAMETER_SET,
                                                     0,
                                                     -1);
            }
            else
            {
                try {
                    ResultCodes resultCode = ResultCodes.RC_HOST_CONNECT_FAILED;
                    Lib.Logger.TraceEvent(TraceEventType.Information,
                                          0,
                                          "Task Id {0}: Executing ESXWebServicesConnectionScript with {1} credential sets.",
                                          taskIdString,
                                          connectionParameterSets.Length.ToString());

                    //
                    // Loop to process credential sets until a successful
                    // connection is made.
                    for (int i = 0;
                         connectionParameterSets.Length > i;
                         ++i)
                    {
                        Dictionary <string, object> connectionDic = new Dictionary <string, object>();
                        foreach (KeyValuePair <string, string> kvp in connectionParameterSets[i])
                        {
                            connectionDic.Add(kvp.Key, kvp.Value);
                        }

                        string userName = connectionParameterSets[i][@"userName"];
                        string password = connectionParameterSets[i][@"password"];

                        String protocol = null;
                        String port     = null;
                        String hostIP   = null;
                        String url      = null;

                        protocol = connectionParameterSets[i][@"protocol"];
                        port     = connectionParameterSets[i][@"port"];
                        hostIP   = connectionParameterSets[i][@"address"] as string;

                        if (hostIP != null)
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: hostIP is \"{1}\".",
                                                  taskIdString,
                                                  hostIP);
                        }
                        else
                        {
                            resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Missing parameter - server address/name.",
                                                  taskIdString);
                        }

                        url = protocol + @"://" + hostIP + @":" + port + @"/sdk";

                        Lib.Logger.TraceEvent(TraceEventType.Information,
                                              0,
                                              "Task Id {0}: Processing credential set {1}: user=\"{2}\" for esx web service url={3}.",
                                              taskIdString,
                                              i.ToString(),
                                              userName,
                                              url);

                        Stopwatch sw = new Stopwatch();

                        try {
                            // Manage certificates:
                            System.Net.ServicePointManager.CertificatePolicy = new CertPolicy();

                            vim_svc_ref      = new ManagedObjectReference();
                            vim_svc_ref.type = "ServiceInstance";

                            // could be ServiceInstance for "HostAgent" and "VPX" for VPXd
                            vim_svc_ref.Value = "ServiceInstance";

                            // connect to esx web service:
                            // if vim_svc not null then disconnect
                            if (vim_svc != null)
                            {
                                Disconnect();
                            }


                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Instantiate VimService object.  Elapsed time {1} ms.",
                                                  taskIdString,
                                                  executionTimer.ElapsedMilliseconds);

                            vim_svc = new VimService();

                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Instantiated VimService object.  Elapsed time {1} ms.",
                                                  taskIdString,
                                                  executionTimer.ElapsedMilliseconds);

                            vim_svc.Url             = url;
                            vim_svc.CookieContainer = new System.Net.CookieContainer();

                            vim_svc_content = vim_svc.RetrieveServiceContent(vim_svc_ref);

                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: RetrievedServiceContent.  Elapsed time {1} ms.",
                                                  taskIdString,
                                                  executionTimer.ElapsedMilliseconds);

                            UserSession userSessionObj = null;
                            if (vim_svc_content.sessionManager != null)
                            {
                                sw.Start();
                                userSessionObj = vim_svc.Login(vim_svc_content.sessionManager, userName, password, null);
                                sw.Stop();

                                if (userSessionObj != null)
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                          0,
                                                          "Task Id {0}: Connection to {1} with user name {2} succeeded.  Elapsed time {3}.",
                                                          taskIdString,
                                                          url,
                                                          userName,
                                                          sw.Elapsed.ToString());

                                    connectionDic.Add("VimServiceObj", vim_svc);
                                    connectionDic.Add("VimServiceContentObj", vim_svc_content);
                                    connectionDic.Add("userSessionObj", userSessionObj);
                                    connectionDic.Add("WebServiceUrl", url);

                                    result = new ConnectionScriptResults(connectionDic, ResultCodes.RC_SUCCESS, 0, i);

                                    break;
                                }
                                else
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                          0,
                                                          "Task Id {0}: Connection to {1} failed with user name {2}.  Elapsed time {3}.\n",
                                                          taskIdString,
                                                          url,
                                                          userName,
                                                          sw.Elapsed.ToString()
                                                          );
                                }
                            }
                        } catch (SoapException se) {
                            ///Console.WriteLine("DEBUG Caught SoapException - " + se.ToString() + "\n Msg = " + se.Message.ToString() + "Code = " + se.Code.ToString());

                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Caught SoapException in ESXWebServicesConnectionScript.  Elapsed time {1}.\n<Exception detail:  [se: {2}]\n[Message: {3}]\n[Code: {4}]\n[Detail XML(OuterXml): {5}] Exception detail end>",
                                                  taskIdString,
                                                  executionTimer,
                                                  se.ToString(),
                                                  se.Message.ToString(),
                                                  se.Code.ToString(),
                                                  se.Detail.OuterXml.ToString());

                            if (se.Message.Contains("Login failed") || se.Message.Contains("incorrect user name or password"))
                            {
                                resultCode = ResultCodes.RC_LOGIN_FAILED;
                            }
                            else if (se.Message.Contains("Unsupported namespace"))
                            {
                                resultCode = ResultCodes.RC_UNSUPPORTED_MESSAGE_TYPE;
                            }
                            else if (se.Message.Contains("Permission to perform this operation was denied"))
                            {
                                resultCode = ResultCodes.RC_LOGIN_FAILED;
                            }
                            else if (se.Code.ToString().Contains("ServerFaultCode"))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: SoapException (ServerFaultCode) in ESXWebServicesConnectionScript.  Elapsed time {1}.\n <More detail:  [InnerText: {2}]\n[InnerXml: {3}]  end>",
                                                      taskIdString,
                                                      executionTimer,
                                                      se.Detail.InnerText,
                                                      se.Detail.InnerXml);

                                resultCode = ResultCodes.RC_ESX_WEB_SERVICE_QUERY_FAILURE;
                            }
                            else
                            {
                                resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                            }
                        } catch (Exception ex) {
                            Lib.LogException(taskIdString,
                                             sw,
                                             String.Format("Connect to {0} failed", url),
                                             ex);
                            //break;
                        } finally {
                            if (vim_svc != null)
                            {
                                vim_svc.Dispose();
                                vim_svc         = null;
                                vim_svc_content = null;
                            }
                        }
                    }  // end of for loop

                    //
                    // Connect failed after all credentials attempted.
                    if (null == result)
                    {
                        result = new ConnectionScriptResults(null,
                                                             resultCode,
                                                             0,
                                                             connectionParameterSets.Length);
                    }
                } catch (Exception e) {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in ESXWebServicesConnectionScript.  Elapsed time {1}.\n Result code changed to RC_PROCESSING_EXECEPTION. <EXP  {2} EXP>",
                                          taskIdString,
                                          executionTimer,
                                          e.ToString());

                    //
                    // This is really an unanticipated fail safe.  We're
                    // going to report that *no* credentials were tried, which
                    // actually may not be true...
                    result = new ConnectionScriptResults(null, ResultCodes.RC_PROCESSING_EXCEPTION, 0, -1);
                }
            }

            Debug.Assert(null != result);
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Connection script ESXWebServicesConnectionScript.  Elapsed time {1}.  Result code {2}.",
                                  taskIdString,
                                  executionTimer.Elapsed.ToString(),
                                  result.ResultCode.ToString());
            return(result);
        }