void SCXWQLSelectStatementCMPI::SetProjection(CMPIArray *projectionPtr) { SCX_LOGTRACE(this->m_log, L"SetProjection(CMPIArray *projectionPtr)"); if(projectionPtr) { cmpiProjection = projectionPtr; CMPIStatus st; unsigned i = projectionPtr->ft->getSize(projectionPtr, &st); if(CMPI_RC_OK != st.rc) { throw SCXInternalErrorException(L"GetSize failed in CMPI: " + StrFromUTF8(st.msg->ft->getCharPtr(st.msg, NULL) ? st.msg->ft->getCharPtr(st.msg, NULL) : ""), SCXSRCLOCATION); } for (unsigned j = 0; j< i; j++) { CMPIData d = projectionPtr->ft->getElementAt(projectionPtr, j, &st); if(CMPI_RC_OK != st.rc) { throw SCXInternalErrorException(L"getElementAt failed in CMPI: " + StrFromUTF8(st.msg->ft->getCharPtr(st.msg, NULL) ? st.msg->ft->getCharPtr(st.msg, NULL) : ""), SCXSRCLOCATION); } if(CMPI_string == d.type) { SCXHandle<SCXProperty> p(new SCXProperty(StrFromUTF8(d.value.string->ft->getCharPtr(d.value.string, &st)), StrFromUTF8(d.value.string->ft->getCharPtr(d.value.string, &st)))); this->projection.push_back(*p); } else { throw SCXInternalErrorException(L"Projection contains property which is not a string type", SCXSRCLOCATION); } } } SCX_LOGTRACE(this->m_log, L"Exit SetProjection(CMPIArray *projectionPtr)"); }
void SCXGlob::DoGlob() { SCX_LOGTRACE(m_logHandle, L"Initialize()"); // Set a default m_index = cNoData; if (this->m_pathnames) { globfree(&this->m_globHolder); memset(&m_globHolder, 0, sizeof(glob_t)); this->m_pathnames = 0; } // Prepares the flag to pass to the OS-provided glob(). int flag = 0; if (!(this->m_isBackSlashEscapeOn)) { flag |= GLOB_NOESCAPE; } if (this->m_isErrorAbortOn) { flag |= GLOB_ERR; } // Calls the OS-provided glob(). int ret = glob(m_pattern.c_str(), flag, NULL, &this->m_globHolder); switch (ret) { case 0: this->m_pathnames = this->m_globHolder.gl_pathv; m_index = cBegin; break; case GLOB_NOMATCH: // No matching pathname exists in the file system. // Does nothing here. break; case GLOB_NOSPACE: { globfree(&this->m_globHolder); wstring message = L"SCXGlob_NoSpace_Error: " + StrFromUTF8(this->m_pattern); throw SCXResourceExhaustedException(L"Memory", message, SCXSRCLOCATION); } case GLOB_ABORTED: { // We are here only if isErrorAbortOn is true. globfree(&this->m_globHolder); wstring message = L"SCXGlob::Initialize(): " + StrFromUTF8(this->m_pattern); throw SCXErrnoException(message, errno, SCXSRCLOCATION); } default: globfree(&this->m_globHolder); wstring message = L"SCXGlob_Unknown_Error: " + StrFromUTF8(this->m_pattern); throw SCXInternalErrorException(message, SCXSRCLOCATION); } }
/** Set user name */ void SCXUser::SetName() { struct passwd pwd; struct passwd *ppwd = NULL; long bufSize = sysconf(_SC_GETPW_R_SIZE_MAX); // Sanity check - all platforms have this, but never hurts to be certain if (bufSize < 1024) { bufSize = 1024; } std::vector<char> buf(bufSize); // Use reentrant form of getpwuid (it's reentrant, and it pacifies purify) #if !defined(sun) int rc = getpwuid_r(m_uid, &pwd, &buf[0], buf.size(), &ppwd); if (rc != 0) { ppwd = NULL; } #else ppwd = getpwuid_r(m_uid, &pwd, &buf[0], buf.size()); #endif if (ppwd) { m_name = StrFromUTF8(ppwd->pw_name); } else { m_name = StrFrom(m_uid); } }
/** Read the SSL information from the config.xml \param[in] sslNode SSL node to read. \param[out] sslEnabled is SSL enabled \param[out] httpsPort HTTPS Port discovered */ void WebLogicFileReader::ReadConfigXmlForSslInformation( const XElementPtr& sslNode, bool& sslEnabled, string& httpsPort) { sslEnabled =false; httpsPort = ""; XElementList sslChildrenNodes; sslNode->GetChildren(sslChildrenNodes); for (size_t index = 0; index < sslChildrenNodes.size(); ++index) { if (sslChildrenNodes[index]->GetName() == WEBLOGIC_SSL_ENABLED_XML_NODE) { string narrow = sslChildrenNodes[index]->GetContent(); wstring wide = StrFromUTF8(narrow); wide = StrToLower(wide); sslEnabled = TRUE_TEXT == wide; } else if (sslChildrenNodes[index]->GetName() == WEBLOGIC_LISTEN_PORT_XML_NODE) { httpsPort = sslChildrenNodes[index]->GetContent(); } } }
void SCXWQLSelectStatementCMPI::SetExp(CMPISelectExp *exp) { SCX_LOGTRACE(this->m_log, L"SetExp(CMPISelectExp *exp)"); if(exp) { cmpiExp = exp; CMPIStatus st; CMPISelectCond *cond = exp->ft->getDOC(exp, &st); if(CMPI_RC_OK != st.rc) { throw SCXInternalErrorException(L"GetDoc failed in CMPI: " + StrFromUTF8(st.msg->ft->getCharPtr(st.msg, NULL) ? st.msg->ft->getCharPtr(st.msg, NULL) : ""), SCXSRCLOCATION); } unsigned i = cond->ft->getCountAndType(cond, NULL, &st); if(CMPI_RC_OK != st.rc) { throw SCXInternalErrorException(L"GetCountAndType failed in CMPI: " + StrFromUTF8(st.msg->ft->getCharPtr(st.msg, NULL) ? st.msg->ft->getCharPtr(st.msg, NULL) : ""), SCXSRCLOCATION); } for (unsigned j = 0; j< i; j++) { SCXHandle<Condition> c = CreateCondition(cond->ft->getSubCondAt(cond, j, &st)); if(CMPI_RC_OK != st.rc) throw SCXInternalErrorException(L"getSubCondAt failed in CMPI: " + StrFromUTF8(st.msg->ft->getCharPtr(st.msg, NULL) ? st.msg->ft->getCharPtr(st.msg, NULL) : ""), SCXSRCLOCATION); this->doc.push_back(*c); } } SCX_LOGTRACE(this->m_log, L"Exit SetExp(CMPISelectExp *exp)"); }
/** Update version Open text file RELEASE-NOTES from the home folder Find line that contains the string "Apache Tomcat Version " Get the rest of the text on that line as the version */ void TomcatAppServerInstance::UpdateVersion() { const string cTomcatVersionPrecursor("Apache Tomcat Version "); SCXFilePath filename(m_homePath); filename.Append(L"RELEASE-NOTES"); try { string filecontent; SCXHandle<istream> mystream = m_deps->OpenVersionFile(filename.Get()); bool foundVersion = false; while (!foundVersion && SCXStream::IsGood(*mystream)) { string tmp; getline(*mystream, tmp); size_t pos = tmp.find(cTomcatVersionPrecursor); if (string::npos != pos) { foundVersion = true; string version = tmp.substr(pos + cTomcatVersionPrecursor.length()); SetVersion(StrStrip(StrFromUTF8(version), L" \t\n\r")); } } } catch (SCXFilePathNotFoundException&) { SCX_LOGERROR(m_log, wstring(L"TomcatAppServerInstance::UpdateVersion() - ").append(GetId()).append(L" - Could not find file: ").append(filename)); } catch (SCXUnauthorizedFileSystemAccessException&) { SCX_LOGERROR(m_log, wstring(L"TomcatAppServerInstance::UpdateVersion() - ").append(GetId()).append(L" - not authorized to open file: ").append(filename)); } }
/** Read the nodemanager.domains file to get a list of the WebLogic 10g domains associated with the installation. Note: this file is located up the tree in a 'well-known' location. i.e. /opt/Oracle/Middleware/wlserver_10.3/common/nodemanager/nodemanager.domains Example: #Domains and directories created by Configuration Wizard #Tue Apr 12 15:23:12 PDT 2011 base_domain=/opt/Oracle/Middleware/user_projects/domains/base_domain \param[in] nodemanagerDomains File object of the text file to open. \param[out] domains vector that will be populated with list of discovered domains. */ void WebLogicFileReader::ReadNodemanagerDomains( const SCXFilePath& nodemanagerDomains, vector<SCXFilePath>& domains) { string content; try { /* * Parse the INI file. * * After a '#', assume the rest of the line is a comment. * The file should consist of name/value pairs seperated * by an '='. */ SCXHandle<istream> reader = OpenNodemanagerDomains(nodemanagerDomains.Get()); while (SCXStream::IsGood(*reader)) { string buffer; getline(*reader, buffer); size_t effectiveEnd = buffer.size(); size_t commentLocation = buffer.find(INI_COMMENT); if (string::npos != commentLocation) { effectiveEnd = commentLocation; } size_t delimiterLocation = buffer.find(INI_DELIMITER); if (string::npos != delimiterLocation) { string narrowPath = buffer.substr(delimiterLocation + 1); wstring widePath = StrFromUTF8(narrowPath); SCXFilePath domainPath; domainPath.SetDirectory(widePath); domains.push_back(domainPath); } } } catch (SCXFilePathNotFoundException&) { SCX_LOGERROR(m_log, wstring(L"WebLogicFileReader::ReadNodemanagerDomains() - "). append(m_installationPath).append(L" - Could not find file: "). append(nodemanagerDomains.Get())); } catch (SCXUnauthorizedFileSystemAccessException&) { SCX_LOGERROR(m_log, wstring(L"WebLogicFileReader::ReadNodemanagerDomains() - "). append(m_installationPath).append(L" - not authorized to open file: "). append(nodemanagerDomains.Get())); } }
/** Read a simple XML file to find the locations of the domains for this WebLogic 11g R1 installation. Example: <?xml version="1.0" encoding="UTF-8"?> <domain-registry xmlns="http://xmlns.oracle.com/weblogic/domain-registry"> <domain location="/opt/Oracle/Middleware/user_projects/domains/base_domain"/> </domain-registry> \param[in] domainRegistryXml File object of the XML file to open. \param[out] domains vector that will contain the list of discovered domains. */ void WebLogicFileReader::ReadDomainRegistryXml( const SCXFilePath& domainRegistryXml, vector<SCXFilePath>& domains) { string xml; try { SCXHandle<istream> reader = OpenDomainRegistryXml(domainRegistryXml.Get()); GetStringFromStream(reader, xml); XElementPtr domainRegistryNode; XElement::Load(xml, domainRegistryNode); if (domainRegistryNode->GetName() == WEBLOGIC_DOMAIN_REGISTRY_XML_NODE) { XElementList domainNodes; domainRegistryNode->GetChildren(domainNodes); for (size_t index = 0; index < domainNodes.size(); ++index) { string location; if (domainNodes[index]->GetName() == WEBLOGIC_DOMAIN_XML_NODE && domainNodes[index]->GetAttributeValue(WEBLOGIC_LOCATION_XML_ATTRIBUTE, location)) { wstring wideLocation = StrFromUTF8(location); SCXFilePath domainPath; domainPath.SetDirectory(wideLocation); domains.push_back(domainPath); } } } } catch (SCXFilePathNotFoundException&) { SCX_LOGERROR(m_log, wstring(L"WebLogicFileReader::ReadDomainRegistryXml() - "). append(m_installationPath).append(L" - Could not find file: "). append(domainRegistryXml.Get())); } catch (SCXUnauthorizedFileSystemAccessException&) { SCX_LOGERROR(m_log, wstring(L"WebLogicFileReader::ReadDomainRegistryXml() - "). append(m_installationPath).append(L" - not authorized to open file: "). append(domainRegistryXml.Get())); } catch (XmlException&) { SCX_LOGERROR(m_log, wstring(L"WebLogicFileReader::ReadDomainRegistryXml() - "). append(m_installationPath).append(L" - Could not load XML from file: "). append(domainRegistryXml.Get())); } }
/** Returns the architecture of the current platform, as uname(3) reports it \returns String with uname result \throws < One for each exception from this function > */ std::wstring SCXOSTypeInfo::GetUnameArchitectureString() const { assert(m_unameIsValid); #if defined(linux) || defined(hpux) || defined(macos) if (m_unameIsValid) { return StrFromUTF8(m_unameInfo.machine); } #elif defined(sun) char buf[256]; if (0 < sysinfo(SI_ARCHITECTURE, buf, sizeof(buf))) { return StrFromUTF8(buf); } #elif defined(aix) // Can't find a generic way to get this property on AIX. This is however the // only one supported right now. return L"powerpc"; #else #error "Platform not supported" #endif return L"Platform not supported"; }
/** Get port from a specialEndpoints tag from the serverindex.xml file \param[in] node specialEndpoint node to get port from \param[out] found Set to true if successfully read port \param[out] port Return the port if found */ void WebSphereAppServerInstance::GetPortFromXml(const XElementPtr& node, bool& found, wstring& port) { const string cEndPointNodeName("endPoint"); const string cPortAttributeName("port"); XElementPtr endPoint; if (node->GetChild(cEndPointNodeName, endPoint)) { string portstr; if (endPoint->GetAttributeValue(cPortAttributeName, portstr)) { port = StrFromUTF8(portstr); found = true; } } }
SCXFilePath SCXGlob::Current() const { SCX_LOGTRACE(m_logHandle, L"Current()"); if(cNoData == m_index) { return SCXFilePath(); } if (this->m_pathnames[m_index]) { return StrFromUTF8(this->m_pathnames[m_index]); } else { return SCXFilePath(); } }
void SCXWQLSelectStatementCMPI::Parse() { SCX_LOGTRACE(this->m_log, L"Parse()"); CMPIArray *projectionPtr; CMPIStatus status; CMPISelectExp *exp = CMNewSelectExp(cmpiBroker, StrToUTF8(query).c_str(), "WQL", &projectionPtr, &status); if(CMPI_RC_OK != status.rc) { if(CMPI_RC_ERR_QUERY_LANGUAGE_NOT_SUPPORTED == status.rc) { throw new SCXInternalErrorException(L"Get CMPI select statement faild. Invalid language specification: " + StrFromUTF8(status.msg->ft->getCharPtr(status.msg, NULL) ? status.msg->ft->getCharPtr(status.msg, NULL) : ""), SCXSRCLOCATION); } if(CMPI_RC_ERR_INVALID_QUERY == status.rc) { throw new SCXParseException(L"Get CMPI select statement faild. Invalid query string: " + StrFromUTF8(status.msg->ft->getCharPtr(status.msg, NULL) ? status.msg->ft->getCharPtr(status.msg, NULL) : ""), SCXSRCLOCATION); } throw new SCXInternalErrorException(L"Get CMPI select statement faild: " + StrFromUTF8(status.msg->ft->getCharPtr(status.msg, NULL) ? status.msg->ft->getCharPtr(status.msg, NULL) : ""), SCXSRCLOCATION); } this->SetExp(exp); this->SetProjection(projectionPtr); SCX_LOGTRACE(this->m_log, L"Exit Parse()"); }
/** Read a simple XML file to find the locations of the both the Admin and Managed servers for a WebLogic 11g R1 installation. Example: <?xml version="1.0" encoding="UTF-8"?> <domain ...> <name>base_domain</name> <domain-version>10.3.2.0</domain-version> <security-configuration ...> ... </security-configuration> <server> <name>AdminServer</name> <ssl> <name>AdminServer</name> <enabled>true</enabled> <listen-port>7012</listen-port> </ssl> <machine>new_UnixMachine_1</machine> <listen-port>7011</listen-port> <listen-address/> </server> <server> <name>new_ManagedServer_1</name> <ssl> <name>new_ManagedServer_1</name> <enabled>true</enabled> <listen-port>7513</listen-port> </ssl> <machine>new_UnixMachine_1</machine> <listen-port>7013</listen-port> <listen-address/> </server> <embedded-ldap> <name>base_domain</name> <credential-encrypted>{AES}RVX+Cadq8XJ5EvV7/1Ta2qGZrJlxve6t5CEa2A9euGUkYOMDTAwAqytymqDBS00Q</credential-encrypted> </embedded-ldap> <configuration-version>10.3.2.0</configuration-version> <machine xsi:type="unix-machineType"> <name>new_UnixMachine_1</name> <node-manager> <name>new_UnixMachine_1</name> <listen-address>localhost</listen-address> <listen-port>5566</listen-port> </node-manager> </machine> <admin-server-name>AdminServer</admin-server-name> </domain> \param[in] domainDir Directory of the domain (needed for build the path to the server \param[in] configXml File object of the XML file to open. \param[out] instances vector that will contain the list of server instances for the given domain. */ void WebLogicFileReader::ReadConfigXml( const SCXFilePath& domainDir, const SCXFilePath& configXml, vector<SCXHandle<AppServerInstance> >& instances) { SCX_LOGTRACE(m_log, L"WebLogicFileReader::ReadConfigXml"); SCX_LOGTRACE(m_log, wstring(L"WebLogicFileReader::ReadConfigXml() - "). append(L"Reading the file: ").append(configXml.Get())); string xml; try { SCXHandle<istream> reader = OpenConfigXml(configXml.Get()); GetStringFromStream(reader, xml); XElementPtr domainNode; XElement::Load(xml, domainNode); if (domainNode->GetName() == WEBLOGIC_DOMAIN_XML_NODE) { string version; ReadConfigXmlForVersion(domainNode, version); string adminServerName; ReadConfigXmlForAdminServerName(domainNode, adminServerName); XElementList serverNodes; domainNode->GetChildren(serverNodes); for (size_t index = 0; index < serverNodes.size(); ++index) { if (serverNodes[index]->GetName() == WEBLOGIC_SERVER_XML_NODE) { bool isAdminServer = false; bool isSslEnabled = false; string name = ""; string httpPort = ""; string httpsPort = ""; XElementList childNodes; serverNodes[index]->GetChildren(childNodes); for (size_t j = 0; j < childNodes.size(); ++j) { /* * <server> * <name>new_ManagedServer_1</name> * <ssl> * <name>new_ManagedServer_1</name> * <enabled>true</enabled> * <listen-port>7513</listen-port> * </ssl> * <machine>new_UnixMachine_1</machine> * <listen-port>7013</listen-port> * <listen-address/> * </server> * */ if (childNodes[j]->GetName() == WEBLOGIC_NAME_XML_NODE) { name = childNodes[j]->GetContent(); isAdminServer = adminServerName == name; } else if (childNodes[j]->GetName() == WEBLOGIC_SSL_XML_NODE) { ReadConfigXmlForSslInformation( childNodes[j], isSslEnabled, httpsPort); } else if (childNodes[j]->GetName() == WEBLOGIC_LISTEN_PORT_XML_NODE) { httpPort = childNodes[j]->GetContent(); } } /* * Having found the server node, * read the children */ wstring wideName = StrFromUTF8(name); SCXFilePath pathOnDisk; pathOnDisk.SetDirectory(domainDir.Get()); pathOnDisk.AppendDirectory(WEBLOGIC_SERVERS_DIRECTORY); pathOnDisk.AppendDirectory(wideName); if (DoesServerDirectoryExist(pathOnDisk)) { SCX_LOGTRACE(m_log, wstring(L"WebLogicFileReader::ReadConfigXml() - "). append(L"Adding instance for ID='").append(pathOnDisk.Get()). append(L"'")); // when the HTTP port is not set for the AdminServer, // default to the default weblogic HTTP port (i.e. 7001) wstring wideHttpPort = StrFromUTF8(httpPort); if(isAdminServer && L"" == wideHttpPort) { wideHttpPort = DEFAULT_WEBLOGIC_HTTP_PORT; } // when the HTTPS port is not set, default to // the default HTTPS port (i.e. 7002) wstring wideHttpsPort = StrFromUTF8(httpsPort); if(L"" == wideHttpsPort) { wideHttpsPort = DEFAULT_WEBLOGIC_HTTPS_PORT; } wstring wideVersion = StrFromUTF8(version); SCXHandle<AppServerInstance> instance( new WebLogicAppServerInstance ( pathOnDisk.GetDirectory())); instance->SetHttpPort(wideHttpPort); instance->SetHttpsPort(wideHttpsPort); instance->SetIsDeepMonitored(false, PROTOCOL_HTTPS); instance->SetIsRunning(false); instance->SetVersion(wideVersion); instance->SetServer( isAdminServer ? WEBLOGIC_SERVER_TYPE_ADMIN : WEBLOGIC_SERVER_TYPE_MANAGED); instances.push_back(instance); } else { SCX_LOGTRACE(m_log, wstring(L"WebLogicFileReader::ReadConfigXml() - "). append(L"The directory (").append(pathOnDisk.Get()). append(L") does not exist on disk, ignoring this instance")); } } } } } catch (SCXFilePathNotFoundException&) { SCX_LOGERROR(m_log, wstring(L"WebLogicFileReader::ReadConfigXml() - "). append(m_installationPath).append(L" - Could not find file: "). append(configXml.Get())); } catch (SCXUnauthorizedFileSystemAccessException&) { SCX_LOGERROR(m_log, wstring(L"WebLogicFileReader::ReadConfigXml() - "). append(m_installationPath).append(L" - not authorized to open file: "). append(configXml.Get())); } catch (XmlException& x) { SCX_LOGERROR(m_log, wstring(L"WebLogicFileReader::ReadConfigXml() - "). append(m_installationPath).append(L" - Could not load XML from file: "). append(configXml.Get())); } }
/** Update ports for Tomcat Load XML file <ConfigPath>/conf/server.xml Get node /Server/Service/Connector where attribute protocol is HTTP/1.1 and secure is true Get attribute named port for HTTPS Port Get node /Server/Service/Connector where attribute protocol is HTTP/1.1 and no attribute named secure exist Get attribute named port for HTTP Port */ void TomcatAppServerInstance::UpdatePorts() { const string cDeploymentNodeName("deployment"); const string cServerNodeName("Server"); const string cServiceNodeName("Service"); const string cConnectorNodeName("Connector"); const string cProtocolAttributeName("protocol"); const string cSecureAttributeName("secure"); const string cPortAttributeName("port"); const string cHTTP11Name("HTTP/1.1"); const string cTrueName("true"); SCXFilePath filename(m_diskPath); string xmlcontent; filename.Append(L"/conf/server.xml"); try { SCXHandle<istream> mystream = m_deps->OpenXmlServerFile(filename.Get()); GetStringFromStream(mystream, xmlcontent); XElementPtr serverNode; XElement::Load(xmlcontent, serverNode); if (serverNode->GetName() == cServerNodeName) { XElementPtr serviceNode; if (serverNode->GetChild(cServiceNodeName, serviceNode)) { XElementList connectorNodes; bool foundHTTPnode = false; bool foundHTTPSnode = false; serviceNode->GetChildren(connectorNodes); for (size_t idx = 0; !(foundHTTPnode && foundHTTPSnode) && idx < connectorNodes.size(); ++idx) { string protocolprop; if (connectorNodes[idx]->GetName() == cConnectorNodeName) { // For Tomcat 5 there is no 'Protocol' specified for the HTTP Connector // we will use the Connectors as they appear in the file. bool hasAttribute = connectorNodes[idx]->GetAttributeValue(cProtocolAttributeName, protocolprop); if( ( hasAttribute && (cHTTP11Name == protocolprop) ) || !hasAttribute ) { string secureprop; string portprop; if (connectorNodes[idx]->GetAttributeValue(cPortAttributeName, portprop)) { if (connectorNodes[idx]->GetAttributeValue(cSecureAttributeName, secureprop) && cTrueName == secureprop) { m_httpsPort = StrFromUTF8(portprop); foundHTTPSnode = true; } else { m_httpPort = StrFromUTF8(portprop); foundHTTPnode = true; } } } } } } } } catch (SCXFilePathNotFoundException&) { SCX_LOGERROR(m_log, wstring(L"TomcatAppServerInstance::UpdateTomcatPorts() - ").append(GetId()).append(L" - Could not find file: ").append(filename)); } catch (SCXUnauthorizedFileSystemAccessException&) { SCX_LOGERROR(m_log, wstring(L"TomcatAppServerInstance::UpdateTomcatPorts() - ").append(GetId()).append(L" - not authorized to open file: ").append(filename)); } catch (XmlException&) { SCX_LOGERROR(m_log, wstring(L"TomcatAppServerInstance::UpdateTomcatPorts() - ").append(GetId()).append(L" - Could not load XML from file: ").append(filename)); } }
bool StaticDiskPartitionInstance::GetBootDrivePath(wstring& bootpathStr) { SCX_LOGTRACE(m_log, L"DiskPartition::GetBootDrivePath():: Entering . . ."); bootpathStr.clear(); // buffer to store lines read from process output wstring curLine; wstring bootInterfacePath; // Determine Solaris boot disk using 'prtconf' and 'ls /dev/dsk' // cmdString stores the current process we are running via SCXProcess::Run() #if defined(sparc) #if PF_MAJOR == 5 && (PF_MINOR == 9 || PF_MINOR == 10) wstring cmdPrtString = L"/usr/sbin/prtconf -pv"; #elif PF_MAJOR == 5 && PF_MINOR == 11 wstring cmdPrtString = L"/sbin/prtconf -pv"; #else #error "Platform not supported" #endif #else// sparc wstring cmdPrtString = L"/usr/bin/grep bootpath /boot/solaris/bootenv.rc"; #endif std::string prtconfResult; std::string finalResult; std::istringstream processInputPrt; std::ostringstream processOutputPrt; std::ostringstream processErrPrt; try { int retCode = m_deps->Run(cmdPrtString, processInputPrt, processOutputPrt, processErrPrt, 15000); if (retCode) { SCX_LOGERROR(m_log, L"Error returned from prtconf, unable to determine boot partition. Error code=" + StrFrom(retCode)); return false; } prtconfResult = processOutputPrt.str(); SCX_LOGTRACE(m_log, L" Got this output from " + cmdPrtString + L" : " + StrFromUTF8(prtconfResult) ); size_t lengthCaptured = prtconfResult.length(); // Truncate trailing newline if there in captured output if (lengthCaptured > 0) { if (prtconfResult[lengthCaptured - 1] == '\n') { prtconfResult[lengthCaptured - 1] = '\0'; } } } catch(SCXCoreLib::SCXException &e) { SCX_LOGERROR(m_log, L"Unable to determine boot partition using prtconf ..." + e.What()); return false; } SCXRegexPtr solPrtconfPatternPtr(NULL); std::vector<wstring> matchingVector; // Let's build our RegEx: try { SCX_LOGTRACE(m_log, L" Using this regex on PrtConf output: " + c_SolPrtconfPattern ); solPrtconfPatternPtr = new SCXCoreLib::SCXRegex(c_SolPrtconfPattern); } catch(SCXCoreLib::SCXInvalidRegexException &e) { SCX_LOGERROR(m_log, L"Exception caught in compiling regex: " + e.What()); return false; } std::istringstream stringStrmPrtconf(prtconfResult); vector<wstring> allLines; // all lines read from prtconf output allLines.clear(); SCXStream::NLFs nlfs; SCXCoreLib::SCXStream::ReadAllLinesAsUTF8(stringStrmPrtconf, allLines, nlfs); for(vector<wstring>::iterator it = allLines.begin(); it != allLines.end(); it++) { curLine.assign(*it); matchingVector.clear(); // Let's get the Boot partition interface and drive letter from prtconf if (solPrtconfPatternPtr->ReturnMatch(curLine, matchingVector, 0)) { bootInterfacePath = matchingVector[1]; SCX_LOGTRACE(m_log, L"Found match of PrtConfPattern : " + bootInterfacePath); break; } } if (bootInterfacePath.size() == 0) { std::wstringstream warningMsg; if (matchingVector.size() > 0) { warningMsg << L"Couldn't find Boot Partition, regular expression error message was: " << matchingVector[0]; } else { warningMsg << L"Couldn't find Boot Partition."; } SCX_LOG(m_log, suppressor.GetSeverity(warningMsg.str()), warningMsg.str()); return false; } // Replace "disk" by "disk" or "sd" to normalize the boot interface path wstring from(L"disk"); size_t start_pos = bootInterfacePath.find(from); if(start_pos != std::string::npos) { bootInterfacePath.replace(start_pos, from.length(), L"(disk|sd)"); } wstring solLsPattern(c_SolLsPatternBeg); solLsPattern += bootInterfacePath; // Now we need to build up our pattern to find the bootdisk, using our results from above: SCXRegexPtr solLsPatternPtr(NULL); //Let's build our RegEx: try { SCX_LOGTRACE(m_log, L" Using this regex on ls -l /dev/dsk output: " + solLsPattern ); solLsPatternPtr = new SCXCoreLib::SCXRegex(solLsPattern); } catch(SCXCoreLib::SCXInvalidRegexException &e) { SCX_LOGERROR(m_log, L"Exception caught in compiling LS Pattern regex: " + e.What()); return false; } // Retrieve the bootdrive using the bootInterface and driveLetter wstring cmdStringLs = L"/usr/bin/ls -l /dev/dsk"; std::string devDskResult; std::istringstream processInputLs; std::ostringstream processOutputLs; std::ostringstream processErrLs; curLine.clear(); try { SCXCoreLib::SCXProcess::Run(cmdStringLs, processInputLs, processOutputLs, processErrLs, 15000); devDskResult = processOutputLs.str(); SCX_LOGTRACE(m_log, L" Got this output from " + cmdStringLs + L" : " + StrFromUTF8(devDskResult) ); size_t lengthCaptured = devDskResult.length(); // Truncate trailing newline if there in captured output if (lengthCaptured > 0) { if (devDskResult[lengthCaptured - 1] == '\n') { devDskResult[lengthCaptured - 1] = '\0'; } } } catch(SCXCoreLib::SCXException &e) { SCX_LOGERROR(m_log, L"Unable to determine boot partition..." + e.What()); return false; } std::istringstream stringStrmDevDsk(devDskResult); allLines.clear(); SCXCoreLib::SCXStream::ReadAllLinesAsUTF8(stringStrmDevDsk, allLines, nlfs); wstring bootDisk(L""); for(vector<wstring>::iterator it = allLines.begin(); it != allLines.end(); it++) { curLine.assign(*it); curLine.push_back('\n'); matchingVector.clear(); // Let's get the boot drive if (solLsPatternPtr->ReturnMatch(curLine, matchingVector, 0)) { bootDisk = matchingVector[1]; //e.g. "c1t0d0s0" break; } } //Check the results if (bootDisk.size() == 0) { std::wstringstream warningMsg; if (matchingVector.size() > 0) { warningMsg << L"Couldn't find Boot Drive, regular expression error message was: " << matchingVector[0]; } else { warningMsg << L"Couldn't find Boot Drive."; } SCX_LOG(m_log, suppressor.GetSeverity(warningMsg.str()), warningMsg.str()); return false; } bootpathStr = L"/dev/dsk/" + bootDisk; //e.g. "/dev/dsk/c1t0d0s0" return true; }
/** Find out operating system name and version This method caches system information in m_osName, m_osVersion and m_osAlias. It requires m_unameInfo to be set prior to call. */ void SCXOSTypeInfo::Init() // private { m_osVersion = L""; m_osName = L"Unknown"; assert(m_unameIsValid); #if defined(hpux) || defined(sun) if (m_unameIsValid) { m_osName = StrFromUTF8(m_unameInfo.sysname); m_osVersion = StrFromUTF8(m_unameInfo.release); } #if defined(hpux) m_osAlias = L"HPUX"; m_osManufacturer = L"Hewlett-Packard Company"; #elif defined(sun) m_osAlias = L"Solaris"; m_osManufacturer = L"Oracle Corporation"; #endif #elif defined(aix) if (m_unameIsValid) { m_osName = StrFromUTF8(m_unameInfo.sysname); // To get "5.3" we must read "5" and "3" from different fields. string ver(m_unameInfo.version); ver.append("."); ver.append(m_unameInfo.release); m_osVersion = StrFromUTF8(ver); } m_osAlias = L"AIX"; m_osManufacturer = L"International Business Machines Corporation"; #elif defined(linux) vector<wstring> lines; SCXStream::NLFs nlfs; #if defined(PF_DISTRO_SUSE) static const string relFileName = "/etc/SuSE-release"; wifstream relfile(relFileName.c_str()); wstring version(L""); wstring patchlevel(L""); SCXStream::ReadAllLines(relfile, lines, nlfs); if (!lines.empty()) { m_osName = ExtractOSName(lines[0]); } // Set the Linux Caption (get first line of the /etc/SuSE-release file) m_linuxDistroCaption = lines[0]; if (0 == m_linuxDistroCaption.length()) { // Fallback - should not normally happen m_linuxDistroCaption = L"SuSE"; } // File contains one or more lines looking like this: // SUSE Linux Enterprise Server 10 (i586) // VERSION = 10 // PATCHLEVEL = 1 for (size_t i = 0; i<lines.size(); i++) { if (StrIsPrefix(StrTrim(lines[i]), L"VERSION", true)) { wstring::size_type n = lines[i].find_first_of(L"="); if (n != wstring::npos) { version = StrTrim(lines[i].substr(n+1)); } } else if (StrIsPrefix(StrTrim(lines[i]), L"PATCHLEVEL", true)) { wstring::size_type n = lines[i].find_first_of(L"="); if (n != wstring::npos) { patchlevel = StrTrim(lines[i].substr(n+1)); } } } if (version.length() > 0) { m_osVersion = version; if (patchlevel.length() > 0) { m_osVersion = version.append(L".").append(patchlevel); } } if (std::wstring::npos != m_osName.find(L"Desktop")) { m_osAlias = L"SLED"; } else { // Assume server. m_osAlias = L"SLES"; } m_osManufacturer = L"SUSE GmbH"; #elif defined(PF_DISTRO_REDHAT) static const string relFileName = "/etc/redhat-release"; wifstream relfile(relFileName.c_str()); SCXStream::ReadAllLines(relfile, lines, nlfs); if (!lines.empty()) { m_osName = ExtractOSName(lines[0]); } // Set the Linux Caption (get first line of the /etc/redhat-release file) m_linuxDistroCaption = lines[0]; if (0 == m_linuxDistroCaption.length()) { // Fallback - should not normally happen m_linuxDistroCaption = L"Red Hat"; } // File should contain one line that looks like this: // Red Hat Enterprise Linux Server release 5.1 (Tikanga) if (lines.size() > 0) { wstring::size_type n = lines[0].find_first_of(L"0123456789"); if (n != wstring::npos) { wstring::size_type n2 = lines[0].substr(n).find_first_of(L" \t\n\t"); m_osVersion = StrTrim(lines[0].substr(n,n2)); } } if ((std::wstring::npos != m_osName.find(L"Client")) // RHED5 || (std::wstring::npos != m_osName.find(L"Desktop"))) // RHED4 { m_osAlias = L"RHED"; } else { // Assume server. m_osAlias = L"RHEL"; } m_osManufacturer = L"Red Hat, Inc."; #elif defined(PF_DISTRO_ULINUX) // The release file is created at agent start time by init.d startup script // This is done to insure that we can write to the appropriate directory at // the time (since, at agent run-time, we may not have root privileges). // // If we CAN create the file here (if we're running as root), then we'll // do so here. But in the normal case, this shouldn't be necessary. Only // in "weird" cases (i.e. starting omiserver by hand, for example). // Create the release file by running GetLinuxOS.sh script // (if we have root privileges) try { if ( !SCXFile::Exists(m_deps->getReleasePath()) && SCXFile::Exists(m_deps->getScriptPath()) && m_deps->isReleasePathWritable() ) { std::istringstream in; std::ostringstream out; std::ostringstream err; int ret = SCXCoreLib::SCXProcess::Run(m_deps->getScriptPath().c_str(), in, out, err, 10000); if ( ret || out.str().length() || err.str().length() ) { wostringstream sout; sout << L"Unexpected errors running script: " << m_deps->getScriptPath().c_str() << L", return code: " << ret << L", stdout: " << StrFromUTF8(out.str()) << L", stderr: " << StrFromUTF8(err.str()); SCX_LOGERROR(m_log, sout.str() ); } } } catch(SCXCoreLib::SCXInterruptedProcessException &e) { wstring msg; msg = L"Timeout running script \"" + m_deps->getScriptPath() + L"\", " + e.Where() + L'.'; SCX_LOGERROR(m_log, msg ); }; // Look in release file for O/S information string sFile = StrToUTF8(m_deps->getReleasePath()); wifstream fin(sFile.c_str()); SCXStream::ReadAllLines(fin, lines, nlfs); if (!lines.empty()) { ExtractToken(L"OSName", lines, m_osName); ExtractToken(L"OSVersion", lines, m_osVersion); ExtractToken(L"OSFullName", lines, m_linuxDistroCaption); ExtractToken(L"OSAlias", lines, m_osAlias); ExtractToken(L"OSManufacturer", lines, m_osManufacturer); } else { m_osAlias = L"Universal"; } // Behavior for m_osCompatName (method GetOSName) should be as follows: // PostInstall scripts will first look for SCX-RELEASE file (only on universal kits) // If found, add "ORIGINAL_KIT_TYPE=Universal" to scxconfig.conf file, // else add "ORIGINAL_KIT_TYPE=!Universal" to scxconfig.conf file. // After that is set up, the SCX-RELEASE file is created. // // A RHEL system should of OSAlias of "RHEL, SLES system should have "SuSE" (in scx-release) // // We need to mimic return values for RHEL and SLES on universal kits that did not // have a universal kit installed previously, but only for RHEL and SLES kits. In // all other cases, continue to return "Linux Distribution". wstring configFilename(m_deps->getConfigPath()); SCXConfigFile configFile(configFilename); try { configFile.LoadConfig(); } catch(SCXFilePathNotFoundException &e) { // Something's whacky with postinstall, so we can't follow algorithm static SCXCoreLib::LogSuppressor suppressor(SCXCoreLib::eError, SCXCoreLib::eTrace); wstring logMessage(L"Unable to load configuration file " + configFilename); SCX_LOG(m_log, suppressor.GetSeverity(logMessage), logMessage); m_osCompatName = L"Unknown Linux Distribution"; } if ( m_osCompatName.empty() ) { wstring kitType; if ( configFile.GetValue(L"ORIGINAL_KIT_TYPE", kitType) ) { if ( L"!Universal" == kitType ) { if ( L"RHEL" == m_osAlias ) { m_osCompatName = L"Red Hat Distribution"; } else if ( L"SLES" == m_osAlias ) { m_osCompatName = L"SuSE Distribution"; } } } if ( m_osCompatName.empty() ) { m_osCompatName = L"Linux Distribution"; } } #else #error "Linux Platform not supported"; #endif #elif defined(macos) m_osAlias = L"MacOS"; m_osManufacturer = L"Apple Inc."; if (m_unameIsValid) { // MacOS is called "Darwin" in uname info, so we hard-code here m_osName = L"Mac OS"; // This value we could read dynamically from the xml file // /System/Library/CoreServices/SystemVersion.plist, but that // file may be named differently based on client/server, and // reading the plist file would require framework stuff. // // Rather than using the plist, we'll use Gestalt, which is an // API designed to figure out versions of anything and everything. // Note that use of Gestalt requires the use of framework stuff // as well, so the Makefiles for MacOS are modified for that. SInt32 major, minor, bugfix; if (0 != Gestalt(gestaltSystemVersionMajor, &major) || 0 != Gestalt(gestaltSystemVersionMinor, &minor) || 0 != Gestalt(gestaltSystemVersionBugFix, &bugfix)) { throw SCXCoreLib::SCXErrnoException(L"Gestalt", errno, SCXSRCLOCATION); } wostringstream sout; sout << major << L"." << minor << L"." << bugfix; m_osVersion = sout.str(); } #else #error "Platform not supported" #endif }
wstring SCXGlob::GetPattern() const { SCX_LOGTRACE(m_logHandle, L"GetPattern()"); return StrFromUTF8(this->m_pattern); }
/** Update ports for WebSphere Load XML file <disk path>/config/cells/<Cell Name>/nodes/<Node Name>/serverindex.xml Ger serverIndex/serverEntries node where serverName attribute is the name of the server For HTTP port get specialEndpoints node where endPointName is WC_defaulthost and get port attribute from endPoint node For HTTPS port get specialEndpoints node where endPointName is WC_defaulthost_secure and get port attribute from endPoint node */ void WebSphereAppServerInstance::UpdatePorts() { const string cServerIndexNodeName("serverindex:ServerIndex"); const string cServerEntriesNodeName("serverEntries"); const string cServerNameAttributeName("serverName"); const string cSpecialEndpointsNodeName("specialEndpoints"); const string cEndPointNameAttributeName("endPointName"); const string cWCdefaultHostName("WC_defaulthost"); const string cWCdefaultHostSecureName("WC_defaulthost_secure"); const string cEndPointNodeName("endPoint"); const string cPortAttributeName("port"); string xmlcontent; SCXFilePath filename(returnProfileDiskPath(m_diskPath)); filename.AppendDirectory(L"config"); filename.AppendDirectory(L"cells"); filename.AppendDirectory(m_cell); filename.AppendDirectory(L"nodes"); filename.AppendDirectory(m_node); filename.SetFilename(L"serverindex.xml"); try { SCXHandle<istream> mystream = m_deps->OpenXmlServerFile(filename.Get()); GetStringFromStream(mystream, xmlcontent); // Load the XML, but don't honor namespaces XElementPtr serverIndexNode; XElement::Load(xmlcontent, serverIndexNode, false); if (serverIndexNode->GetName() == cServerIndexNodeName) { XElementList serverEntriesNodes; bool foundServer = false; serverIndexNode->GetChildren(serverEntriesNodes); for (size_t idx = 0; !foundServer && idx < serverEntriesNodes.size(); ++idx) { string name; if (serverEntriesNodes[idx]->GetName() == cServerEntriesNodeName && serverEntriesNodes[idx]->GetAttributeValue(cServerNameAttributeName, name) && m_server == StrFromUTF8(name)) { XElementList childNodes; bool foundHTTPnode = false; bool foundHTTPSnode = false; foundServer = true; serverEntriesNodes[idx]->GetChildren(childNodes); for (size_t idx2 = 0; !(foundHTTPnode && foundHTTPSnode) && idx2 < childNodes.size(); ++idx2) { if (childNodes[idx2]->GetName() == cSpecialEndpointsNodeName && childNodes[idx2]->GetAttributeValue(cEndPointNameAttributeName, name)) { if (cWCdefaultHostName == name) { GetPortFromXml(childNodes[idx2], foundHTTPnode, m_httpPort); } else if (cWCdefaultHostSecureName == name) { GetPortFromXml(childNodes[idx2], foundHTTPSnode, m_httpsPort); } } } } } } } catch (SCXFilePathNotFoundException&) { SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdatePorts() - ").append(GetId()).append(L" - Could not find file: ").append(filename)); } catch (SCXUnauthorizedFileSystemAccessException&) { SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdatePorts() - ").append(GetId()).append(L" - not authorized to open file: ").append(filename)); } catch (XmlException&) { SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdatePorts() - ").append(GetId()).append(L" - Could not load XML from file: ").append(filename)); } }
/** Update the Solaris Sparc instance. */ void StaticDiskPartitionInstance::Update_Solaris() { SCX_LOGTRACE(m_log, L"DiskPartition::Update_Solaris():: Entering, DeviceID is:" + m_deviceID); // Execute 'df -g' and retrieve result to determine filesystem that is mounted on // and block size. Then, go through output of prtvtoc for this filesystem to // retrieve the remaining partition information. #if PF_MAJOR == 5 && (PF_MINOR == 9 || PF_MINOR == 10) wstring cmdStringDf = L"/usr/sbin/df -g"; #elif PF_MAJOR == 5 && PF_MINOR == 11 wstring cmdStringDf = L"/sbin/df -g"; #else #error "Platform not supported" #endif int status; std::istringstream processInputDf; std::ostringstream processOutputDf; std::ostringstream processErrDf; wstring curLine; curLine.clear(); wstring mountedStr; wstring blockSizeStr; std::string dfResult; vector<wstring> allLines; // all lines read from output allLines.clear(); SCXStream::NLFs nlfs; bool foundIt = false; vector<wstring> matchingVector; SCXRegexPtr solDfPatternPtr(NULL); SCXRegexPtr solPrtvtocBpSPatternPtr(NULL); SCXRegexPtr solPrtvtocDetailPatternPtr(NULL); // Let's build our RegEx: try { solDfPatternPtr = new SCXCoreLib::SCXRegex(c_SolDfPattern); solPrtvtocBpSPatternPtr = new SCXCoreLib::SCXRegex(c_SolPrtvtocBpSPattern); solPrtvtocDetailPatternPtr = new SCXCoreLib::SCXRegex(c_SolprtvtocDetailPattern); } catch(SCXCoreLib::SCXInvalidRegexException &e) { SCX_LOGERROR(m_log, L"Exception caught in compiling regex: " + e.What()); return; } try { status = SCXCoreLib::SCXProcess::Run(cmdStringDf, processInputDf, processOutputDf, processErrDf, 15000); if (status != 0) { SCX_LOGERROR(m_log, StrAppend(L"Error on command " + cmdStringDf + L" - status ", status)); SCX_LOGERROR(m_log, StrFromUTF8("Output - " + processOutputDf.str())); SCX_LOGERROR(m_log, StrFromUTF8("Error - " + processErrDf.str())); return; } dfResult = processOutputDf.str(); } catch(SCXCoreLib::SCXException &e) { SCX_LOGERROR(m_log, L"Unable to retrieve partition information from OS using 'df -g'..." + e.What()); } std::istringstream stringStrmDf_g(dfResult); allLines.clear(); size_t dfLineCt = 100; allLines.reserve(dfLineCt); foundIt = false; SCXCoreLib::SCXStream::ReadAllLinesAsUTF8(stringStrmDf_g, allLines, nlfs); for (vector<wstring>::iterator it = allLines.begin(); it != allLines.end() && !foundIt; it++) { curLine.assign(*it); matchingVector.clear(); if ((solDfPatternPtr->ReturnMatch(curLine, matchingVector, 0)) && (matchingVector.size() >= 4) && (m_deviceID == matchingVector[2])) { mountedStr = matchingVector[1]; blockSizeStr = matchingVector[3]; foundIt = true; } else if (matchingVector.size() > 0) { //Have an error message SCX_LOGINFO(m_log, L"No match found! Error: " + matchingVector[0]); } } //Check the results if (!foundIt || mountedStr .size() == 0) { SCX_LOGERROR(m_log, L"Failed to find this partition info with df -g: " + m_deviceID ); return; } //The next (and last) step is to do a prtvtoc [dir] command to retrieve the rest of the partition info: #if PF_MAJOR == 5 && (PF_MINOR == 9 || PF_MINOR == 10) wstring cmdStringPrtvToc = L"/usr/sbin/prtvtoc " + m_deviceID; #elif PF_MAJOR == 5 && PF_MINOR == 11 wstring cmdStringPrtvToc = L"/sbin/prtvtoc " + m_deviceID; #else #error "Platform not supported" #endif std::istringstream processInputPrtvtoc; std::ostringstream processOutputPrtvtoc; std::ostringstream processErrPrtvtoc; curLine.clear(); wstring firstSectorStr; wstring sectorCountStr; wstring bytesPerSectorStr; std::string prtResult(""); try { SCXCoreLib::SCXProcess::Run(cmdStringPrtvToc, processInputPrtvtoc, processOutputPrtvtoc, processErrPrtvtoc, 15000); prtResult = processOutputPrtvtoc.str(); size_t lengthCaptured = prtResult.length(); // Truncate trailing newline if there in captured output if (lengthCaptured > 0) { if (prtResult[lengthCaptured - 1] == '\n') { prtResult[lengthCaptured - 1] = '\0'; } } } catch(SCXCoreLib::SCXException &e) { SCX_LOGERROR(m_log, L"Unable to retrieve partition information from OS using 'df -g'..." + e.What()); } std::istringstream stringStrmPrtvtoc(prtResult); allLines.clear(); foundIt = false; SCXCoreLib::SCXStream::ReadAllLinesAsUTF8(stringStrmPrtvtoc, allLines, nlfs);; for(vector<wstring>::iterator it = allLines.begin(); it != allLines.end() && !foundIt; it++) { curLine.assign(*it); matchingVector.clear(); // First, we match on a comment line that tells us the Sector Size if (solPrtvtocBpSPatternPtr->ReturnMatch(curLine, matchingVector, 0)) { bytesPerSectorStr = matchingVector[1]; } // Next, we look for a detail line that matches our index: else if ((solPrtvtocDetailPatternPtr->ReturnMatch(curLine, matchingVector, 0)) && (matchingVector.size() >= 5) && (m_index == SCXCoreLib::StrToUInt(matchingVector[1]))) { // This is our row in the Partion info output firstSectorStr = matchingVector[2]; sectorCountStr = matchingVector[3]; foundIt = true; } } //Check the results if (!foundIt || bytesPerSectorStr.size() == 0) { SCX_LOGERROR(m_log, L"Failed to find this partition info with prtvtoc: " + m_deviceID + L" And Regex Error Msg: " + matchingVector[0]); return; } // If we reached here we have everything we need // just need to do a little arithmetic and fill in our Properties struct: m_blockSize = SCXCoreLib::StrToULong(blockSizeStr); char dummyChar; unsigned int sectorSz = StrToUInt(bytesPerSectorStr); unsigned long long totalSectors = StrToUInt(sectorCountStr); unsigned long long startingSector = StrToUInt(firstSectorStr); m_partitionSize = totalSectors * sectorSz; m_startingOffset = startingSector * sectorSz; m_numberOfBlocks = RoundToUnsignedInt(static_cast<double>(m_partitionSize) / static_cast<double>(m_blockSize)); return; }
/** Returns the architecture of the platform, e.g. PA-Risc, x86 or SPARC \returns String with the architecture of the platform */ std::wstring SCXOSTypeInfo::GetArchitectureString() const { #if defined(hpux) #if defined(hppa) return L"PA-Risc"; #else return L"IA64"; #endif // defined(hpux) #elif defined(linux) unsigned short bitSize = 0; try { SystemInfo sysInfo; sysInfo.GetNativeBitSize(bitSize); } catch (SCXCoreLib::SCXException &e) { SCX_LOGERROR(m_log, StrAppend( StrAppend(L"Failure in SystemInstance::GetNativeBitSize: ", e.What()), e.Where())); } if (32 == bitSize) { return L"x86"; } else if (64 == bitSize) { return L"x64"; } else { assert(!"Unknown architecture"); return L"Unknown"; } #elif defined(sun) #if defined(sparc) return L"SPARC"; #else return L"x86"; #endif #elif defined(aix) return L"powerpc"; // This is what uname -p says #elif defined(macos) // On MacOS Intel platforms, the architecture appears to always be i386, // regardless of 32-bit vs. 64-bit capabilities. However, since we may // (some day) run on something else, we'll implement this properly. // // Intel (i386) on Mac is a special case: we return 'x86' or 'x64' based // on 64-bit capabilities of the CPU. // First get the machine architecture dynamically int mib[2]; char hwMachine[64]; size_t len_hwMachine = sizeof(hwMachine); mib[0] = CTL_HW; mib[1] = HW_MACHINE; if (0 != sysctl(mib, 2, hwMachine, &len_hwMachine, NULL, 0)) { wostringstream sout; sout << L"Failure calling sysctl(): Errno=" << errno; SCX_LOGERROR(m_log, sout.str()); return L""; } // Now figure out our bit size (if Intel, handle the special case) if (0 == strncmp("i386", hwMachine, sizeof(hwMachine))) { unsigned short bitSize = 0; try { SystemInfo sysInfo; sysInfo.GetNativeBitSize(bitSize); } catch (SCXCoreLib::SCXException &e) { SCX_LOGERROR(m_log, StrAppend( StrAppend(L"Failure in SystemInstance::GetNativeBitSize: ", e.What()), e.Where())); } if (32 == bitSize) { return L"x86"; } else if (64 == bitSize) { return L"x64"; } } // Return the actual architecture, whatever it is return StrFromUTF8(hwMachine); #else #error "Platform not supported" #endif }