operatingsystem_linux.cpp

来自「Pegasus is an open-source implementation」· C++ 代码 · 共 950 行 · 第 1/2 页

CPP
950
字号
//%2006//////////////////////////////////////////////////////////////////////////// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;// IBM Corp.; EMC Corporation, The Open Group.// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;// EMC Corporation; VERITAS Software Corporation; The Open Group.// Copyright (c) 2006 Hewlett-Packard Development Company, L.P.; IBM Corp.;// EMC Corporation; Symantec Corporation; The Open Group.//// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to// deal in the Software without restriction, including without limitation the// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or// sell copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// // THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.////==============================================================================//// Author: Al Stone <ahs3@fc.hp.com>//         Christopher Neufeld <neufeld@linuxcare.com>//// Modified By: David Kennedy       <dkennedy@linuxcare.com>//              Christopher Neufeld <neufeld@linuxcare.com>//              Al Stone            <ahs3@fc.hp.com>//              Susan Campbell      <scampbell@hp.com>/////////////////////////////////////////////////////////////////////////////////#include <Pegasus/Common/Config.h>#include <Pegasus/Common/System.h>#include <Pegasus/Common/Logger.h>#include "OperatingSystem.h"#include <iostream>#include <set>#include <sys/utsname.h>#include <sys/types.h>#include <sys/stat.h>#include <sys/param.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#include <unistd.h>#include <time.h>#include <utmpx.h>#include <regex.h>#include <dirent.h>PEGASUS_USING_STD;#define OSP_DEBUG(X) // Logger::put(Logger::DEBUG_LOG, "Linux OSProvider",Logger::INFORMATION, "$0", X)OperatingSystem::OperatingSystem(void){}OperatingSystem::~OperatingSystem(void){}//-- this table is used by getName to load the distribution Name//   into osName. The table documents distro specific//   configuration files that getName will parse in /etc//   if the optional_string is NULL, otherwise the optional string will be used in osName.//static const struct{   const char *vendor_name;   const char *determining_filename;   const char *optional_string;} LINUX_VENDOR_INFO[] = {   { "Caldera",          "coas",               "Caldera Linux" },   { "Corel",            "environment.corel",  "Corel Linux"   },   { "Debian GNU/Linux", "debian_version",     NULL            },   { "Mandrake",         "mandrake-release",   NULL            },   { "Red Hat",          "redhat-release",     NULL            },   { "SuSE",             "SuSE-release",       NULL            },   { "Turbolinux",       "turbolinux-release", NULL            },   { NULL, NULL, NULL }};/**   getVendorInfo method for Linux implementation of OS Provider   Gets the system text from vendor's release file  */static void getVendorInfo(    String& releaseText,    String& nameText ){   static const Uint32 MAX_RELEASE_STRING_LEN=128;   char info_file[MAXPATHLEN];   char buffer[MAX_RELEASE_STRING_LEN];   struct stat statBuf;   for (int ii = 0; LINUX_VENDOR_INFO[ii].vendor_name != NULL ; ii++)   {     sprintf(info_file,  "/etc/%s",             LINUX_VENDOR_INFO[ii].determining_filename );      // If the file exists in /etc, we know what distro we're in      if (!stat(info_file, &statBuf))      {         // Set the default OS name         nameText.assign(LINUX_VENDOR_INFO[ii].vendor_name);         nameText.append(" Distribution");         if (LINUX_VENDOR_INFO[ii].optional_string == NULL)         {	    // try to set text to a more descriptive value from the etc file            FILE *vf = fopen(info_file, "r");            if (vf)            {                if (fgets(buffer, MAX_RELEASE_STRING_LEN, vf) != NULL)                {		    String buffer_s = buffer;                    // parse the text to extract first line                    Uint32 buffer_index = buffer_s.find( '\n' );                    if ( buffer_index != PEG_NOT_FOUND )                    {                        // We have found a valid index into the                        // release string. Now get just the OS name.                        releaseText = buffer_s.subString(0,buffer_index);                        buffer_index = releaseText.find( " release" );                        if ( buffer_index != PEG_NOT_FOUND )                        {			    nameText.assign( releaseText.subString(0,buffer_index) );                        }                    }	       }	       fclose(vf);	    }         }         break;      }   }}/**   getName method of the Linux implementation for the OS Provider   Calls getVendorInfo() to get the operating system name.  */Boolean OperatingSystem::getName(String& osName){    String releaseText;    getVendorInfo( releaseText, osName );    return true;}/**   getUtilGetHostName method for the Linux implementation of the OS Provider   Gets the name of the host system from gethostname and gethostbyname_r.  */static Boolean getUtilGetHostName(String& csName){    char hostName[PEGASUS_MAXHOSTNAMELEN + 1];    struct hostent *hostEntry;    if (gethostname(hostName, sizeof(hostName)) != 0)    {        return false;    }    hostName[sizeof(hostName)-1] = 0;    // Now get the official hostname.  If this call fails then return    // the value from gethostname().    char hostEntryBuffer[8192];    struct hostent hostEntryStruct;    int hostEntryErrno;    gethostbyname_r(        hostName,        &hostEntryStruct,        hostEntryBuffer,        sizeof(hostEntryBuffer),        &hostEntry,        &hostEntryErrno);    if (hostEntry)    {        csName.assign(hostEntry->h_name);    }    else    {        csName.assign(hostName);    }    return true;}Boolean OperatingSystem::getCSName(String& csName){    return getUtilGetHostName(csName);}/**   getCaption method for Linux implementation of OS Provider   Gets the text from the system's release file.  */Boolean OperatingSystem::getCaption(String& caption){   String osName;   getVendorInfo( caption, osName );   return true;}/**   getDescription method for Linux implementation of OS Provider   Gets the text from the system's release file.  */Boolean OperatingSystem::getDescription(String& description){   String osName;   getVendorInfo( description, osName );   return true;}/**   getInstallDate method for Linux implementation of OS provider   Need to determine reliable method of knowing install date   one possibility is date of OS image (but not always   truly the date the OS was installed. For now, don't return   any date (function returns FALSE).  */Boolean OperatingSystem::getInstallDate(CIMDateTime& installDate){// ATTN-SLC-P2-17-Apr-02:  Implement getInstallDate for Linux   return false;}/**   getStatus method for Linux implementation of OS provider   Would like to be able to return and actual status vs. just   always Unknown, but didn't know how to differentiate between   OK and Degraded (assuming they are the only values that make   sense, since the CIMOM is up and running), but one could see   an argument for including Stopping if the Shutdown or Reboot   methods have been invoked. For now, always return "Unknown".    */Boolean OperatingSystem::getStatus(String& status){// ATTN-SLC-P3-17-Apr-02: Get true Linux status (vs. Unknown) BZ#44   status.assign("Unknown");   return true;}/**   getVersion method for Linux implementation of OS provider   Uses uname system call and extracts the release information.   Returns FALSE if uname call results in errors.   */Boolean OperatingSystem::getVersion(String& osVersion){    struct utsname  unameInfo;    char release[sizeof(unameInfo.release)];    // Call uname and check for any errors.    if (uname(&unameInfo) < 0)    {       return false;    }    sprintf(release, "%s", unameInfo.release);    osVersion.assign(release);    return true;}Boolean OperatingSystem::getOSType(Uint16& osType){    osType = LINUX;    return true;}Boolean OperatingSystem::getOtherTypeDescription(String& otherTypeDescription){    struct utsname  unameInfo;    char version[sizeof(unameInfo.release) + sizeof(unameInfo.version)];    // Call uname and check for any errors.    if (uname(&unameInfo) < 0)    {       return false;    }    sprintf(version, "%s %s", unameInfo.release, unameInfo.version);    otherTypeDescription.assign(version);    return true;}static CIMDateTime time_t_to_CIMDateTime(time_t *time_to_represent){   const int CIM_DATE_TIME_ASCII_LEN = 256;   const CIMDateTime NULLTIME;   CIMDateTime dt;   char date_ascii_rep[CIM_DATE_TIME_ASCII_LEN];   char utc_offset[20];   struct tm broken_time;   dt = NULLTIME;   localtime_r(time_to_represent, &broken_time);   if (strftime(date_ascii_rep, CIM_DATE_TIME_ASCII_LEN,                "%Y%m%d%H%M%S.000000", &broken_time))   {#if defined (PEGASUS_PLATFORM_LINUX_GENERIC_GNU)      //-- the following makes use of a GNU extension      snprintf(utc_offset, 20, "%+04ld", broken_time.tm_gmtoff / 60);#else      snprintf(utc_offset, 20, "%+04ld", 0);#endif      strncat(date_ascii_rep, utc_offset, CIM_DATE_TIME_ASCII_LEN);      dt = String(date_ascii_rep);   }   return dt;}/**   getLastBootUpTime method for Linux implementation of OS Provider   gets information from /proc/uptime file  */Boolean OperatingSystem::getLastBootUpTime(CIMDateTime& lastBootUpTime){   const CIMDateTime NULLTIME;   const char *UPTIME_FILE = "/proc/uptime";   CIMDateTime dt;   FILE *procfile;   unsigned long seconds_since_boot;   char read_buffer[MAXPATHLEN];   time_t t_now, t_then;   struct tm tm_now;   dt = NULLTIME;   procfile = fopen(UPTIME_FILE, "r");   if (procfile)   {      if (fgets(read_buffer, MAXPATHLEN, procfile))         if (sscanf(read_buffer, " %lu.", &seconds_since_boot))         {            //-- convert displacement in seconds to a date and time            t_now = time(NULL);            localtime_r(&t_now, &tm_now);            tm_now.tm_sec -= seconds_since_boot;            t_then = mktime(&tm_now);            dt = time_t_to_CIMDateTime(&t_then);         }      fclose(procfile);   }   lastBootUpTime = dt;   return true;}/**   getLocalDateTime method for Linux implementation of OS Provider   Currently calls time to get local time, should be changed to use   the CIMOM date time and be consistent across all time properties   (e.g., LastBootUpTime + SystemUpTime = LocalDateTime)  */Boolean OperatingSystem::getLocalDateTime(CIMDateTime& localDateTime){   time_t now;// ATTN-SLC-P2-17-Apr-02: should convert from time to use of CIMOM datetime   now = time(NULL);   localDateTime = time_t_to_CIMDateTime(&now);   return true;}/**   getCurrentTimeZone method for Linux implementation of OS Provider  */Boolean OperatingSystem::getCurrentTimeZone(Sint16& currentTimeZone){   struct tm buf;   time_t now;// check vs. HP-UX implementation - can't use the same?#if defined(PEGASUS_PLATFORM_LINUX_GENERIC_GNU)   now = time(NULL);   localtime_r(&now, &buf);   currentTimeZone = (buf.tm_gmtoff / 60);   return true;#else   return false;#endif}/**   getNumberOfLicensedUsers method for Linux implementation of OS Provider   Always returns 0 for unlimited  */Boolean OperatingSystem::getNumberOfLicensedUsers(Uint32& numberOfLicensedUsers){   // According to the MOF, if it's unlimited, use zero   numberOfLicensedUsers = 0;   return true;}/**   getNumberOfUsers method for Linux implementation of OS Provider   Goes through the utents, counting the number of type USER_PROCESS  */Boolean OperatingSystem::getNumberOfUsers(Uint32& numberOfUsers){    struct utmpx * utmpp;    numberOfUsers = 0;    while ((utmpp = getutxent()) != NULL)    {        if (utmpp->ut_type == USER_PROCESS)        {            numberOfUsers++;        }    }    endutxent();    return true;}/**   getNumberOfProcesses method for Linux implementation of OS Provider

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?