/** 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())); } }
/** Update the Linux instance. */ void StaticDiskPartitionInstance::Update_Linux() { SCX_LOGTRACE(m_log, L"DiskPartition::Update_Linux():: Entering, DeviceID is:" + m_deviceID); bool opened = m_deps->open(StrToUTF8(m_deviceID).c_str(), O_RDONLY | O_NONBLOCK); if (!opened) { return; // Failure should already be logged by the open call } int ret; struct hd_geometry geo; memset(&geo,0,sizeof(geo)); ret = m_deps->ioctl(HDIO_GETGEO, &geo); if (ret || errno) { SCX_LOGERROR(m_log, L"Could not read disk geometry : ret=" + StrFrom(ret) + L" errno=" + StrFrom(errno)); return; //No use going on . . . } u_int64_t sectorSz=0; ret = m_deps->ioctl( BLKSSZGET, §orSz); if (ret || errno) { SCX_LOGERROR(m_log, L"ioctl BLKSSZGET failed : ret=" + StrFrom(ret) + L" errno=" + StrFrom(errno)); return; } u_int64_t blockDevBsz=0; ret = m_deps->ioctl( BLKBSZGET, &blockDevBsz); if (ret || errno) { SCX_LOGERROR(m_log, L"ioctl BLKBSZGET failed : ret=" + StrFrom(ret) + L" errno=" + StrFrom(errno)); return; } unsigned long partitionSize=0; ret = m_deps->ioctl( BLKGETSIZE, &partitionSize); if (ret || errno) { SCX_LOGERROR(m_log, L"ioctl BLKGETSIZE failed : ret=" + StrFrom(ret) + L" errno=" + StrFrom(errno)); return; } // fill in the fields in the instance of PartitionInformation m_partitionSize = partitionSize * sectorSz; m_blockSize = blockDevBsz; m_startingOffset = geo.start; m_numberOfBlocks = RoundToUnsignedInt( static_cast<double>(m_partitionSize) / static_cast<double>(m_blockSize)); }
/** 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())); } }
/** The disk sampler thread body. \param param - thread parameters. */ void StatisticalLogicalDiskEnumeration::DiskSampler(SCXCoreLib::SCXThreadParamHandle& param) { StatisticalLogicalDiskSamplerParam* p = static_cast<StatisticalLogicalDiskSamplerParam*>(param.GetData()); SCXASSERT(0 != p); SCXASSERT(0 != p->m_diskEnum); bool bUpdate = true; p->m_cond.SetSleep(DISK_SECONDS_PER_SAMPLE * 1000); { SCXCoreLib::SCXConditionHandle h(p->m_cond); while( ! p->GetTerminateFlag()) { if (bUpdate) { try { p->m_diskEnum->SampleDisks(); } catch (const SCXCoreLib::SCXException& e) { SCX_LOGERROR(p->m_diskEnum->m_log, std::wstring(L"StatisticalLogicalDiskEnumeration::DiskSampler() - Unexpected exception caught: ").append(e.What()).append(L" - ").append(e.Where())); } bUpdate = false; } enum SCXCoreLib::SCXCondition::eConditionResult r = h.Wait(); if (SCXCoreLib::SCXCondition::eCondTimeout == r) { bUpdate = true; } } } }
/** Constructor */ OSInstance::OSInstance() : EntityInstance(true) { m_log = SCXLogHandleFactory::GetLogHandle(moduleIdentifier); SCX_LOGTRACE(m_log, L"OSInstance constructor"); // Do various initiation that can be done once and for all #if defined(linux) PrecomputeMaxProcesses(); #elif defined(sun) /* Nothing yet */ #elif defined(hpux) /* Get information the system static variables (guaranteed constant until reboot) */ m_psts_isValid = true; if (pstat_getstatic(&m_psts, sizeof(m_psts), 1, 0) < 0) { SCX_LOGERROR(m_log, StrAppend(L"Could not do pstat_getstatic(). errno = ", errno)); m_psts_isValid = false; } // Compute the boot time once and for all SetBootTime(); #elif defined(aix) /* Nothing yet */ #else #error "Not implemented for this platform." #endif }
/** Sets the time related member variables. Information is read from the file /proc/uptime that contains the number of seconds since the system was last rebooted. This code is duplicated from processinstance.cpp. */ void OSInstance::SetBootTime(void) { m_system_boot_isValid = false; //m_system_boot.IsInitialized(); // First read seconds since boot FILE *f = fopen("/proc/uptime", "r"); if (!f) { SCX_LOGERROR(m_log, StrAppend(L"Could not open /proc/uptime. errno = ", errno)); } int s = fscanf(f, "%lf", &m_upsec); fclose(f); if (s != 1) { SCX_LOGERROR(m_log, StrAppend(L"Could not read /proc/uptime. errno = ", errno)); } SCXAmountOfTime delta; delta.SetSeconds(m_upsec); m_system_boot = m_now - delta; m_system_boot_isValid = true; }
/** Update version Load XML file <disk path>\properties\version\profile.version <?xml version="1.0" encoding="UTF-8"?> <profile> <id>default</id> <version>7.0.0.0</version> <build-info date="8/31/08" level="r0835.03"/> </profile> */ void WebSphereAppServerInstance::UpdateVersion() { const string cProfileNodeName("profile"); const string cVersionNodeName("version"); string xmlcontent; SCXFilePath filename(GetProfileVersionXml()); try { SCXHandle<istream> mystream = m_deps->OpenXmlVersionFile(filename.Get()); GetStringFromStream(mystream, xmlcontent); XElementPtr profileNode; XElement::Load(xmlcontent, profileNode); if (profileNode->GetName() == cProfileNodeName) { XElementPtr versionNode; if (profileNode->GetChild(cVersionNodeName, versionNode)) { wstring version; versionNode->GetContent(version); SetVersion(version); } } } catch (SCXFilePathNotFoundException&) { SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdateVersion() - ").append(GetId()).append(L" - Could not find file: ").append(filename)); } catch (SCXUnauthorizedFileSystemAccessException&) { SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdateVersion() - ").append(GetId()).append(L" - not authorized to open file: ").append(filename)); } catch (XmlException&) { SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdateVersion() - ").append(GetId()).append(L" - Could not load XML from file: ").append(filename)); } }
/** Updates instance with latest data in preparation for read of individual properties. */ void OSInstance::Update() { SCX_LOGTRACE(m_log, L"OSInstance Update()"); // Get current time m_now = SCXCalendarTime::CurrentLocal(); #if defined(hpux) m_unameIsValid = !((uname(&m_unameInfo) < 0) && (errno != EOVERFLOW)); // Meaning: Ok if no error, or if errno is EOVERFLOW #else m_unameIsValid = !(uname(&m_unameInfo) < 0); #endif if (!m_unameIsValid) { SCX_LOGERROR(m_log, StrAppend(L"Could not do uname(). errno = ", errno)); } #if defined(linux) SetBootTime(); #elif defined(hpux) /* Get information about the system dynamic variables */ m_pstd_isValid = true; if (pstat_getdynamic(&m_pstd, sizeof(m_pstd), 1, 0) != 1) { SCX_LOGERROR(m_log, StrAppend(L"Could not do pstat_getdynamic(). errno = ",errno)); m_pstd_isValid = false; } #elif defined (aix) || defined(macos) || defined(sun) // Nothing extra for these platforms #else #error Platform not supported #endif }
/** Constructor \param deps - dependencies */ StatisticalLogicalDiskEnumeration::StatisticalLogicalDiskEnumeration(SCXCoreLib::SCXHandle<DiskDepend> deps) : m_deps(0), m_sampler(0) { m_log = SCXCoreLib::SCXLogHandleFactory::GetLogHandle(L"scx.core.common.pal.system.disk.statisticallogicaldiskenumeration"); m_lock = SCXCoreLib::ThreadLockHandleGet(); m_deps = deps; #if defined(hpux) // Try to init LVM TAB and log errors. try { m_deps->GetLVMTab(); } catch(SCXCoreLib::SCXException& e) { SCX_LOGERROR(m_log, e.What()); throw; } UpdatePathToRdev(L"/dev/dsk/"); UpdatePathToRdev(L"/dev/disk/"); #endif }
/** Store sample data for all instances in collection. */ void StatisticalLogicalDiskEnumeration::SampleDisks() { SCXCoreLib::SCXThreadLock lock(m_lock); #if defined(linux) m_deps->RefreshProcDiskStats(); #endif for (EntityIterator iter = Begin(); iter != End(); iter++) { SCXCoreLib::SCXHandle<StatisticalLogicalDiskInstance> disk = *iter; try { disk->Sample(); } catch (const SCXCoreLib::SCXException& e) { SCX_LOGERROR(m_log, std::wstring(L"StatisticalLogicalDiskEnumeration::SampleDisks() - Unexpected exception caught: ").append( e.What()).append(L" - ").append(e.Where()).append( L"; for logical disk ").append(disk->m_device) ); } } }
/** Report assertion failed suitable for unit tests. Parameters: c - The condition that failed (as a string). f - name of file where asserttion failed. l - line in file where assertion failed. m - extra log message. Ignored if 0. Retval: None. This method is called by the SCXASSERT macro when the assertion failes. This method will log using scxlog and abort as assert usually does. */ void scx_assert_failed(const char* c, const char* f, const unsigned int l, const wchar_t* m /* = 0 */) { std::wstring errText; if (0 == m) { errText = L"Assertion failed: " + SCXCoreLib::StrFromMultibyte(std::string(c)) + L", file " + SCXCoreLib::StrFromMultibyte(std::string(f)) + L", line " + SCXCoreLib::StrFrom(l); } else { errText = L"Assertion failed: " + SCXCoreLib::StrFromMultibyte(std::string(c)) + L", file " + SCXCoreLib::StrFromMultibyte(std::string(f)) + L", line " + SCXCoreLib::StrFrom(l) + L", Message: " + m; } SCX_LOGERROR(SCXCoreLib::SCXLogHandleFactory::GetLogHandle(L"scx.core.assert"), errText); // Send error to stderr as well, just in case we're running in a command-line context std::wcerr << errText << std::endl; abort(); }
/** 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)); } }
/** 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)); } }
/** 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 }
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; }
/** 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 StrFromMultibyte(hwMachine); #else #error "Platform not supported" #endif }
/** 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; }