PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/hadoop-1.1.2/src/contrib/hod/hodlib/Common/util.py

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Python | 309 lines | 290 code | 6 blank | 13 comment | 0 complexity | 6ff4a1aab66cf261adb6add65bd27171 MD5 | raw file
  1. #Licensed to the Apache Software Foundation (ASF) under one
  2. #or more contributor license agreements. See the NOTICE file
  3. #distributed with this work for additional information
  4. #regarding copyright ownership. The ASF licenses this file
  5. #to you under the Apache License, Version 2.0 (the
  6. #"License"); you may not use this file except in compliance
  7. #with the License. You may obtain a copy of the License at
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #Unless required by applicable law or agreed to in writing, software
  10. #distributed under the License is distributed on an "AS IS" BASIS,
  11. #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. #See the License for the specific language governing permissions and
  13. #limitations under the License.
  14. import errno, sys, os, traceback, stat, socket, re, warnings, signal
  15. from hodlib.Common.tcp import tcpSocket, tcpError
  16. from hodlib.Common.threads import simpleCommand
  17. setUGV = { 'S_ISUID' : 2, 'S_ISGID' : 1, 'S_ISVTX' : 0 }
  18. reEscapeSeq = r"\\(.)?"
  19. reEscapeSeq = re.compile(reEscapeSeq)
  20. HOD_INTERRUPTED_CODE = 127
  21. HOD_INTERRUPTED_MESG = "Hod interrupted. Cleaning up and exiting"
  22. TORQUE_USER_LIMITS_COMMENT_FIELD = "User-limits exceeded. " + \
  23. "Requested:([0-9]*) Used:([0-9]*) MaxLimit:([0-9]*)"
  24. TORQUE_USER_LIMITS_EXCEEDED_MSG = "Requested number of nodes exceeded " + \
  25. "maximum user limits. "
  26. class AlarmException(Exception):
  27. def __init__(self, msg=''):
  28. self.message = msg
  29. Exception.__init__(self, msg)
  30. def __repr__(self):
  31. return self.message
  32. def isProcessRunning(pid):
  33. '''Check if a process is running, by sending it a 0 signal, and checking for errors'''
  34. # This method is documented in some email threads on the python mailing list.
  35. # For e.g.: http://mail.python.org/pipermail/python-list/2002-May/144522.html
  36. try:
  37. os.kill(pid, 0)
  38. return True
  39. except OSError, err:
  40. return err.errno == errno.EPERM
  41. def untar(file, targetDir):
  42. status = False
  43. command = 'tar -C %s -zxf %s' % (targetDir, file)
  44. commandObj = simpleCommand('untar', command)
  45. commandObj.start()
  46. commandObj.wait()
  47. commandObj.join()
  48. if commandObj.exit_code() == 0:
  49. status = True
  50. return status
  51. def tar(tarFile, tarDirectory, tarList):
  52. currentDir = os.getcwd()
  53. os.chdir(tarDirectory)
  54. status = False
  55. command = 'tar -czf %s ' % (tarFile)
  56. for file in tarList:
  57. command = "%s%s " % (command, file)
  58. commandObj = simpleCommand('tar', command)
  59. commandObj.start()
  60. commandObj.wait()
  61. commandObj.join()
  62. if commandObj.exit_code() == 0:
  63. status = True
  64. else:
  65. status = commandObj.exit_status_string()
  66. os.chdir(currentDir)
  67. return status
  68. def to_http_url(list):
  69. """convert [hostname, port] to a http url"""
  70. str = ''
  71. str = "http://%s:%s" % (list[0], list[1])
  72. return str
  73. def get_exception_string():
  74. (type, value, tb) = sys.exc_info()
  75. exceptList = traceback.format_exception(type, value, tb)
  76. exceptString = ''
  77. for line in exceptList:
  78. exceptString = "%s%s" % (exceptString, line)
  79. return exceptString
  80. def get_exception_error_string():
  81. (type, value, tb) = sys.exc_info()
  82. if value:
  83. exceptString = "%s %s" % (type, value)
  84. else:
  85. exceptString = type
  86. return exceptString
  87. def check_timestamp(timeStamp):
  88. """ Checks the validity of a timeStamp.
  89. timeStamp - (YYYY-MM-DD HH:MM:SS in UTC)
  90. returns True or False
  91. """
  92. isValid = True
  93. try:
  94. timeStruct = time.strptime(timeStamp, "%Y-%m-%d %H:%M:%S")
  95. except:
  96. isValid = False
  97. return isValid
  98. def sig_wrapper(sigNum, handler, *args):
  99. if args:
  100. handler(args)
  101. else:
  102. handler()
  103. def get_perms(filename):
  104. mode = stat.S_IMODE(os.stat(filename)[stat.ST_MODE])
  105. permsString = ''
  106. permSet = 0
  107. place = 2
  108. for who in "USR", "GRP", "OTH":
  109. for what in "R", "W", "X":
  110. if mode & getattr(stat,"S_I"+what+who):
  111. permSet = permSet + 2**place
  112. place = place - 1
  113. permsString = "%s%s" % (permsString, permSet)
  114. permSet = 0
  115. place = 2
  116. permSet = 0
  117. for permFlag in setUGV.keys():
  118. if mode & getattr(stat, permFlag):
  119. permSet = permSet + 2**setUGV[permFlag]
  120. permsString = "%s%s" % (permSet, permsString)
  121. return permsString
  122. def local_fqdn():
  123. """Return a system's true FQDN rather than any aliases, which are
  124. occasionally returned by socket.gethostname."""
  125. fqdn = None
  126. me = os.uname()[1]
  127. nameInfo=socket.gethostbyname_ex(me)
  128. nameInfo[1].append(nameInfo[0])
  129. for name in nameInfo[1]:
  130. if name.count(".") and name.startswith(me):
  131. fqdn = name
  132. if fqdn == None:
  133. fqdn = me
  134. return(fqdn)
  135. def need_to_allocate(allocated, config, command):
  136. status = True
  137. if allocated.isSet():
  138. status = False
  139. elif re.search("\s*dfs.*$", command) and \
  140. config['gridservice-hdfs']['external']:
  141. status = False
  142. elif config['gridservice-mapred']['external']:
  143. status = False
  144. return status
  145. def filter_warnings():
  146. warnings.filterwarnings('ignore',
  147. message=".*?'with' will become a reserved keyword.*")
  148. def args_to_string(list):
  149. """return a string argument space seperated"""
  150. arg = ''
  151. for item in list:
  152. arg = "%s%s " % (arg, item)
  153. return arg[:-1]
  154. def replace_escapes(object):
  155. """ replace any escaped character. e.g \, with , \= with = and so on """
  156. # here object is either a config object or a options object
  157. for section in object._mySections:
  158. for option in object._configDef[section].keys():
  159. if object[section].has_key(option):
  160. if object._configDef[section][option]['type'] == 'keyval':
  161. keyValDict = object[section][option]
  162. object[section][option] = {}
  163. for (key,value) in keyValDict.iteritems():
  164. match = reEscapeSeq.search(value)
  165. if match:
  166. value = reEscapeSeq.sub(r"\1", value)
  167. object[section][option][key] = value
  168. def hadoopVersion(hadoopDir, java_home, log):
  169. # Determine the version of hadoop being used by executing the
  170. # hadoop version command. Code earlier in idleTracker.py
  171. hadoopVersion = { 'major' : None, 'minor' : None }
  172. hadoopPath = os.path.join(hadoopDir, 'bin', 'hadoop')
  173. cmd = "%s version" % hadoopPath
  174. log.debug('Executing command %s to find hadoop version' % cmd)
  175. env = os.environ
  176. env['JAVA_HOME'] = java_home
  177. hadoopVerCmd = simpleCommand('HadoopVersion', cmd, env)
  178. hadoopVerCmd.start()
  179. hadoopVerCmd.wait()
  180. hadoopVerCmd.join()
  181. if hadoopVerCmd.exit_code() == 0:
  182. verLine = hadoopVerCmd.output()[0]
  183. log.debug('Version from hadoop command: %s' % verLine)
  184. hadoopVerRegExp = re.compile("Hadoop ([0-9]+)\.([0-9]+).*")
  185. verMatch = hadoopVerRegExp.match(verLine)
  186. if verMatch != None:
  187. hadoopVersion['major'] = verMatch.group(1)
  188. hadoopVersion['minor'] = verMatch.group(2)
  189. return hadoopVersion
  190. def get_cluster_status(hdfsAddress, mapredAddress):
  191. """Determine the status of the cluster based on socket availability
  192. of HDFS and Map/Reduce."""
  193. status = 0
  194. mapredSocket = tcpSocket(mapredAddress)
  195. try:
  196. mapredSocket.open()
  197. mapredSocket.close()
  198. except tcpError:
  199. status = 14
  200. hdfsSocket = tcpSocket(hdfsAddress)
  201. try:
  202. hdfsSocket.open()
  203. hdfsSocket.close()
  204. except tcpError:
  205. if status > 0:
  206. status = 10
  207. else:
  208. status = 13
  209. return status
  210. def parseEquals(list):
  211. # takes in a list of keyval pairs e.g ['a=b','c=d'] and returns a
  212. # dict e.g {'a'='b','c'='d'}. Used in GridService/{mapred.py/hdfs.py} and
  213. # HodRing/hodring.py. No need for specially treating escaped =. as in \=,
  214. # since all keys are generated by hod and don't contain such anomalies
  215. dict = {}
  216. for elems in list:
  217. splits = elems.split('=')
  218. dict[splits[0]] = splits[1]
  219. return dict
  220. def getMapredSystemDirectory(mrSysDirRoot, userid, jobid):
  221. return os.path.join(mrSysDirRoot, userid, 'mapredsystem', jobid)
  222. class HodInterrupt:
  223. def __init__(self):
  224. self.HodInterruptFlag = False
  225. self.log = None
  226. def set_log(self, log):
  227. self.log = log
  228. def init_signals(self):
  229. def sigStop(sigNum, handler):
  230. sig_wrapper(sigNum, self.setFlag)
  231. signal.signal(signal.SIGTERM, sigStop) # 15 : software termination signal
  232. signal.signal(signal.SIGQUIT, sigStop) # 3 : Quit program
  233. signal.signal(signal.SIGINT, sigStop) # 2 ^C : Interrupt program
  234. def sig_wrapper(sigNum, handler, *args):
  235. self.log.critical("Caught signal %s." % sigNum )
  236. if args:
  237. handler(args)
  238. else:
  239. handler()
  240. def setFlag(self, val = True):
  241. self.HodInterruptFlag = val
  242. def isSet(self):
  243. return self.HodInterruptFlag
  244. class HodInterruptException(Exception):
  245. def __init__(self, value = ""):
  246. self.value = value
  247. def __str__(self):
  248. return repr(self.value)
  249. hodInterrupt = HodInterrupt()