os_check.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/usr/bin/env python
  2. '''
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. '''
  17. import os
  18. import sys
  19. import platform
  20. def linux_distribution():
  21. PYTHON_VER = sys.version_info[0] * 10 + sys.version_info[1]
  22. if PYTHON_VER < 26:
  23. linux_distribution = platform.dist()
  24. else:
  25. linux_distribution = platform.linux_distribution()
  26. return linux_distribution
  27. class OS_CONST_TYPE(type):
  28. # os families
  29. REDHAT_FAMILY = 'redhat'
  30. DEBIAN_FAMILY = 'debian'
  31. SUSE_FAMILY = 'suse'
  32. # Declare here os type mapping
  33. OS_FAMILY_COLLECTION = [
  34. {'name': REDHAT_FAMILY,
  35. 'os_list':
  36. ['redhat', 'fedora', 'centos', 'oraclelinux',
  37. 'ascendos', 'amazon', 'xenserver', 'oel', 'ovs',
  38. 'cloudlinux', 'slc', 'scientific', 'psbm',
  39. 'centos linux']
  40. },
  41. {'name': DEBIAN_FAMILY,
  42. 'os_list': ['ubuntu', 'debian']
  43. },
  44. {'name': SUSE_FAMILY,
  45. 'os_list': ['sles', 'sled', 'opensuse', 'suse']
  46. }
  47. ]
  48. # Would be generated from Family collection definition
  49. OS_COLLECTION = []
  50. def __init__(cls, name, bases, dct):
  51. for item in cls.OS_FAMILY_COLLECTION:
  52. cls.OS_COLLECTION += item['os_list']
  53. def __getattr__(cls, name):
  54. """
  55. Added support of class.OS_<os_type> properties defined in OS_COLLECTION
  56. Example:
  57. OSConst.OS_CENTOS would return centos
  58. OSConst.OS_OTHEROS would triger an error, coz
  59. that os is not present in OS_FAMILY_COLLECTION map
  60. """
  61. name = name.lower()
  62. if "os_" in name and name[3:] in cls.OS_COLLECTION:
  63. return name[3:]
  64. else:
  65. raise Exception("Unknown class property '%s'" % name)
  66. class OSConst:
  67. __metaclass__ = OS_CONST_TYPE
  68. class OSCheck:
  69. @staticmethod
  70. def get_os_type():
  71. """
  72. Return values:
  73. redhat, fedora, centos, oraclelinux, ascendos,
  74. amazon, xenserver, oel, ovs, cloudlinux, slc, scientific, psbm,
  75. ubuntu, debian, sles, sled, opensuse, suse ... and others
  76. In case cannot detect - exit.
  77. """
  78. # Read content from /etc/*-release file
  79. # Full release name
  80. dist = linux_distribution()
  81. operatingSystem = dist[0].lower()
  82. # special cases
  83. if os.path.exists('/etc/oracle-release'):
  84. return 'oraclelinux'
  85. elif operatingSystem.startswith('suse linux enterprise server'):
  86. return 'sles'
  87. elif operatingSystem.startswith('red hat enterprise linux'):
  88. return 'redhat'
  89. if operatingSystem != '':
  90. return operatingSystem
  91. else:
  92. raise Exception("Cannot detect os type. Exiting...")
  93. @staticmethod
  94. def get_os_family():
  95. """
  96. Return values:
  97. redhat, debian, suse ... and others
  98. In case cannot detect raises exception( from self.get_operating_system_type() ).
  99. """
  100. os_family = OSCheck.get_os_type()
  101. for os_family_item in OSConst.OS_FAMILY_COLLECTION:
  102. if os_family in os_family_item['os_list']:
  103. os_family = os_family_item['name']
  104. break
  105. return os_family.lower()
  106. @staticmethod
  107. def get_os_version():
  108. """
  109. Returns the OS version
  110. In case cannot detect raises exception.
  111. """
  112. # Read content from /etc/*-release file
  113. # Full release name
  114. dist = linux_distribution()
  115. dist = dist[1]
  116. if dist:
  117. return dist
  118. else:
  119. raise Exception("Cannot detect os version. Exiting...")
  120. @staticmethod
  121. def get_os_major_version():
  122. """
  123. Returns the main OS version like
  124. Centos 6.5 --> 6
  125. RedHat 1.2.3 --> 1
  126. """
  127. return OSCheck.get_os_version().split('.')[0]
  128. @staticmethod
  129. def get_os_release_name():
  130. """
  131. Returns the OS release name
  132. In case cannot detect raises exception.
  133. """
  134. dist = linux_distribution()
  135. dist = dist[2].lower()
  136. if dist:
  137. return dist
  138. else:
  139. raise Exception("Cannot detect os release name. Exiting...")
  140. # Exception safe family check functions
  141. @staticmethod
  142. def is_debian_family():
  143. """
  144. Return true if it is so or false if not
  145. This is safe check for debian family, doesn't generate exception
  146. """
  147. try:
  148. if OSCheck.get_os_family() == OSConst.DEBIAN_FAMILY:
  149. return True
  150. except Exception:
  151. pass
  152. return False
  153. @staticmethod
  154. def is_suse_family():
  155. """
  156. Return true if it is so or false if not
  157. This is safe check for suse family, doesn't generate exception
  158. """
  159. try:
  160. if OSCheck.get_os_family() == OSConst.SUSE_FAMILY:
  161. return True
  162. except Exception:
  163. pass
  164. return False
  165. @staticmethod
  166. def is_redhat_family():
  167. """
  168. Return true if it is so or false if not
  169. This is safe check for redhat family, doesn't generate exception
  170. """
  171. try:
  172. if OSCheck.get_os_family() == OSConst.REDHAT_FAMILY:
  173. return True
  174. except Exception:
  175. pass
  176. return False