/// <summary> /// Get Oracle Version /// </summary> /// <param name="OracleHome">Oracle Home</param> /// <param name="version">Version</param> /// <returns></returns> private ResultCodes GetOracleServerEdition(string OracleHome, out string edition) { ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to retrieve config file from OracleHome: {1}.", m_taskId, OracleHome); StringBuilder fileContent = new StringBuilder(); string contentXMLFilePath = string.Empty; edition = @""; if (OracleHome.EndsWith(@"\")) { contentXMLFilePath = OracleHome + @"inventory\ContentsXML\comps.xml"; } else { contentXMLFilePath = OracleHome + @"\inventory\ContentsXML\comps.xml"; } if (Lib.ValidateFile(m_taskId, contentXMLFilePath, m_cimvScope)) { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, contentXMLFilePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { // // Launch the remote process. // This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote file retrieval operation completed with result code {1}.", m_taskId, resultCode.ToString()); fileContent.Append(rp.Stdout); } // Parse config file content edition = parseContentXMLFile(fileContent.ToString()); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Oracle Server Config file: {1} does not exist.", m_taskId, contentXMLFilePath); // Some Oracle Administrator might have corrupted config file or registry settings. // In order not to confuse scan result with actual error, return RC_SUCCESS instead. resultCode = ResultCodes.RC_SUCCESS; } return(resultCode); }
private bool checkErrors(ResultCodes error, bool silent) { if (error != ResultCodes.Driver_Success) { if (!silent) { MessageBox.Show(error.ToString()); this.Close(); } return(false); } return(true); }
private ResultCodes DeleteFile(ManagementScope cimvScope, string fileName) { ResultCodes resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; using (IRemoteProcess rp = RemoteProcess.NewRemoteProcess(m_taskId, cimvScope, @"cmd /Q /C del """ + fileName + '"', null, StdioRedirection.STDOUT, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Deletion of file {1} completed with result code {2}.", m_taskId, fileName, resultCode.ToString()); } return(resultCode); }
/// <summary> /// Collect usage statistics from agent. /// </summary> /// <param name="cimvScope">WMI connection.</param> /// <returns>Operation result code.</returns> private ResultCodes GetUsageStatistics(ManagementScope cimvScope) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Attempting to get usage statistics", m_taskId); ResultCodes resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; if (String.IsNullOrEmpty(m_serviceDataPath)) { return(resultCode); } String resultPath = m_serviceDataPath + "result.cvs"; StringBuilder fileContent = new StringBuilder(); if (Lib.ValidateFile(m_taskId, resultPath, cimvScope)) { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(m_taskId, cimvScope, resultPath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { // Launch the remote process. // This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote file retrieval operation completed with result code {1}.", m_taskId, resultCode.ToString()); fileContent.Append(rp.Stdout); } string[] lines = fileContent.ToString().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); m_resultFileContents = String.Join(BdnaDelimiters.DELIMITER_TAG, lines); resultCode = ResultCodes.RC_SUCCESS; } return(resultCode); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WindowsWASNodeandCoreGroupScript.", m_taskId); try { // Check ManagementScope CIMV //ManagementScope cimvScope = null; if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WindowsWASNodeandCoreGroupScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } //Check Script attributes if (resultCode.Equals(ResultCodes.RC_SUCCESS)) { if (scriptParameters.ContainsKey("profilePath")) { m_profileHome = scriptParameters[@"profilePath"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter WAS Profile Path parameter.", m_taskId); } if (scriptParameters.ContainsKey("cellName")) { m_cell = scriptParameters[@"cellName"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter WAS Cell Name parameter.", m_taskId); } } if (resultCode == ResultCodes.RC_SUCCESS) { StringBuilder ngDir = new StringBuilder(); StringBuilder ngList = new StringBuilder(); ngDir.Append((string)m_profileHome).Append(@"\config\cells\").Append((string)m_cell).Append(@"\nodegroups"); StringCollection ngNames = findGroups(ngDir.ToString()); foreach (string ng in ngNames) { if (!String.IsNullOrEmpty(ng)) { if (ngList.Length > 0) { ngList.Append(BdnaDelimiters.DELIMITER_TAG); } ngList.Append(ng); } } if (ngList.Length > 0) { BuildDataRow(s_nodeGroup, ngList.ToString()); } // Process Cluster Info StringBuilder clstDir = new StringBuilder(); StringBuilder clstList = new StringBuilder(); clstDir.Append((string)m_profileHome).Append(@"\config\cells\").Append((string)m_cell).Append(@"\clusters"); StringCollection clstNames = findGroups(clstDir.ToString()); foreach (string clst in clstNames) { if (!String.IsNullOrEmpty(clst)) { if (clstList.Length > 0) { clstList.Append(BdnaDelimiters.DELIMITER_TAG); } clstList.Append(clst); } } if (clstList.Length > 0) { BuildDataRow(s_cluster, clstList.ToString()); BuildDataRow(s_isCluster, "True"); } else { BuildDataRow(s_isCluster, "False"); } // Process CoreGroup Info StringBuilder cgDir = new StringBuilder(); StringBuilder cgList = new StringBuilder(); cgDir.Append((string)m_profileHome).Append(@"\config\cells\").Append((string)m_cell).Append(@"\coregroups"); StringCollection cgNames = findGroups(cgDir.ToString()); foreach (string cg in cgNames) { if (!String.IsNullOrEmpty(cg)) { if (cgList.Length > 0) { cgList.Append(BdnaDelimiters.DELIMITER_TAG); } cgList.Append(cg); } } if (cgList.Length > 0) { BuildDataRow(s_coreGroup, cgList.ToString()); } } } catch (Exception ex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsWASNodeandCoreGroupScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsWASNodeandCoreGroupScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WindowsWASNodeandCoreGroupScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script DataEntryValidateExecFileScript.", m_taskId); try { // Check ManagementScope CIMV if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to DataEntryValidateExecFileScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed.", m_taskId); } } //Check DataEntry System Installation Path if (scriptParameters.ContainsKey("swDir")) { m_dataEntryPath = scriptParameters[@"swDir"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter DataEntry Installation Directory.", m_taskId); } // Check Remote Process Temp Directory if (!m_connection.ContainsKey(@"TemporaryDirectory")) { m_connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: User specified temp directory has been validated.", m_taskId); } } } if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to determine file existence {1}.", m_taskId, m_dataEntryPath); StringBuilder builderFile = new StringBuilder(); builderFile.Append((string)m_dataEntryPath).Append(@"builder.exe"); if (Lib.ValidateFile(m_taskId, builderFile.ToString(), m_cimvScope)) { this.BuildDataRow(@"builderInstalled", "True"); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: File: {1} does not exist.", m_taskId, m_dataEntryPath); this.BuildDataRow(@"builderInstalled", "False"); } StringBuilder stationFile = new StringBuilder(); stationFile.Append((string)m_dataEntryPath).Append(@"station.exe"); if (Lib.ValidateFile(m_taskId, stationFile.ToString(), m_cimvScope)) { this.BuildDataRow(@"stationInstalled", "True"); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: File: {1} does not exist.", m_taskId, m_dataEntryPath); this.BuildDataRow(@"stationInstalled", "False"); } } } catch (ManagementException me) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Insufficient privilege to access file property station.exe.\nMessage: {1}", m_taskId, me.Message); if (me.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, me.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_ACCESS_FILE_PROPERTY; } catch (COMException ce) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Not enough privilege to access run WMI query.\nMessage: {1}.", m_taskId, ce.Message); if (ce.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, ce.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_RUN_WMI_QUERY; } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in DataEntryValidateExecFileScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in DataEntryValidateExecFileScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script DataEntryValidateExecFileScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { string taskIdString = taskId.ToString(); StringBuilder dataRow = new StringBuilder(); StringBuilder resultBuffer = new StringBuilder(); IDictionary <string, string> resultDic = new Dictionary <string, string>(); Stopwatch executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; string strOracleHome = null; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WindowsOracleListenerNamesScript.", taskIdString); try { // Check ManagementScope CIMV ManagementScope cimvScope = null; if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WindowsOracleListenerNamesScript is null.", taskIdString); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", taskIdString); } else { cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed.", taskIdString); } } //Check OracleHome attributes if (!scriptParameters.ContainsKey("OracleHome")) { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing OracleHome parameter", taskIdString); } else { strOracleHome = scriptParameters["OracleHome"].Trim(); if (strOracleHome.EndsWith(@"\")) { strOracleHome = strOracleHome.Substring(0, strOracleHome.Length - 1); } } // Check Remote Process Temp Directory if (!connection.ContainsKey(@"TemporaryDirectory")) { connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(taskIdString, connection[@"TemporaryDirectory"].ToString(), cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", taskIdString, connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Temporary directory {1} has been validated.", taskIdString, connection[@"TemporaryDirectory"].ToString()); } } } if (resultCode == ResultCodes.RC_SUCCESS) { string strLISTENERORA = strOracleHome.Trim() + @"\NETWORK\ADMIN\listener.ora"; if (!Lib.ValidateFile(taskIdString, strLISTENERORA, cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Oracle Home does not contain a server installation. listener.ora is missing.\nSkipping the rest of the validation.", taskIdString); } else { string commandLine = @"cmd /q /e:off /C " + @"type " + strOracleHome.Trim() + @"\NETWORK\ADMIN\listener.ora"; StringBuilder stdoutData = new StringBuilder(); using (IRemoteProcess rp = RemoteProcess.NewRemoteProcess( taskIdString, // Task Id to log against. cimvScope, // assuming Remote process uses cimv2 management scope commandLine, // script supplied command line. null, // Optional working directory StdioRedirection.STDOUT, // Flags for what stdio files you want null, // Data to pass for stdin. connection, // Script parameters passed to all collection script by WinCs tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { //This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote process operation completed with result code {1}.", taskIdString, resultCode.ToString()); if (resultCode == ResultCodes.RC_SUCCESS) { stdoutData.Append(rp.Stdout.ToString()); if (rp.Stdout == null || rp.Stdout.Length <= 0) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: No data returned from remote process execution.\nResult code changed to RC_PROCESSING_EXCEPTION.", taskIdString); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Remote process execution failed. Result code {1}.\n{2}", taskIdString, resultCode.ToString(), rp.Stdout.ToString()); } } if (stdoutData != null && stdoutData.Length > 0) { StringBuilder sb = new StringBuilder(); string[] arrOutput = stdoutData.ToString().Split("\r\n".ToCharArray()); string strListener = null; bool matched = false; foreach (string line in arrOutput) { if (s_listenerName.IsMatch(line)) { if (!s_listenerNoName.IsMatch(line)) { Match m = s_listenerName.Match(line); strListener = m.Groups[1].Value; sb.AppendLine(strListener); resultDic[strListener] = strListener; } } } if (0 < sb.Length) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Listener matched:\n{1}", taskIdString, sb.ToString()); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: No Listener services matched.", taskIdString); } foreach (KeyValuePair <string, string> kvp in resultDic) { if (resultBuffer.Length > 0) { resultBuffer.Append(BdnaDelimiters.DELIMITER_TAG); } resultBuffer.Append(kvp.Value); } if (!attributes.ContainsKey("listenerNames")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Attribute \"listenerNames\" missing from attributeSet.", taskIdString); } else if (0 == resultBuffer.Length) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Script completed sucessfully with no data to return.", taskIdString); } else { dataRow.Append(elementId).Append(',') .Append(attributes["listenerNames"]).Append(',') .Append(scriptParameters["CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',') .Append("listenerNames").Append(',') .Append(BdnaDelimiters.BEGIN_TAG).Append(resultBuffer.ToString()).Append(BdnaDelimiters.END_TAG); } } } } } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsOracleListenerNamesScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", taskIdString, executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsOracleListenerNamesScript. Elapsed time {1}.\n{2}", taskIdString, executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WindowsOracleListenerNamesScript. Elapsed time {1}. Result code {2}.", taskIdString, executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> /// public CollectionScriptResults ExecuteTask (long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; try { Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script SAPClientInfoScript", m_taskId); if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to SAPClientInfoScript is null.", m_taskId); } else { //Check host attributes if (connection.ContainsKey(@"address")) { m_strApplicationServer = connection[@"address"] as String; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing SAP Application Server connection parameter.", m_taskId); } //Check InstanceNumber attributes if (connection.ContainsKey(@"systemNumber")) { m_strInstanceNumber = connection[@"systemNumber"] as String; if (m_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.", m_taskId, m_strInstanceNumber); resultCode = ResultCodes.RC_INVALID_PARAMETER_TYPE; } } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing SAP system number connection parameter.", m_taskId); } //Check SAP Credential if (connection.ContainsKey(@"sapUserName") && connection.ContainsKey(@"sapUserPassword")) { m_strSAPUserName = connection[@"sapUserName"] as String; m_strSAPUserPassword = connection[@"sapUserPassword"] as String; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing SAP User name/password connection parameter", m_taskId); } } if (resultCode == ResultCodes.RC_SUCCESS) { using (SAPGuiConnection oConn = new SAPGuiConnection()) { if (!String.IsNullOrEmpty(SAPConnectionString)) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Connecting to remote machine using {1}.", m_taskId, SAPConnectionString); Stopwatch sw = Stopwatch.StartNew(); oConn.Connect(SAPConnectionString, this.m_strSAPUserName, this.m_strSAPUserPassword); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Connection to {1} complete. Elapsed time {2}.\n{3}", m_taskId, m_strApplicationServer, sw.Elapsed.ToString(), oConn.logData.ToString()); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Collecting SAP Client information from remote SAP server.", m_taskId); sw.Reset(); sw.Start(); SAPClientInfoCollector oClientInfoCollector = new SAPClientInfoCollector(ref oConn.Session); oClientInfoCollector.Collect(); m_sapClientInfoProperties = oClientInfoCollector.ResultString; Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Collection of client information complete. Elapsed time {1}.\n{2}", m_taskId, sw.Elapsed.ToString(), oClientInfoCollector.logData.ToString()); } } BuildDataRow(); } } catch (Exception ex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in SAPClientInfoScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in SAPClientInfoScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script SAPClientInfoScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Execute nslookup command remotely. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_executionTimer = Stopwatch.StartNew(); m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WindowsWASHostsLookupScript.", m_taskId); try { // Check ManagementScope CIMV ManagementScope cimvScope = null; if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WindowsWASHostsLookupScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } //Check script parameter if (!scriptParameters.ContainsKey("hostsToLookup")) { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter hostsToLookup.", m_taskId); } else { m_hostsToLookup = scriptParameters[@"hostsToLookup"]; } // Check Remote Process Temp Directory if (!connection.ContainsKey(@"TemporaryDirectory")) { connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, connection[@"TemporaryDirectory"].ToString(), cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Temporary directory {1} has been validated.", m_taskId, connection[@"TemporaryDirectory"].ToString()); } } } if (resultCode == ResultCodes.RC_SUCCESS) { StringBuilder val = new StringBuilder(); String[] hosts = m_hostsToLookup.Split(','); foreach (string host in hosts) { StringBuilder commandLine = new StringBuilder(); if (val.ToString().Length != 0) { val.Append(@"<BDNA,>"); } val.Append(host).Append(@"<BDNA,1>"); commandLine.Append(@"nslookup ").Append(host); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to retrieve command output {1}.", m_taskId, commandLine); String collectedData = ""; using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile( m_taskId, // Task Id to log against. cimvScope, // assuming Remote process uses cimv2 management scope commandLine.ToString(), // batch file connection, // connection dictionary. tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { //This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Batch file executed completed with result code {1}.", m_taskId, resultCode.ToString()); collectedData = rp.Stdout.ToString(); if (string.IsNullOrEmpty(collectedData)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Script completed sucessfully with no data to return.", m_taskId); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } else { string[] collectedDataArr = collectedData.Split("\r\n".ToCharArray()); bool flag = false; for (int i = 0; i < collectedDataArr.Length; i++) { string output = collectedDataArr[i]; if (s_nameRegex.IsMatch(output)) { Match match = s_nameRegex.Match(output); string name = match.Groups["name"].ToString(); val.Append(@"DBHost_DNSHostName=").Append(name); flag = true; } if ((s_addrRegex.IsMatch(output)) && (flag)) { Match match = s_addrRegex.Match(output); string addr = match.Groups["address"].ToString(); val.Append(@"<BDNA,1>DBHost_IPAddr=").Append(addr); } } } } } m_dataRow.Append(m_elementId).Append(',') .Append(m_attributes["lookedUpHosts"]).Append(',') .Append(m_scriptParameters["CollectorId"]).Append(',') .Append(m_taskId).Append(',') .Append(m_databaseTimestamp + m_executionTimer.ElapsedMilliseconds).Append(',') .Append("lookedUpHosts").Append(',') .Append(BdnaDelimiters.BEGIN_TAG).Append(val).Append(BdnaDelimiters.END_TAG); } } catch (Exception ex) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsWASHostsLookupScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WindowsWASHostsLookupScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode); return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); string taskIdString = taskId.ToString(); StringBuilder dataRow = new StringBuilder(); StringBuilder parsedIniFileData = new StringBuilder(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script CollectWindowsCPAINIFile.", taskIdString); Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Hash Dump = {1}", taskIdString, scriptParameters.ToString()); string remoteFileName = scriptParameters[@"CPAWindowsIniFilePath"]; StringBuilder collectedCPAttr = new StringBuilder(); string logData = null; Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Passed file name into the script : {0}", remoteFileName); Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Running TFTP to collect the contents of CPA INI file on a remote system", taskIdString); MemoryStream ms = new MemoryStream(4096); using (TraceListener tl = new TextWriterTraceListener(ms)) { tl.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ProcessId | TraceOptions.ThreadId; try { Lib.Logger.Listeners.Add(tl); // // Create a remote process object to manage the // transfer of the remote file contents to our // script. // // Many of these values are passed to the script from // WinCs to give the Remote Process library access to // Facilities outside the script sandbox. The script // need not care what these values are, just pass them // through. // // Wrap the RemoteProcess in a using clause so that resources // are automatically released when the remote process // operation completes. ManagementScope cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", taskIdString); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); } connection[@"TemporaryDirectory"] = @"c:\"; // collect data from multiple files if (remoteFileName.Contains(",")) { Lib.Logger.TraceEvent(TraceEventType.Information, 0, "CPAIniFilePath has multiple INI files path (" + remoteFileName + ")", taskIdString); string[] iniFiles = remoteFileName.Split(','); for (int fileCount = 0; fileCount < iniFiles.Length; fileCount++) { String fileName = iniFiles[fileCount]; Lib.Logger.TraceEvent(TraceEventType.Information, 0, "CPA file path is " + fileName, taskIdString); using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(taskIdString, // Task Id to log against. cimvScope, // WMI connection, passed to collection script from WinCs fileName, // Name of remote file to retrieve. connection, // credential hash passed to all collection/connection scripts tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { // TFTP listener, passed to script from WinCs // // Launch the remote process. This method will // block until the entire remote process operation // completes. ResultCodes rc = rp.Launch(); // // Once you get control back, there are properties that // can be checked to information about the outcome of the // operation, obtain log data, and retrieve collection results. Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Remote process operation completed with result code" + rc.ToString(), taskIdString); if (null != collectedCPAttr) { collectedCPAttr.Append(rp.Stdout); } } } if (null != collectedCPAttr) { int MIN_SECTIONS = 1; // string collectedCPAttr = sb.ToString(); // System.Console.WriteLine(collectedCPAttr); string[] cpAttrSections = new Regex(@"\[").Split(collectedCPAttr.ToString()); // System.Console.WriteLine("{0} sections in text:", cpAttrSections.Length); if (cpAttrSections.Length > 0) { for (int secCtr = 0; secCtr < cpAttrSections.Length; secCtr++) { // System.Console.WriteLine("This Section"); // System.Console.WriteLine(cpAttrSections[secCtr]); string[] secEntries = cpAttrSections[secCtr].Split('\n'); if (secEntries.Length == 1) { continue; } for (int entryCtr = 0; entryCtr < secEntries.Length; entryCtr++) { string tEntry = secEntries[entryCtr].Trim(); if (tEntry.Length > 0) { if (tEntry.EndsWith("]")) { if (secCtr > MIN_SECTIONS) { parsedIniFileData.Append("<BDNA,>"); } parsedIniFileData.Append("Section="); parsedIniFileData.Append(tEntry.TrimEnd(']')); } else { if (secEntries[entryCtr - 1].Trim().EndsWith("]")) { parsedIniFileData.Append("<BDNA,1>"); } else { parsedIniFileData.Append("<BDNA,2>"); } parsedIniFileData.Append(tEntry); } } } } } Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Parsing Succeeded. Parsed INI File Data is : " + parsedIniFileData.ToString(), parsedIniFileData.ToString()); if (ResultCodes.RC_SUCCESS == resultCode) { dataRow.Append(elementId).Append(',') .Append(attributes[@"collectedCPAttr"]) .Append(',') .Append(scriptParameters[@"CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds) .Append(',') .Append(@"collectedCPAttr") .Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append(collectedCPAttr) .Append(BdnaDelimiters.END_TAG); dataRow.Append(elementId).Append(',') .Append(attributes[@"parsedCPAttr"]) .Append(',') .Append(scriptParameters[@"CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds) .Append(',') .Append(@"parsedCPAttr") .Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append(parsedIniFileData) .Append(BdnaDelimiters.END_TAG); } } } else { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(taskIdString, // Task Id to log against. cimvScope, // WMI connection, passed to collection script from WinCs remoteFileName, // Name of remote file to retrieve. connection, // credential hash passed to all collection/connection scripts tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { // TFTP listener, passed to script from WinCs // // Launch the remote process. This method will // block until the entire remote process operation // completes. ResultCodes rc = rp.Launch(); // // Once you get control back, there are properties that // can be checked to information about the outcome of the // operation, obtain log data, and retrieve collection results. Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Remote process operation completed with result code" + rc.ToString(), taskIdString); if (null != collectedCPAttr) { collectedCPAttr.Append(rp.Stdout); int MIN_SECTIONS = 1; // string collectedCPAttr = sb.ToString(); // System.Console.WriteLine(collectedCPAttr); string[] cpAttrSections = new Regex(@"\[").Split(collectedCPAttr.ToString()); // System.Console.WriteLine("{0} sections in text:", cpAttrSections.Length); if (cpAttrSections.Length > 0) { for (int secCtr = 0; secCtr < cpAttrSections.Length; secCtr++) { // System.Console.WriteLine("This Section"); // System.Console.WriteLine(cpAttrSections[secCtr]); string[] secEntries = cpAttrSections[secCtr].Split('\n'); if (secEntries.Length == 1) { continue; } for (int entryCtr = 0; entryCtr < secEntries.Length; entryCtr++) { string tEntry = secEntries[entryCtr].Trim(); if (tEntry.Length > 0) { if (tEntry.EndsWith("]")) { if (secCtr > MIN_SECTIONS) { parsedIniFileData.Append("<BDNA,>"); } parsedIniFileData.Append("Section="); parsedIniFileData.Append(tEntry.TrimEnd(']')); } else { if (secEntries[entryCtr - 1].Trim().EndsWith("]")) { parsedIniFileData.Append("<BDNA,1>"); } else { parsedIniFileData.Append("<BDNA,2>"); } parsedIniFileData.Append(tEntry); } } } } } Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Parsing Succeeded. Parsed INI File Data is : " + parsedIniFileData.ToString(), parsedIniFileData.ToString()); if (ResultCodes.RC_SUCCESS == resultCode) { dataRow.Append(elementId).Append(',') .Append(attributes[@"collectedCPAttr"]) .Append(',') .Append(scriptParameters[@"CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds) .Append(',') .Append(@"collectedCPAttr") .Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append(collectedCPAttr) .Append(BdnaDelimiters.END_TAG); dataRow.Append(elementId).Append(',') .Append(attributes[@"parsedCPAttr"]) .Append(',') .Append(scriptParameters[@"CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds) .Append(',') .Append(@"parsedCPAttr") .Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append(parsedIniFileData) .Append(BdnaDelimiters.END_TAG); } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "CPA INI File not found on target machine.", taskIdString); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } } } } finally { tl.Flush(); Lib.Logger.Listeners.Remove(tl); } logData = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); } Lib.Logger.TraceEvent(TraceEventType.Information, 0, "CPA INI File data returned: ", taskIdString); Lib.Logger.TraceEvent(TraceEventType.Information, 0, collectedCPAttr.ToString(), taskIdString); Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Log data returned: ", taskIdString); Lib.Logger.TraceEvent(TraceEventType.Information, 0, logData, taskIdString); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); m_taskId = taskId.ToString(); StringBuilder dataRow = new StringBuilder(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script StopServiceSUScript.", m_taskId); try { if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to StopServiceSUScript is null.", m_taskId); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV2 namespace is not present in connection object.", m_taskId); } else if (!connection.ContainsKey(@"default")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for Default namespace is not present in connection object.", m_taskId); } else { ManagementScope defaultScope = connection[@"default"] as ManagementScope; ManagementScope cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV2 namespace failed.", m_taskId); } else if (!defaultScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to Default namespace failed.", m_taskId); } else { string status = "Software usage service not installed"; if (IsServiceSUInstalled(cimvScope)) { StopServiceSU(cimvScope); status = "Software usage agent successfully stopped"; } dataRow.Append(elementId) .Append(',') .Append(attributes[@"status"]) .Append(',') .Append(scriptParameters[@"CollectorId"]) .Append(',') .Append(taskId) .Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds) .Append(',') .Append(@"status") .Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append(status) .Append(BdnaDelimiters.END_TAG); } } } catch (Exception ex) { Lib.LogException(m_taskId, executionTimer, "Unhandled exception in StopServiceSUScript", ex); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script StopServiceSUScript. Elapsed time {1}. Result code {2}.", m_taskId, executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_tftpPath = tftpPath; m_tftpPath_login = tftpPath_login; m_tftpPath_password = tftpPath_password; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script MSVirtualServerVMConfigFileContentScript.", m_taskId); try { // Check ManagementScope CIMV if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to MSVirtualServerVMConfigFileContentScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } //Check VM Config File Path attribute if (scriptParameters.ContainsKey("vmcFile")) { m_vmcFilePath = scriptParameters[@"vmcFile"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter VM Config File Path attribute.", m_taskId); } // Check Remote Process Temp Directory if (!m_connection.ContainsKey(@"TemporaryDirectory")) { m_connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: User specified temp directory has been validated.", m_taskId); } } } if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to retrieve file {1}.", m_taskId, m_vmcFilePath); StringBuilder fileContent = new StringBuilder(); if (Lib.ValidateFile(m_taskId, m_vmcFilePath, m_cimvScope)) { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, m_vmcFilePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { // // Launch the remote process. // This method will block until the entire remote process operation completes. rp.Encoding = Encoding.Unicode; resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote file retrieval operation completed with result code {1}.", m_taskId, resultCode.ToString()); fileContent.Append(rp.Stdout); } //Console.WriteLine(fileContent.ToString()); string formattedFile = fileContent.ToString().Substring(1); StringBuilder fileData = getVMData(formattedFile); this.BuildDataRow(@"vmcFileData", fileData.ToString()); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: VM Config file {1} does not exist.", m_taskId, m_vmcFilePath); resultCode = ResultCodes.RC_SUCCESS; //@TODO: change to RC_REMOTE_FILE_NOT_EXISTED //resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; //@TODO: change to RC_REMOTE_FILE_NOT_EXISTED } } } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in MSVirtualServerVMConfigFileContentScript. Elapsed time {1}.\n{2}Result code changed to RC_PROCESSING_EXECEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in MSVirtualServerVMConfigFileContentScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script MSVirtualServerVMConfigFileContentScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script HyperV_MacAddressInfoScript.", m_taskId); try { // Check ManagementScope virtualization if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to HyperV_MacAddressInfoScript is null.", m_taskId); } else if (!connection.ContainsKey("virtualization")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for virtualization namespace is not present in connection object.", m_taskId); } else { m_virtualizeScope = connection[@"virtualization"] as ManagementScope; if (!m_virtualizeScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to virtualization namespace failed", m_taskId); } if (!connection.ContainsKey("v2")) { //resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for virtualization v2 namespace is not present in connection object.", m_taskId); } else { m_virtualizev2Scope = connection[@"v2"] as ManagementScope; if (!m_virtualizev2Scope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to virtualization v2 namespace failed", m_taskId); } } } //Check VM_Guid attribute if (scriptParameters.ContainsKey("VM_Guid")) { m_VM_Guid = scriptParameters[@"VM_Guid"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter VM_Guid attribute.", m_taskId); } //Check VM_Guid attribute if (scriptParameters.ContainsKey("VM_Guid")) { m_VM_Guid = scriptParameters[@"VM_Guid"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter VM_Guid attribute.", m_taskId); } if (resultCode == ResultCodes.RC_SUCCESS) { /* ConnectionOptions connectionOptions = new ConnectionOptions(); * * connectionOptions.Username = "******"; * * connectionOptions.Password = @"Simple.0"; * ManagementScope m_virtualizeScope = new ManagementScope(@"\\Hyper-v9140\root\virtualization", connectionOptions); * m_virtualizeScope.Connect(); */ String queryString = @"SELECT * FROM Msvm_SyntheticEthernetPortSettingData WHERE InstanceID like '%" + m_VM_Guid + "%'"; ObjectQuery query = new ObjectQuery(queryString); StringBuilder sbVmInfo = new StringBuilder(); ManagementObjectSearcher searcher = null; ManagementObjectCollection moc = null; if (m_virtualizeScope != null) { searcher = new ManagementObjectSearcher(m_virtualizeScope, query); moc = searcher.Get(); using (searcher) { resultCode = Lib.ExecuteWqlQuery(m_taskId, searcher, out moc); } } if (m_virtualizev2Scope != null && ResultCodes.RC_SUCCESS != resultCode && ResultCodes.RC_WMI_QUERY_TIMEOUT != resultCode) { searcher = new ManagementObjectSearcher(m_virtualizev2Scope, query); moc = searcher.Get(); using (searcher) { resultCode = Lib.ExecuteWqlQuery(m_taskId, searcher, out moc); } } String mac = ""; String guid = ""; sbVmInfo.Append("<BDNA,A>"); if (ResultCodes.RC_SUCCESS == resultCode && null != moc) { using (moc) { foreach (ManagementObject mo in moc) { mac = (String)mo["Address"]; guid = (String)mo["InstanceID"]; guid = guid.Replace("Microsoft:", ""); guid = guid.Substring(0, 36); if (mac != null && guid != null) { for (int i = 2; i < mac.Length; i = i + 1 + 2) { mac = mac.Insert(i, ":"); } sbVmInfo.Append(@"<BDNA,>Guid=""" + guid + @"""<BDNA,1>MacAddress =""" + mac + @""""); } } // // Package data into CLE format to be returned. if (sbVmInfo.Length > 0) { // BuildDataRow(s_attributeName, sbVmInfo.ToString()); BuildDataRow(s_attributeName, sbVmInfo.ToString()); } } } } } catch (ManagementException mex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: ManagementException in HyperV_MacAddressInfoScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), mex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } } catch (Exception ex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in HyperV_MacAddressInfoScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in HyperV_MacAddressInfoScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script HyperV_MacAddressInfoScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_tftpPath = tftpPath; m_tftpPath_login = tftpPath_login; m_tftpPath_password = tftpPath_password; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WinFileContentScript.", m_taskId); try { // Check ManagementScope CIMV if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to VMWareVMXConfigFileContentScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } string filePath = string.Empty; foreach (KeyValuePair <string, string> kvp in scriptParameters) { string key = kvp.Key; if (key.Contains(":")) { int i = key.IndexOf(':'); key = key.Substring(i + 1); } if (key == @"filePath") { filePath = kvp.Value; } } if (string.IsNullOrEmpty(filePath)) { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task id {0}: Missing file path parameter.", m_taskId); } // Check Remote Process Temp Directory if (!m_connection.ContainsKey(@"TemporaryDirectory")) { m_connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: User specified temp directory has been validated.", m_taskId); } } } if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to retrieve file {1}.", m_taskId, m_FilePath); StringBuilder fileContent = new StringBuilder(); if (Lib.ValidateFile(m_taskId, filePath, m_cimvScope)) { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, filePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { // // Launch the remote process. // This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote file retrieval operation completed with result code {1}.", m_taskId, resultCode.ToString()); fileContent.Append(rp.Stdout); } this.BuildDataRow(@"fileContent", fileContent.ToString()); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: file {1} does not exist.", m_taskId, filePath); //resultCode = ResultCodes.RC_SUCCESS; } } } catch (ManagementException me) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Insufficient privilege to read file.\nMessage: {1}", m_taskId, me.Message); if (me.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, me.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE; } catch (COMException ce) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Not enough privilege to access run WMI query.\nMessage: {1}.", m_taskId, ce.Message); if (ce.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, ce.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_RUN_WMI_QUERY; } catch (Exception ex) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WinFileContentScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE; } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script VMWareVMXConfigFileContentScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script HyperV_KvpInfoScript.", m_taskId); try { // Check ManagementScope virtualization if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to HyperV_KvpInfoScript is null.", m_taskId); } else if (!connection.ContainsKey("virtualization")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for virtualization namespace is not present in connection object.", m_taskId); } else { m_virtualizeScope = connection[@"virtualization"] as ManagementScope; if (!m_virtualizeScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to virtualization namespace failed", m_taskId); } if (!connection.ContainsKey("v2")) { //resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for virtualization v2 namespace is not present in connection object.", m_taskId); } else { m_virtualizev2Scope = connection[@"v2"] as ManagementScope; if (!m_virtualizev2Scope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to virtualization v2 namespace failed", m_taskId); } } } //Check VM_Guid attribute if (scriptParameters.ContainsKey("VM_Guid")) { m_VM_Guid = scriptParameters[@"VM_Guid"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter VM_Guid attribute.", m_taskId); } if (resultCode == ResultCodes.RC_SUCCESS) { /* ConnectionOptions connectionOptions = new ConnectionOptions(); * * connectionOptions.Username = "******"; * * connectionOptions.Password = @"Simple.0"; * ManagementScope m_virtualizeScope = new ManagementScope(@"\\Hyper-v9140\root\virtualization", connectionOptions); * m_virtualizeScope.Connect(); */ String queryString = @"SELECT * FROM Msvm_KvpExchangeComponent WHERE SystemName like '%" + m_VM_Guid + "%'"; ObjectQuery query = new ObjectQuery(queryString); ManagementObjectSearcher searcher = null; ManagementObjectCollection moc = null; if (m_virtualizeScope != null) { searcher = new ManagementObjectSearcher(m_virtualizeScope, query); moc = searcher.Get(); using (searcher) { resultCode = Lib.ExecuteWqlQuery(m_taskId, searcher, out moc); } } if (m_virtualizev2Scope != null && ResultCodes.RC_SUCCESS != resultCode && ResultCodes.RC_WMI_QUERY_TIMEOUT != resultCode) { searcher = new ManagementObjectSearcher(m_virtualizev2Scope, query); moc = searcher.Get(); using (searcher) { resultCode = Lib.ExecuteWqlQuery(m_taskId, searcher, out moc); } } StringBuilder sbVmInfo = new StringBuilder(); String NetworkAddressIPv6 = ""; String NetworkAddressIPv4 = ""; String IntegrationServicesVersion = ""; String guestOSType = ""; String guestOSVersion = ""; String guestOSPlatformID = ""; String guestCompName = ""; String pattern = @"<PROPERTY NAME=""Data"" TYPE=""string""><VALUE>([^/]*)</VALUE></PROPERTY>"; sbVmInfo.Append("<BDNA,A>"); if (ResultCodes.RC_SUCCESS == resultCode && null != moc) { using (moc) { foreach (ManagementObject mo in moc) { sbVmInfo.Append(@"<BDNA,>"); String guid = (String)mo["SystemName"]; sbVmInfo.Append(@"GUID=""" + guid + @"""<BDNA,1>"); String[] strs = (String[])mo["GuestIntrinsicExchangeItems"]; foreach (String str in strs) { if (str.Contains("NetworkAddressIPv6")) { String ipv6 = str; Match m_ipv6 = Regex.Match(ipv6, pattern); if (m_ipv6.Success) { NetworkAddressIPv6 = m_ipv6.ToString(); NetworkAddressIPv6 = NetworkAddressIPv6.Replace(@"<PROPERTY NAME=""Data"" TYPE=""string""><VALUE>", "").Replace("</VALUE></PROPERTY>", ""); } sbVmInfo.Append(@"<BDNA,1>NetworkAddressIPv6=""" + NetworkAddressIPv6 + @""""); } if (str.Contains("NetworkAddressIPv4")) { String ipv4 = str; Match m_ipv4 = Regex.Match(ipv4, pattern); if (m_ipv4.Success) { NetworkAddressIPv4 = m_ipv4.ToString(); NetworkAddressIPv4 = NetworkAddressIPv4.Replace(@"<PROPERTY NAME=""Data"" TYPE=""string""><VALUE>", "").Replace("</VALUE></PROPERTY>", ""); } sbVmInfo.Append(@"<BDNA,1>NetworkAddressIPv4=""" + NetworkAddressIPv4 + @""""); } if (str.Contains("IntegrationServicesVersion")) { String isv = str; Match m_isv = Regex.Match(isv, pattern); if (m_isv.Success) { IntegrationServicesVersion = m_isv.ToString(); IntegrationServicesVersion = IntegrationServicesVersion.Replace(@"<PROPERTY NAME=""Data"" TYPE=""string""><VALUE>", "").Replace("</VALUE></PROPERTY>", ""); } sbVmInfo.Append(@"<BDNA,1>IntegrationServicesVersion=""" + IntegrationServicesVersion + @""""); } if (str.Contains("OSName")) { String osType = str; Match m_osType = Regex.Match(osType, pattern); if (m_osType.Success) { guestOSType = m_osType.ToString(); guestOSType = guestOSType.Replace(@"<PROPERTY NAME=""Data"" TYPE=""string""><VALUE>", "").Replace("</VALUE></PROPERTY>", ""); } sbVmInfo.Append(@"<BDNA,1>guestOSType=""" + guestOSType + @""""); } if (str.Contains("OSVersion")) { String OSVersion = str; Match m_OSVersion = Regex.Match(OSVersion, pattern); if (m_OSVersion.Success) { guestOSVersion = m_OSVersion.ToString(); guestOSVersion = guestOSVersion.Replace(@"<PROPERTY NAME=""Data"" TYPE=""string""><VALUE>", "").Replace("</VALUE></PROPERTY>", ""); } sbVmInfo.Append(@"<BDNA,1>guestOSVersion=""" + guestOSVersion + @""""); } if (str.Contains("OSPlatformId")) { String OSPlatformId = str; Match m_OSPlatformId = Regex.Match(OSPlatformId, pattern); if (m_OSPlatformId.Success) { guestOSPlatformID = m_OSPlatformId.ToString(); guestOSPlatformID = guestOSPlatformID.Replace(@"<PROPERTY NAME=""Data"" TYPE=""string""><VALUE>", "").Replace("</VALUE></PROPERTY>", ""); } sbVmInfo.Append(@"<BDNA,1>guestOSPlatformID=""" + guestOSPlatformID + @""""); } if (str.Contains("FullyQualifiedDomainName")) { String guestName = str; Match m_guestName = Regex.Match(guestName, pattern); if (m_guestName.Success) { guestCompName = m_guestName.ToString(); guestCompName = guestCompName.Replace(@"<PROPERTY NAME=""Data"" TYPE=""string""><VALUE>", "").Replace("</VALUE></PROPERTY>", ""); } sbVmInfo.Append(@"<BDNA,1>guestCompName=""" + guestCompName + @""""); } } } // // Package data into CLE format to be returned. if (sbVmInfo.Length > 0) { // BuildDataRow(s_attributeName, sbVmInfo.ToString()); BuildDataRow(s_attributeName, sbVmInfo.ToString()); } } } } } catch (ManagementException mex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: ManagementException in HyperV_KvpInfoScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), mex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } } catch (Exception ex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in HyperV_KvpInfoScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in HyperV_KvpInfoScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script HyperV_KvpInfoScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
private void Throw() { ResultCodes resultCode = (ResultCodes)Result; throw new RegisterException(resultCode.ToString()); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); string taskIdString = taskId.ToString(); StringBuilder dataRow = new StringBuilder(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WinTypingStaticScript.", taskIdString); try { ManagementScope cimvScope = null; if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WinTypingStaticScript is null.", taskIdString); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", taskIdString); } else { cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", taskIdString); } else { StringBuilder idString = new StringBuilder(); resultCode = GetIdString(taskIdString, cimvScope, idString); if (ResultCodes.RC_SUCCESS == resultCode) { dataRow.Append(elementId) .Append(',') .Append(attributes[@"windowsTypingData"]) .Append(',') .Append(scriptParameters[@"CollectorId"]) .Append(',') .Append(taskId) .Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds) .Append(',') .Append(@"windowsTypingData") .Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append(idString) .Append(BdnaDelimiters.END_TAG); } } } } catch (ManagementException me) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Insufficient privilege to access Win32_OperatingSystem WMI Class.\nMessage: {1}", taskIdString, me.Message); if (me.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", taskIdString, me.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_RUN_WMI_QUERY; } catch (COMException ce) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Not enough privilege to access run WMI query.\nMessage: {1}.", taskIdString, ce.Message); if (ce.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", taskIdString, ce.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_RUN_WMI_QUERY; } catch (Exception ex) { Lib.LogException(taskIdString, executionTimer, "Unhandled exception in WinTypingStaticScript", ex); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WinTypingStaticScript. Elapsed time {1}. Result code {2}.", taskIdString, executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); Stopwatch executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; StringBuilder dataRow = new StringBuilder(); Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WindowsSiebelServerDataCollectionScript.", m_taskId); try { // // Check ManagementScope CIMV ManagementScope cimvScope = null; if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WindowsSiebelServerDataCollectionScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed.", m_taskId); } } // // Check Siebel Credential if (resultCode == ResultCodes.RC_SUCCESS) { string[] connectionVariables = new String[] { @"SiebelUserName", @"SiebelUserPassword", @"TemporaryDirectory", @"siebelSrvrmgrPath" }; resultCode = this.ValidateConnectionParameters(connection, connectionVariables); } // // Check Parameter variables. if (resultCode == ResultCodes.RC_SUCCESS) { string[] paramVariables = new String[] { @"installDirectory", @"gatewayServerName", @"serverName", @"enterpriseName", @"siebelServerCommand" }; resultCode = this.ValidateScriptParameters(scriptParameters, paramVariables); } // // Check Temporary Directory string tempDir = connection[@"TemporaryDirectory"].ToString(); resultCode = this.ValidateTemporaryDirectory(cimvScope, ref tempDir); // Execute Siebel Command string strBatchFileContent = BuildBatchFile(connection[@"siebelSrvrmgrPath"].ToString(), scriptParameters[@"gatewayServerName"], scriptParameters[@"serverName"], scriptParameters[@"enterpriseName"], connection[@"SiebelUserName"].ToString(), connection[@"SiebelUserPassword"].ToString(), scriptParameters[@"siebelServerCommand"], scriptParameters[@"outputDisplayColumns"]); string stdout = null; using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile (taskId.ToString(), cimvScope, strBatchFileContent, connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { // //This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote process operation completed with result code {1}.", m_taskId, resultCode.ToString()); if (resultCode == ResultCodes.RC_SUCCESS) { if (rp.Stdout != null && rp.Stdout.Length > 0) { stdout = rp.Stdout.ToString(); string commandOutput = null; if (!stdout.Contains(@"Execution completed")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Data returned is shorter than expected, possibly due to transfer failure.\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } else { // // package command output result. if (ResultCodes.RC_SUCCESS == ParseCommandOutput(stdout, scriptParameters[@"siebelServerCommand"], scriptParameters[@"outputDisplayColumns"], out commandOutput)) { if (!attributes.ContainsKey(s_returnAttribute)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Attribute \"{1}\" missing from attributeSet.", m_taskId, s_returnAttribute); } else { dataRow.Append(elementId).Append(',') .Append(attributes[s_returnAttribute]).Append(',') .Append(scriptParameters[@"CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',') .Append(s_returnAttribute).Append(',') .Append(BdnaDelimiters.BEGIN_TAG).Append(commandOutput).Append(BdnaDelimiters.END_TAG); } } } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: No data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.", taskId.ToString()); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Remote execution error.\nSTDOUT.STDERR:\n{1}", m_taskId, rp.Stdout.ToString()); } } //// post processing?? //if (resultCode == ResultCodes.RC_SUCCESS && string.IsNullOrEmpty( > 0) { // //foreach (KeyValuePair<string, QueryTableEntry> entry in s_queryTable) { // // entry.Value.ResultHandler(this, entry.Key, stdoutData.ToString()); // //} //} } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsSiebelServerDataCollectionScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsSiebelServerDataCollectionScript. Elapsed time {1}.\n{2}", m_taskId, executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WindowsSiebelServerDataCollectionScript. Elapsed time {1}. Result code {2}.", m_taskId, executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_connection = connection; string strOracleHome = null, strSchemaName = null, strSchemaPassword = null; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WindowsOracleInstanceLMSOptions3StaticScript.", m_taskId); try { // Check ManagementScope CIMV ManagementScope cimvScope = null; if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WindowsOracleInstanceLMSOptions3StaticScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } if (!scriptParameters.ContainsKey("version")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing script parameter \"version\".", m_taskId); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; } else { m_strVersion = scriptParameters["version"].Trim(); } if (!scriptParameters.ContainsKey("OracleHome")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing script parameter \"OracleHome\".", m_taskId); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; } else { strOracleHome = scriptParameters["OracleHome"].Trim(); if (strOracleHome.EndsWith(@"\")) { strOracleHome = strOracleHome.Substring(0, strOracleHome.Length - 1); } } if (!connection.ContainsKey("schemaName")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing script parameter \"schemaName\".", m_taskId); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; } else { strSchemaName = connection["schemaName"].ToString().Trim(); } if (!connection.ContainsKey("schemaPassword")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing script parameter \"schemaPassword\".", m_taskId); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; } else { strSchemaPassword = connection["schemaPassword"].ToString().Trim(); } if (ResultCodes.RC_SUCCESS == resultCode) { // Check Remote Process Temp Directory if (!connection.ContainsKey("TemporaryDirectory")) { connection["TemporaryDirectory"] = @"%TMP%"; } else { if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Temporary directory {1} has been validated.", m_taskId, connection[@"TemporaryDirectory"].ToString()); } } } } if (resultCode == ResultCodes.RC_SUCCESS) { string strTempDir = connection["TemporaryDirectory"].ToString().Trim(); if (strTempDir.EndsWith(@"\")) { strTempDir = strTempDir.Substring(0, strTempDir.Length - 1); } string strBatchFileContent = buildBatchFile(strTempDir, strOracleHome, strSchemaName, strSchemaPassword); StringBuilder stdoutData = new StringBuilder(); using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile (m_taskId, cimvScope, strBatchFileContent, connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { //This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote process operation completed with result code {1}.", m_taskId, resultCode.ToString()); if (resultCode == ResultCodes.RC_SUCCESS) { stdoutData.Append(rp.Stdout); if (rp.Stdout != null && rp.Stdout.Length > 0) { if (rp.Stdout.ToString().Contains("ORA-01017")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Oracle L3 credential is invalid.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}", m_taskId, rp.Stdout.ToString()); resultCode = ResultCodes.RC_HOST_CONNECT_FAILED; } else if (rp.Stdout.ToString().Contains("ERROR-")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Batch file execution exception.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}", m_taskId, rp.Stdout.ToString()); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } else if (!rp.Stdout.ToString().Contains(@"BDNA")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: SQLPLUS exception, no proper data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}", m_taskId, rp.Stdout.ToString()); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } else if (!rp.Stdout.ToString().Contains(@"Execution completed")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Exception with batch return data.\nData returned is shorter than expected, possibly due to transfer failure.\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: No data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Remote execution error.\nSTDOUT.STDERR:\n{1}", m_taskId, rp.Stdout.ToString()); } } if (resultCode == ResultCodes.RC_SUCCESS && stdoutData.Length > 0) { foreach (KeyValuePair <string, QueryTableEntry> entry in s_queryTable) { entry.Value.ResultHandler(this, entry.Key, stdoutData.ToString()); } this.processLabelSecurityCollectedData(); if (!ver8_pattern.IsMatch(m_strVersion)) { this.processDatabaseVaultCollectedData(); this.processAuditVaultCollectedData(); } foreach (KeyValuePair <string, string> kvp in m_collectedData) { this.BuildDataRow(kvp.Key, kvp.Value); } } } } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsOracleInstanceLMSOptions3StaticScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsOracleInstanceLMSOptions3StaticScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WindowsOracleInstanceLMSOptions3StaticScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); m_taskId = taskId.ToString(); m_connection = connection; m_tftpDispatcher = tftpDispatcher; m_tftpPath = tftpPath; m_tftpPath_login = tftpPath_login; m_tftpPath_password = tftpPath_password; StringBuilder dataRow = new StringBuilder(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script UninstallServiceSUScript.", m_taskId); try { if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to UninstallServiceSUScript is null.", m_taskId); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV2 namespace is not present in connection object.", m_taskId); } else if (!connection.ContainsKey(@"default")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for Default namespace is not present in connection object.", m_taskId); } else { ManagementScope defaultScope = connection[@"default"] as ManagementScope; ManagementScope cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV2 namespace failed.", m_taskId); } else if (!defaultScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to Default namespace failed.", m_taskId); } else { using (ManagementClass wmiRegistry = new ManagementClass(defaultScope, new ManagementPath(@"StdRegProv"), null)) { try { resultCode = DeleteRegistryValues(wmiRegistry); } catch (Exception ex) { // We may catch an exception if the QPD registry keys or values // do not exist. Carry on in this case. } if (resultCode == ResultCodes.RC_SUCCESS) { string status = "Software usage service was not found"; if (IsServiceSUInstalled(cimvScope)) { resultCode = UninstallServiceSU(cimvScope); status = "Software usage agent successfully uninstalled"; } dataRow.Append(elementId) .Append(',') .Append(attributes[@"status"]) .Append(',') .Append(scriptParameters[@"CollectorId"]) .Append(',') .Append(taskId) .Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds) .Append(',') .Append(@"status") .Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append(status) .Append(BdnaDelimiters.END_TAG); } if (resultCode == ResultCodes.RC_SUCCESS && !String.IsNullOrEmpty(m_pathName)) { DeleteFiles(cimvScope); } } } } } catch (Exception ex) { Lib.LogException(m_taskId, executionTimer, "Unhandled exception in UninstallServiceSUScript", ex); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script UninstallServiceSUScript. Elapsed time {1}. Result code {2}.", m_taskId, executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); string taskIdString = taskId.ToString(); StringBuilder dataRow = new StringBuilder(); string strListenerName = null, strOracleHome = null; ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WindowsOracleListenerStaticScript.", taskIdString); try { // Check ManagementScope CIMV ManagementScope cimvScope = null; if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WindowsOracleListenerStaticScript is null.", taskIdString); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", taskIdString); } else { cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed.", taskIdString); } } //Check OracleHome attributes if (!scriptParameters.ContainsKey("OracleHome")) { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing OracleHome script parameter.", taskIdString); } else { strOracleHome = scriptParameters["OracleHome"].Trim(); if (strOracleHome.EndsWith(@"\")) { strOracleHome = strOracleHome.Substring(0, strOracleHome.Length - 1); } } //Check Listener Name attribute if (!scriptParameters.ContainsKey("name")) { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing Listener Name script parameter.", taskIdString); } else { strListenerName = scriptParameters["name"]; } // Check Remote Process Temp Directory if (!connection.ContainsKey(@"TemporaryDirectory")) { connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(taskIdString, connection[@"TemporaryDirectory"].ToString(), cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", taskIdString, connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Temporary directory {1} has been validated.", taskIdString, connection[@"TemporaryDirectory"].ToString()); } } } if (resultCode == ResultCodes.RC_SUCCESS) { string commandLine = @"cmd /q /e:off /C " + strOracleHome.Trim() + @"\BIN\LSNRCTL.EXE status " + strListenerName; StringBuilder stdoutData = new StringBuilder(); using (IRemoteProcess rp = RemoteProcess.NewRemoteProcess(taskIdString, cimvScope, commandLine, null, StdioRedirection.STDOUT, null, connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { //This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote process operation completed with result code {1}.", taskIdString, resultCode.ToString()); if (resultCode == ResultCodes.RC_SUCCESS) { stdoutData.Append(rp.Stdout); if (rp.Stdout != null && rp.Stdout.Length > 0) { if (!rp.Stdout.ToString().ToUpper().Contains(@"PARAMETER FILE")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: SQLPLUS exception, no proper data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}", taskIdString, rp.Stdout.ToString()); //resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: No data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.", taskIdString); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Remote execution error.\n{1}", taskIdString, rp.Stdout.ToString()); } } if (resultCode == ResultCodes.RC_SUCCESS && stdoutData.Length > 0) { string[] arrOutputLine = stdoutData.ToString().Split("\r\n".ToCharArray()); string strListenerAddress = "", strParameterFile = "", strInstances = "", strPort = ""; for (int i = 0; i < arrOutputLine.Length; i++) { string output = arrOutputLine[i]; if (s_connectingRegex_en.IsMatch(output)) { MatchCollection mtc = s_connectingRegex_en.Matches(output); foreach (Match m in mtc) { strListenerAddress = "" + m.Groups["addr"].Value; } } else if (s_connectingRegex_fr.IsMatch(output)) { MatchCollection mtc = s_connectingRegex_fr.Matches(output); foreach (Match m in mtc) { strListenerAddress = "" + m.Groups["addr"].Value; } } else if (s_connectingRegex_de.IsMatch(output)) { MatchCollection mtc = s_connectingRegex_de.Matches(output); foreach (Match m in mtc) { strListenerAddress = "" + m.Groups["addr"].Value; } } else if (s_connectingRegex_it.IsMatch(output)) { MatchCollection mtc = s_connectingRegex_it.Matches(output); foreach (Match m in mtc) { strListenerAddress = "" + m.Groups["addr"].Value; } } if (s_listenerRegex_en.IsMatch(output)) { MatchCollection mtc = s_listenerRegex_en.Matches(output); foreach (Match m in mtc) { strParameterFile += "" + m.Groups["parameterFile"].Value; } } else if (s_listenerRegex_fr.IsMatch(output)) { MatchCollection mtc = s_listenerRegex_fr.Matches(output); foreach (Match m in mtc) { strParameterFile += "" + m.Groups["parameterFile"].Value; } } else if (s_listenerRegex_de.IsMatch(output)) { MatchCollection mtc = s_listenerRegex_de.Matches(output); foreach (Match m in mtc) { strParameterFile += "" + m.Groups["parameterFile"].Value; } } else if (s_listenerRegex_it.IsMatch(output)) { MatchCollection mtc = s_listenerRegex_it.Matches(output); foreach (Match m in mtc) { strParameterFile += "" + m.Groups["parameterFile"].Value; } } if (!String.IsNullOrEmpty(strListenerAddress) && s_listeningRegex_en.IsMatch(output)) { int j = 0; for (j = i; j < arrOutputLine.Length; j++) { string ucaseOutput = arrOutputLine[j].ToUpper(); if (!s_keyExtProcRegex_en.IsMatch(ucaseOutput)) { if (s_descriptionRegex_en.IsMatch(ucaseOutput)) { MatchCollection mtc = s_descriptionRegex_en.Matches(ucaseOutput); foreach (Match m in mtc) { strListenerAddress = m.Groups["addr"].Value; } break; } } i = j; } } else if (!String.IsNullOrEmpty(strListenerAddress) && s_listeningRegex_fr.IsMatch(output)) { int j = 0; for (j = i; j < arrOutputLine.Length; j++) { string ucaseOutput = arrOutputLine[j].ToUpper(); if (!s_keyExtProcRegex_fr.IsMatch(ucaseOutput)) { if (s_descriptionRegex_fr.IsMatch(ucaseOutput)) { MatchCollection mtc = s_descriptionRegex_fr.Matches(ucaseOutput); foreach (Match m in mtc) { strListenerAddress = m.Groups["addr"].Value; } break; } } i = j; } } else if (!String.IsNullOrEmpty(strListenerAddress) && s_listeningRegex_de.IsMatch(output)) { int j = 0; for (j = i; j < arrOutputLine.Length; j++) { string ucaseOutput = arrOutputLine[j].ToUpper(); if (!s_keyExtProcRegex_de.IsMatch(ucaseOutput)) { if (s_descriptionRegex_de.IsMatch(ucaseOutput)) { MatchCollection mtc = s_descriptionRegex_de.Matches(ucaseOutput); foreach (Match m in mtc) { strListenerAddress = m.Groups["addr"].Value; } break; } } i = j; } } else if (!String.IsNullOrEmpty(strListenerAddress) && s_listeningRegex_it.IsMatch(output)) { int j = 0; for (j = i; j < arrOutputLine.Length; j++) { string ucaseOutput = arrOutputLine[j].ToUpper(); if (!s_keyExtProcRegex_it.IsMatch(ucaseOutput)) { if (s_descriptionRegex_it.IsMatch(ucaseOutput)) { MatchCollection mtc = s_descriptionRegex_it.Matches(ucaseOutput); foreach (Match m in mtc) { strListenerAddress = m.Groups["addr"].Value; } break; } } i = j; } } if (s_portRegex_en.IsMatch(strListenerAddress)) { Match m0 = s_portRegex_en.Match(strListenerAddress); strPort = m0.Groups[1].Value; } else if (s_portRegex_fr.IsMatch(strListenerAddress)) { Match m0 = s_portRegex_fr.Match(strListenerAddress); strPort = m0.Groups[1].Value; } else if (s_portRegex_de.IsMatch(strListenerAddress)) { Match m0 = s_portRegex_de.Match(strListenerAddress); strPort = m0.Groups[1].Value; } else if (s_portRegex_it.IsMatch(strListenerAddress)) { Match m0 = s_portRegex_it.Match(strListenerAddress); strPort = m0.Groups[1].Value; } if (s_instancesRegex_en.IsMatch(output)) { Match m0 = s_instancesRegex_en.Match(output); string strinstance = m0.Groups[1].Value; if (!String.IsNullOrEmpty(strInstances)) { if (!strInstances.Contains(strinstance)) { strInstances += " " + strinstance; } } else { strInstances = strinstance; } } } dataRow.Append(elementId).Append(',') .Append(attributes["listenerAddress"]).Append(',') .Append(scriptParameters["CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',') .Append("listenerAddress").Append(',') .Append(BdnaDelimiters.BEGIN_TAG).Append(strListenerAddress).Append(BdnaDelimiters.END_TAG); dataRow.Append(elementId).Append(',') .Append(attributes["parameterFilePath"]).Append(',') .Append(scriptParameters["CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',') .Append("parameterFilePath").Append(',') .Append(BdnaDelimiters.BEGIN_TAG).Append(strParameterFile).Append(BdnaDelimiters.END_TAG); dataRow.Append(elementId).Append(',') .Append(attributes["port"]).Append(',') .Append(scriptParameters["CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',') .Append("port").Append(',') .Append(BdnaDelimiters.BEGIN_TAG).Append(strPort).Append(BdnaDelimiters.END_TAG); dataRow.Append(elementId).Append(',') .Append(attributes["associateInstances"]).Append(',') .Append(scriptParameters["CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',') .Append("associateInstances").Append(',') .Append(BdnaDelimiters.BEGIN_TAG).Append(strInstances).Append(BdnaDelimiters.END_TAG); } } } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsOracleListenerStaticScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", taskIdString, executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WindowsOracleListenerStaticScript. Elapsed time {1}.\n{2}", taskIdString, executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WindowsOracleListenerStaticScript. Elapsed time {1}. Result code {2}.", taskIdString, executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }
/// <summary> /// Execute command /// (Note that file path must be absolute path) /// </summary> /// <param name="filePath">File Path</param> /// <param name="collectedData">Collected Result.</param> /// <returns></returns> private ResultCodes ExecuteCommand(string userCommandLine, out string collectedData) { ResultCodes resultCode = ResultCodes.RC_SUCCESS; collectedData = string.Empty; if (!m_connection.ContainsKey(@"TemporaryDirectory")) { m_connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Temporary directory {1} has been validated.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); } } } if (resultCode == ResultCodes.RC_SUCCESS) { string strTempDir = m_connection["TemporaryDirectory"].ToString().Trim(); if (strTempDir.EndsWith(@"\")) { strTempDir = strTempDir.Substring(0, strTempDir.Length - 1); } string strBatchFileContent = buildBatchFile(userCommandLine); StringBuilder stdoutData = new StringBuilder(); using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile (m_taskId, m_cimvScope, strBatchFileContent, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { //This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote process operation completed with result code {1}.", m_taskId, resultCode.ToString()); if (rp != null && rp.Stdout != null && resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote processExec completed with result <{1}>.", m_taskId, rp.Stdout.ToString()); collectedData = rp.Stdout.ToString(); //string output = rp.Stdout.ToString(); //if (output.IndexOf(s_endTag) != -1) { // collectedData = output.Substring(0, output.Length - s_endTag.Length - 2); //} else { // resultCode = ResultCodes.RC_PROCESS_EXEC_FAILED; // Lib.Logger.TraceEvent(TraceEventType.Error, // 0, // "Task Id {0}: Remote execution error.\nSTDOUT.STDERR:\n{1}", // m_taskId, // rp.Stdout.ToString()); //} } else { resultCode = ResultCodes.RC_PROCESS_EXEC_FAILED; } } } return(resultCode); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script HyperVConfigFileDynamicScript.", m_taskId); try { // Check ManagementScope CIMV if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to HyperVConfigFileDynamicScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } if (resultCode == ResultCodes.RC_SUCCESS) { String strResult = this.findXMLFilePaths(); // Console.WriteLine(strResult); // // Package data into CLE format to be returned. if (strResult.Length > 0) { BuildDataRow(s_attributeName, strResult); } } } catch (ManagementException mex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: no configuration files(c:\\programdata\\microsoft\\windows\\hyper-v\\virtual machines\\*.xml) in exception in HyperVConfigFileDynamicScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), mex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } } catch (Exception ex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in HyperVConfigFileDynamicScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in HyperVConfigFileDynamicScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script HyperVConfigFileDynamicScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Get File Content /// (Note that file path must be absolute path) /// (Note that file path should not have double quote in general, but it has escaped the double quote to be convenient). /// </summary> /// <param name="filePath">File Path</param> /// <param name="collectedData">Collected Result.</param> /// <returns></returns> private ResultCodes GetFileContent(string filePath, out string collectedData) { collectedData = string.Empty; ResultCodes resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_ACCESS_FILE_PROPERTY; if (!m_connection.ContainsKey(@"TemporaryDirectory")) { m_connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: User specified temp directory has been validated.", m_taskId); } } } if (filePath.EndsWith("\"") && filePath.StartsWith("\"")) { filePath = filePath.Substring(1, filePath.Length - 2); } if (Lib.ValidateFile(m_taskId, filePath, m_cimvScope)) { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, filePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { // // Launch the remote process. // This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote file retrieval operation completed with result code {1}.", m_taskId, resultCode.ToString()); collectedData = rp.Stdout.ToString(); } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: filepath: {1} does not exist.", m_taskId, filePath); } return(resultCode); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_executionTimer = Stopwatch.StartNew(); m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WindowsWASProfileFootprintScript.", m_taskId); try { ManagementScope cimvScope = null; ManagementScope defaultScope = null; // Check ManagementScope CIMV if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WindowsWASProfileFootprintScript is null.", m_taskId); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else if (!connection.ContainsKey(@"default")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for Default namespace is not present in connection object.", m_taskId); } else { cimvScope = connection[@"cimv2"] as ManagementScope; defaultScope = connection[@"default"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed.", m_taskId); } else if (!defaultScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to Default namespace failed.", m_taskId); } } //Check WAS Installation Path attribute if (resultCode.Equals(ResultCodes.RC_SUCCESS)) { if (scriptParameters.ContainsKey("profilePath")) { m_profileHome = scriptParameters[@"profilePath"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter WAS Profile Path parameter.", m_taskId); } } // Check Remote Process Temp Directory if (resultCode.Equals(ResultCodes.RC_SUCCESS)) { if (!connection.ContainsKey(@"TemporaryDirectory")) { connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, connection[@"TemporaryDirectory"].ToString(), cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: User specified temp directory has been validated.", m_taskId); } } } } if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to retrieve file {1}.", m_taskId, m_profileHome); StringBuilder fileContent = new StringBuilder(); StringBuilder setupCmd = new StringBuilder(); setupCmd.Append((string)m_profileHome).Append(@"\bin\setupCmdLine.bat"); if (Lib.ValidateFile(m_taskId, setupCmd.ToString(), cimvScope)) { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(m_taskId, cimvScope, setupCmd.ToString(), connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { // // Launch the remote process. // This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote file retrieval operation completed with result code {1}.", m_taskId, resultCode.ToString()); fileContent.Append(rp.Stdout); } // Parse file content resultCode = parseCmdlineFile(fileContent.ToString()); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: WAS setupCmdline file: {1} does not exist.", m_taskId, m_profileHome); resultCode = ResultCodes.RC_SUCCESS; } } } catch (Exception ex) { Lib.LogException(m_taskId, m_executionTimer, "Unhandled exception in WindowsWASProfileFootprintScript", ex); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } CollectionScriptResults result = new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString()); Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WindowsWASProfileFootprintScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), result.ResultCode.ToString()); return(result); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpPath = tftpPath; m_tftpPath_login = tftpPath_login; m_tftpPath_password = tftpPath_password; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WinFilePropertiesScript.", m_taskId); try { // Check ManagementScope CIMV if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WinFilePropertiesScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } string filePath = string.Empty; string fileCommand = string.Empty; foreach (KeyValuePair <string, string> kvp in scriptParameters) { string key = kvp.Key; if (key.Contains(":")) { int i = key.IndexOf(':'); key = key.Substring(i + 1); } if (key == @"filePath") { filePath = kvp.Value; } else if (key == @"fileCommand") { fileCommand = kvp.Value; } } if (string.IsNullOrEmpty(filePath)) { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task id {0}: Missing file path parameter.", m_taskId); } if (string.IsNullOrEmpty(fileCommand)) { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task id {0}: Missing file command parameter.", m_taskId); } if (resultCode == ResultCodes.RC_SUCCESS) { string collectedData = string.Empty; if (fileCommand == @"fileProperties") { resultCode = GetFileProperties(filePath, out collectedData); if (resultCode == ResultCodes.RC_SUCCESS) { BuildDataRow(@"fileProperties", collectedData); } else { BuildDataRow(@"fileProperties", @"NotFound"); } } else if (fileCommand == "dirListing") { resultCode = GetDirListing(filePath, out collectedData); if (resultCode == ResultCodes.RC_SUCCESS) { BuildDataRow(@"fileProperties", collectedData); } else { BuildDataRow(@"fileProperties", @"NotFound"); } } else if (fileCommand == "fileContent") { resultCode = GetFileContent(filePath, out collectedData); if (resultCode == ResultCodes.RC_SUCCESS) { BuildDataRow(@"fileContent", collectedData); } } else if (fileCommand == "executeCommand") { resultCode = ExecuteCommand(filePath, out collectedData); if (resultCode == ResultCodes.RC_SUCCESS) { BuildDataRow(@"commandResult", collectedData); } } } } catch (ManagementException me) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Insufficient privilege to access file property.\nMessage: {1}", m_taskId, me.Message); if (me.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, me.InnerException.Message); } BuildDataRow(@"fileProperties", @"NotFound"); resultCode = ResultCodes.RC_SUCCESS; } catch (COMException ce) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Not enough privilege to access run WMI query.\nMessage: {1}.", m_taskId, ce.Message); if (ce.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, ce.InnerException.Message); } BuildDataRow(@"fileProperties", @"NotFound"); resultCode = ResultCodes.RC_SUCCESS; } catch (Exception ex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WinFilePropertiesScript. Elapsed time {1}.\nResult code changed to RC_PROCESSING_EXCEPTION.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex); resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE; } else { Lib.LogException(m_taskId, m_executionTimer, "Unhandled exception in WinFilePropertiesScript", ex); } BuildDataRow(@"fileProperties", @"NotFound"); resultCode = ResultCodes.RC_SUCCESS; } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WinFilePropertiesScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script VMwareConfigFileDynamicScript.", m_taskId); try { // Check ManagementScope CIMV if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to VMwareConfigFileDynamicScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } if (resultCode == ResultCodes.RC_SUCCESS) { StringBuilder strFiles = new StringBuilder(); StringCollection arrDirs = this.FindLocalUserDirectories(); // If this VMware installation is VMServer, // there is a centralize vm listing file called, "vm-list" if (isVMConfigFileReadable(s_vmserver_central_listing_file_path)) { if (strFiles.Length > 0) { strFiles.Append(BdnaDelimiters.DELIMITER_TAG); } strFiles.Append(s_vmserver_central_listing_file_path); } // If this VMware installation is VMGSXServer, // there is a centralize vm listing file called, "vm-list" if (isVMConfigFileReadable(s_vmgsxserver_central_listing_file_path)) { if (strFiles.Length > 0) { strFiles.Append(BdnaDelimiters.DELIMITER_TAG); } strFiles.Append(s_vmgsxserver_central_listing_file_path); } // // Retrieving property of each file if it exists.. foreach (string strSubDir in arrDirs) { if (!String.IsNullOrEmpty(strSubDir)) { String strFavoriteFilePath = strSubDir + @"\Application Data\VMware\favorites.vmls"; strFavoriteFilePath.Replace(@"\", @"\\"); if (isVMConfigFileReadable(strFavoriteFilePath)) { if (strFiles.Length > 0) { strFiles.Append(BdnaDelimiters.DELIMITER_TAG); } strFiles.Append(strFavoriteFilePath); } } } // // Package data into CLE format to be returned. if (strFiles.Length > 0) { BuildDataRow(s_attributeName, strFiles.ToString()); } } } catch (Exception ex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in VMwareConfigFileDynamicScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in VMwareConfigFileDynamicScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script VMwareConfigFileDynamicScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpPath = tftpPath; m_tftpPath_login = tftpPath_login; m_tftpPath_password = tftpPath_password; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script VMwareVMLSConfigFileContentScript.", m_taskId); try { // Check ManagementScope CIMV if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to VMwareVMLSConfigFileContentScript is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed.", m_taskId); } } //Check VMLSFilePath attribute if (scriptParameters.ContainsKey("VMLSFilePath")) { m_vmlsFilePath = scriptParameters[@"VMLSFilePath"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter VMLSFilePath attribute.", m_taskId); } // Check Remote Process Temp Directory if (!m_connection.ContainsKey(@"TemporaryDirectory")) { m_connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: User specified temp directory has been validated.", m_taskId); } } } // DEBUG-- to be removed #region DEBUG StringBuilder sb = new StringBuilder(); foreach (KeyValuePair <string, string> kvp in m_attributes) { sb.Append(@"Attribute[").Append((string)kvp.Key).Append(@"]=").AppendLine((string)kvp.Value); } Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attribute dictionary contents:\n{1}", m_taskId, sb.ToString()); #endregion // DEBUG if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to retrieve file {1}.", m_taskId, m_vmlsFilePath); StringBuilder fileContent = new StringBuilder(); if (Lib.ValidateFile(m_taskId, m_vmlsFilePath, m_cimvScope)) { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, m_vmlsFilePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { // // Launch the remote process. // This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote file retrieval operation completed with result code {1}.", m_taskId, resultCode.ToString()); fileContent.Append(rp.Stdout); } // Format file content to format: name=value string strFormattedString = this.formatFileContent(fileContent.ToString()); this.BuildDataRow(@"VMLSFileContent", strFormattedString); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: VMLS file {1} does not exist.", m_taskId, m_vmlsFilePath); resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE; } } } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in VMwareVMLSConfigFileContentScript. Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in VMwareVMLSConfigFileContentScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script VMwareVMLSConfigFileContentScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
/// <summary> /// Execute an arbitrary command remotely. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_executionTimer = Stopwatch.StartNew(); string commandLine = string.Empty; //string returnAttribute = null; string returnAttribute = string.Empty; ResultCodes resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script Extend_IBM_WindowsWebSphereMQ_Server_QueueManagerStatic_script.", m_taskId); try { // Check ManagementScope CIMV ManagementScope cimvScope = null; if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to Extend_IBM_WindowsWebSphereMQ_Server_QueueManagerStatic_script is null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } // We have to massage the script parameter set, replace // any keys with a colon by just the part after the colon. Dictionary <string, string> d = new Dictionary <string, string>(); foreach (KeyValuePair <string, string> kvp in scriptParameters) { string[] sa = kvp.Key.Split(s_collectionParameterSetDelimiter, StringSplitOptions.RemoveEmptyEntries); Debug.Assert(sa.Length > 0); d[sa[sa.Length - 1]] = kvp.Value; } scriptParameters = d; //Check input parameter and set what output attribute to return if (scriptParameters.ContainsKey("qmDisplayData_commandLine")) { commandLine = scriptParameters[@"qmDisplayData_commandLine"]; returnAttribute = "qmDisplayData"; } else if (scriptParameters.ContainsKey("channelsStatus_commandLine")) { commandLine = scriptParameters[@"channelsStatus_commandLine"]; returnAttribute = "channelsStatus"; } else if (scriptParameters.ContainsKey("channelsDisplayData_commandLine")) { commandLine = scriptParameters[@"channelsDisplayData_commandLine"]; returnAttribute = "channelsDisplayData"; } else if (scriptParameters.ContainsKey("queuesDisplayData_commandLine")) { commandLine = scriptParameters[@"queuesDisplayData_commandLine"]; returnAttribute = "queuesDisplayData"; } else if (scriptParameters.ContainsKey("channelDetailDisplayData_commandLine")) { commandLine = scriptParameters[@"channelDetailDisplayData_commandLine"]; returnAttribute = "channelDetailDisplayData"; } else if (scriptParameters.ContainsKey("queueDetailDisplayData_commandLine")) { commandLine = scriptParameters[@"queueDetailDisplayData_commandLine"]; returnAttribute = "queueDetailDisplayData"; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing script parameter.", m_taskId); } //Check commandLine parameter //if (!scriptParameters.ContainsKey("commandLine")) if (string.IsNullOrEmpty(commandLine)) { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing command Line parameter.", m_taskId); } else { // Both Working directory and temporary need to be collected as part of Windows Credential. // BUG 14064 has been filed to track this problem. // Check working and temporary directory parameter if (!connection.ContainsKey(@"WorkingDirectory") || string.IsNullOrEmpty(connection[@"WorkingDirectory"].ToString())) { connection[@"WorkingDirectory"] = @"%TMP%"; } if (!connection.ContainsKey(@"TemporaryDirectory") || string.IsNullOrEmpty(connection[@"TemporaryDirectory"].ToString())) { connection[@"TemporaryDirectory"] = @"%TMP%"; } Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to retrieve command output {1}.", m_taskId, commandLine); String batchFileContent = this.BuildBatchFile(connection[@"WorkingDirectory"].ToString(), commandLine); String collectedData = ""; using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile( m_taskId, // Task Id to log against. cimvScope, // assuming Remote process uses cimv2 management scope batchFileContent, // batch file connection, // connection dictionary. tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { //This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Batch file executed completed with result code {1}.", m_taskId, resultCode.ToString()); if (resultCode == ResultCodes.RC_SUCCESS) { collectedData = rp.Stdout.ToString(); if (string.IsNullOrEmpty(collectedData)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Script completed sucessfully with no data to return.", m_taskId); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else if (!collectedData.Contains(@"Execution completed")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Exception with batch file return data.\nData returned is shorter than expected, possibly due to transfer failure.\nResult code changed to RC_PROCESSING_EXCEPTION. Partial result: {1}", m_taskId, collectedData); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } else { collectedData = collectedData.Substring(0, collectedData.Length - @"Execution completed.\r\n".Length); string strFormattedString = this.formatCommandResult(collectedData.ToString()); m_outputData.Append(elementId).Append(',') //.Append(attributes[@"commandResult"]).Append(',') .Append(attributes[returnAttribute]).Append(',') .Append(scriptParameters[@"CollectorId"]).Append(',') .Append(m_taskId).Append(',') .Append(databaseTimestamp + m_executionTimer.ElapsedMilliseconds).Append(',') .Append(returnAttribute).Append(',') //.Append(BdnaDelimiters.BEGIN_TAG).Append(collectedData).Append(BdnaDelimiters.END_TAG); .Append(BdnaDelimiters.BEGIN_TAG).Append(strFormattedString ).Append(BdnaDelimiters.END_TAG); } } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Error during command execution. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode); } } } } } catch (Exception ex) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in Extend_IBM_WindowsWebSphereMQ_Server_QueueManagerStatic_script. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script Extend_IBM_WindowsWebSphereMQ_Server_QueueManagerStatic_script. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode); return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_outputData.ToString())); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); m_taskId = taskId.ToString(); StringBuilder collectedData = new StringBuilder(); ResultCodes resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_ACCESS_FILE_PROPERTY; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script FSecureAVDetailsScript.", m_taskId); try { if (null == scriptParameters) { resultCode = ResultCodes.RC_NULL_PARAMETER_SET; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Parameter set object passed to FSecureAVDetailsScript is null.", m_taskId); } else if (!scriptParameters.ContainsKey(@"installDirectory") || string.IsNullOrEmpty(scriptParameters[@"installDirectory"])) { resultCode = ResultCodes.RC_NULL_PARAMETER_SET_NAME; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Parameter installDirectory object passed to FSecureAVDetailsScript is null.", m_taskId); } else if (null == attributes) { resultCode = ResultCodes.RC_NULL_ATTRIBUTE_SET; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Attribute object passed to FSecureAVDetailsScript is null.", m_taskId); } else if (!attributes.ContainsKey(@"avDefDetails")) { resultCode = ResultCodes.RC_NULL_ATTRIBUTE_SET; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Attribute object passed to FSecureAVDetailsScript is null.", m_taskId); } else if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to FSecureAVDetailsScript is null.", m_taskId); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV2 namespace is not present in connection object.", m_taskId); } else if (!connection.ContainsKey(@"default")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for Default namespace is not present in connection object.", m_taskId); } else { m_defaultScope = connection[@"default"] as ManagementScope; m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV2 namespace failed.", m_taskId); } else if (!m_defaultScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to Default namespace failed.", m_taskId); } else { // Get AV Definition directories ManagementClass wmiRegistry = new ManagementClass(m_defaultScope, new ManagementPath(@"StdRegProv"), null); IList <string> repositoryDirectories = null; using (wmiRegistry) { repositoryDirectories = GetVirusDefinitionPath(wmiRegistry, scriptParameters[@"installDirectory"]); //resultCode = GetInstalledDirectoriesAndVersion(); //if (resultCode == ResultCodes.RC_SUCCESS) { // resultCode = GetBaseInstallationDetails(); //} } foreach (string avDefPath in repositoryDirectories) { IList <string> AV_database = Lib.RetrieveSubDirectories(m_taskId, m_cimvScope, avDefPath.ToString()); foreach (string avRepository in AV_database) { string avRepositoryPath = avDefPath + @"\" + avRepository; string virusDefinitionInfo = GetAntiVirusRepositoryDetails(avRepositoryPath); if (!string.IsNullOrEmpty(virusDefinitionInfo)) { if (collectedData.Length > 0) { collectedData.Append(BdnaDelimiters.DELIMITER1_TAG); } collectedData.Append(virusDefinitionInfo); } } } if (collectedData.Length <= 0) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Script completed sucessfully with no data to return.", m_taskId); } else { dataRow.Append(elementId).Append(',') .Append(attributes[@"avDefDetails"]).Append(',') .Append(scriptParameters[@"CollectorId"]).Append(',') .Append(taskId).Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',') .Append(@"avDefDetails").Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append(collectedData.ToString()) .Append(BdnaDelimiters.END_TAG); resultCode = ResultCodes.RC_SUCCESS; } } } } catch (ManagementException me) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Insufficient privilege to access av file property.\nMessage: {1}", m_taskId, me.Message); if (me.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, me.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_ACCESS_FILE_PROPERTY; } catch (COMException ce) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Not enough privilege to access run WMI query.\nMessage: {1}.", m_taskId, ce.Message); if (ce.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, ce.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_RUN_WMI_QUERY; } catch (Exception ex) { Lib.LogException(m_taskId, executionTimer, "Unhandled exception in FSecureAVDetailsScript", ex); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script FSecureAVDetailsScript. Elapsed time {1}. Result code {2}.", m_taskId, executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }