hodRing.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. #!/usr/bin/env python
  15. """hodring launches hadoop commands on work node and
  16. cleans up all the work dirs afterward
  17. """
  18. # -*- python -*-
  19. import os, sys, time, shutil, getpass, xml.dom.minidom, xml.dom.pulldom
  20. import socket, sets, urllib, csv, signal, pprint, random, re, httplib
  21. from xml.dom import getDOMImplementation
  22. from pprint import pformat
  23. from optparse import OptionParser
  24. from urlparse import urlparse
  25. from hodlib.Common.util import local_fqdn, parseEquals, getMapredSystemDirectory, isProcessRunning
  26. from hodlib.Common.tcp import tcpSocket, tcpError
  27. binfile = sys.path[0]
  28. libdir = os.path.dirname(binfile)
  29. sys.path.append(libdir)
  30. import hodlib.Common.logger
  31. from hodlib.GridServices.service import *
  32. from hodlib.Common.util import *
  33. from hodlib.Common.socketServers import threadedHTTPServer
  34. from hodlib.Common.hodsvc import hodBaseService
  35. from hodlib.Common.threads import simpleCommand
  36. from hodlib.Common.xmlrpc import hodXRClient
  37. mswindows = (sys.platform == "win32")
  38. originalcwd = os.getcwd()
  39. reHdfsURI = re.compile("hdfs://(.*?:\d+)(.*)")
  40. class CommandDesc:
  41. """A class that represents the commands that
  42. are run by hodring"""
  43. def __init__(self, dict, log):
  44. self.log = log
  45. self.log.debug("In command desc")
  46. self.log.debug("Done in command desc")
  47. dict.setdefault('argv', [])
  48. dict.setdefault('version', None)
  49. dict.setdefault('envs', {})
  50. dict.setdefault('workdirs', [])
  51. dict.setdefault('attrs', {})
  52. dict.setdefault('final-attrs', {})
  53. dict.setdefault('fg', False)
  54. dict.setdefault('ignorefailures', False)
  55. dict.setdefault('stdin', None)
  56. self.log.debug("Printing dict")
  57. self._checkRequired(dict)
  58. self.dict = dict
  59. def _checkRequired(self, dict):
  60. if 'name' not in dict:
  61. raise ValueError, "Command description lacks 'name'"
  62. if 'program' not in dict:
  63. raise ValueError, "Command description lacks 'program'"
  64. if 'pkgdirs' not in dict:
  65. raise ValueError, "Command description lacks 'pkgdirs'"
  66. def getName(self):
  67. return self.dict['name']
  68. def getProgram(self):
  69. return self.dict['program']
  70. def getArgv(self):
  71. return self.dict['argv']
  72. def getVersion(self):
  73. return self.dict['version']
  74. def getEnvs(self):
  75. return self.dict['envs']
  76. def getPkgDirs(self):
  77. return self.dict['pkgdirs']
  78. def getWorkDirs(self):
  79. return self.dict['workdirs']
  80. def getAttrs(self):
  81. return self.dict['attrs']
  82. def getfinalAttrs(self):
  83. return self.dict['final-attrs']
  84. def isForeground(self):
  85. return self.dict['fg']
  86. def isIgnoreFailures(self):
  87. return self.dict['ignorefailures']
  88. def getStdin(self):
  89. return self.dict['stdin']
  90. def parseDesc(str):
  91. dict = CommandDesc._parseMap(str)
  92. dict['argv'] = CommandDesc._parseList(dict['argv'])
  93. dict['envs'] = CommandDesc._parseMap(dict['envs'])
  94. dict['pkgdirs'] = CommandDesc._parseList(dict['pkgdirs'], ':')
  95. dict['workdirs'] = CommandDesc._parseList(dict['workdirs'], ':')
  96. dict['attrs'] = CommandDesc._parseMap(dict['attrs'])
  97. dict['final-attrs'] = CommandDesc._parseMap(dict['final-attrs'])
  98. return CommandDesc(dict)
  99. parseDesc = staticmethod(parseDesc)
  100. def _parseList(str, delim = ','):
  101. list = []
  102. for row in csv.reader([str], delimiter=delim, escapechar='\\',
  103. quoting=csv.QUOTE_NONE, doublequote=False):
  104. list.extend(row)
  105. return list
  106. _parseList = staticmethod(_parseList)
  107. def _parseMap(str):
  108. """Parses key value pairs"""
  109. dict = {}
  110. for row in csv.reader([str], escapechar='\\', quoting=csv.QUOTE_NONE, doublequote=False):
  111. for f in row:
  112. [k, v] = f.split('=', 1)
  113. dict[k] = v
  114. return dict
  115. _parseMap = staticmethod(_parseMap)
  116. class MRSystemDirectoryManager:
  117. """Class that is responsible for managing the MapReduce system directory"""
  118. def __init__(self, jtPid, mrSysDir, fsName, hadoopPath, log, retries=120):
  119. self.__jtPid = jtPid
  120. self.__mrSysDir = mrSysDir
  121. self.__fsName = fsName
  122. self.__hadoopPath = hadoopPath
  123. self.__log = log
  124. self.__retries = retries
  125. def toCleanupArgs(self):
  126. return " --jt-pid %s --mr-sys-dir %s --fs-name %s --hadoop-path %s " \
  127. % (self.__jtPid, self.__mrSysDir, self.__fsName, self.__hadoopPath)
  128. def removeMRSystemDirectory(self):
  129. jtActive = isProcessRunning(self.__jtPid)
  130. count = 0 # try for a max of a minute for the process to end
  131. while jtActive and (count<self.__retries):
  132. time.sleep(0.5)
  133. jtActive = isProcessRunning(self.__jtPid)
  134. count += 1
  135. if count == self.__retries:
  136. self.__log.warn('Job Tracker did not exit even after a minute. Not going to try and cleanup the system directory')
  137. return
  138. self.__log.debug('jt is now inactive')
  139. cmd = "%s dfs -fs hdfs://%s -rmr %s" % (self.__hadoopPath, self.__fsName, \
  140. self.__mrSysDir)
  141. self.__log.debug('Command to run to remove system directory: %s' % (cmd))
  142. try:
  143. hadoopCommand = simpleCommand('mr-sys-dir-cleaner', cmd)
  144. hadoopCommand.start()
  145. hadoopCommand.wait()
  146. hadoopCommand.join()
  147. ret = hadoopCommand.exit_code()
  148. if ret != 0:
  149. self.__log.warn("Error in removing MapReduce system directory '%s' from '%s' using path '%s'" \
  150. % (self.__mrSysDir, self.__fsName, self.__hadoopPath))
  151. self.__log.warn(pprint.pformat(hadoopCommand.output()))
  152. else:
  153. self.__log.info("Removed MapReduce system directory successfully.")
  154. except:
  155. self.__log.error('Exception while cleaning up MapReduce system directory. May not be cleaned up. %s', \
  156. get_exception_error_string())
  157. self.__log.debug(get_exception_string())
  158. def createMRSystemDirectoryManager(dict, log):
  159. keys = [ 'jt-pid', 'mr-sys-dir', 'fs-name', 'hadoop-path' ]
  160. for key in keys:
  161. if (not dict.has_key(key)) or (dict[key] is None):
  162. return None
  163. mrSysDirManager = MRSystemDirectoryManager(int(dict['jt-pid']), dict['mr-sys-dir'], \
  164. dict['fs-name'], dict['hadoop-path'], log)
  165. return mrSysDirManager
  166. class HadoopCommand:
  167. """Runs a single hadoop command"""
  168. def __init__(self, id, desc, tempdir, tardir, log, javahome,
  169. mrSysDir, restart=False):
  170. self.desc = desc
  171. self.log = log
  172. self.javahome = javahome
  173. self.__mrSysDir = mrSysDir
  174. self.program = desc.getProgram()
  175. self.name = desc.getName()
  176. self.workdirs = desc.getWorkDirs()
  177. self.hadoopdir = tempdir
  178. self.confdir = os.path.join(self.hadoopdir, '%d-%s' % (id, self.name),
  179. "confdir")
  180. self.logdir = os.path.join(self.hadoopdir, '%d-%s' % (id, self.name),
  181. "logdir")
  182. self.child = None
  183. self.restart = restart
  184. self.filledInKeyVals = []
  185. self._createWorkDirs()
  186. self._createHadoopSiteXml()
  187. self._createHadoopLogDir()
  188. self.__hadoopThread = None
  189. def _createWorkDirs(self):
  190. for dir in self.workdirs:
  191. if os.path.exists(dir):
  192. if not os.access(dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK):
  193. raise ValueError, "Workdir %s does not allow rwx permission." % (dir)
  194. continue
  195. try:
  196. os.makedirs(dir)
  197. except:
  198. pass
  199. def getFilledInKeyValues(self):
  200. return self.filledInKeyVals
  201. def createXML(self, doc, attr, topElement, final):
  202. for k,v in attr.iteritems():
  203. self.log.debug('_createHadoopSiteXml: ' + str(k) + " " + str(v))
  204. if ( v == "fillinport" ):
  205. v = "%d" % (ServiceUtil.getUniqRandomPort(low=50000, log=self.log))
  206. keyvalpair = ''
  207. if isinstance(v, (tuple, list)):
  208. for item in v:
  209. keyvalpair = "%s%s=%s," % (keyvalpair, k, item)
  210. keyvalpair = keyvalpair[:-1]
  211. else:
  212. keyvalpair = k + '=' + v
  213. self.filledInKeyVals.append(keyvalpair)
  214. if(k == "mapred.job.tracker"): # total hack for time's sake
  215. keyvalpair = k + "=" + v
  216. self.filledInKeyVals.append(keyvalpair)
  217. if ( v == "fillinhostport"):
  218. port = "%d" % (ServiceUtil.getUniqRandomPort(low=50000, log=self.log))
  219. self.log.debug('Setting hostname to: %s' % local_fqdn())
  220. v = local_fqdn() + ':' + port
  221. keyvalpair = ''
  222. if isinstance(v, (tuple, list)):
  223. for item in v:
  224. keyvalpair = "%s%s=%s," % (keyvalpair, k, item)
  225. keyvalpair = keyvalpair[:-1]
  226. else:
  227. keyvalpair = k + '=' + v
  228. self.filledInKeyVals.append(keyvalpair)
  229. if ( v == "fillindir"):
  230. v = self.__mrSysDir
  231. pass
  232. prop = None
  233. if isinstance(v, (tuple, list)):
  234. for item in v:
  235. prop = self._createXmlElement(doc, k, item, "No description", final)
  236. topElement.appendChild(prop)
  237. else:
  238. if k == 'fs.default.name':
  239. prop = self._createXmlElement(doc, k, "hdfs://" + v, "No description", final)
  240. else:
  241. prop = self._createXmlElement(doc, k, v, "No description", final)
  242. topElement.appendChild(prop)
  243. def _createHadoopSiteXml(self):
  244. if self.restart:
  245. if not os.path.exists(self.confdir):
  246. os.makedirs(self.confdir)
  247. else:
  248. assert os.path.exists(self.confdir) == False
  249. os.makedirs(self.confdir)
  250. implementation = getDOMImplementation()
  251. doc = implementation.createDocument('', 'configuration', None)
  252. comment = doc.createComment("This is an auto generated hadoop-site.xml, do not modify")
  253. topElement = doc.documentElement
  254. topElement.appendChild(comment)
  255. finalAttr = self.desc.getfinalAttrs()
  256. self.createXML(doc, finalAttr, topElement, True)
  257. attr = {}
  258. attr1 = self.desc.getAttrs()
  259. for k,v in attr1.iteritems():
  260. if not finalAttr.has_key(k):
  261. attr[k] = v
  262. self.createXML(doc, attr, topElement, False)
  263. siteName = os.path.join(self.confdir, "hadoop-site.xml")
  264. sitefile = file(siteName, 'w')
  265. print >> sitefile, topElement.toxml()
  266. sitefile.close()
  267. self.log.debug('created %s' % (siteName))
  268. def _createHadoopLogDir(self):
  269. if self.restart:
  270. if not os.path.exists(self.logdir):
  271. os.makedirs(self.logdir)
  272. else:
  273. assert os.path.exists(self.logdir) == False
  274. os.makedirs(self.logdir)
  275. def _createXmlElement(self, doc, name, value, description, final):
  276. prop = doc.createElement("property")
  277. nameP = doc.createElement("name")
  278. string = doc.createTextNode(name)
  279. nameP.appendChild(string)
  280. valueP = doc.createElement("value")
  281. string = doc.createTextNode(value)
  282. valueP.appendChild(string)
  283. desc = doc.createElement("description")
  284. string = doc.createTextNode(description)
  285. desc.appendChild(string)
  286. prop.appendChild(nameP)
  287. prop.appendChild(valueP)
  288. prop.appendChild(desc)
  289. if (final):
  290. felement = doc.createElement("final")
  291. string = doc.createTextNode("true")
  292. felement.appendChild(string)
  293. prop.appendChild(felement)
  294. pass
  295. return prop
  296. def getMRSystemDirectoryManager(self):
  297. return MRSystemDirectoryManager(self.__hadoopThread.getPid(), self.__mrSysDir, \
  298. self.desc.getfinalAttrs()['fs.default.name'], \
  299. self.path, self.log)
  300. def run(self, dir):
  301. status = True
  302. args = []
  303. desc = self.desc
  304. self.log.debug(pprint.pformat(desc.dict))
  305. self.log.debug("Got package dir of %s" % dir)
  306. self.path = os.path.join(dir, self.program)
  307. self.log.debug("path: %s" % self.path)
  308. args.append(self.path)
  309. args.extend(desc.getArgv())
  310. envs = desc.getEnvs()
  311. fenvs = os.environ
  312. for k, v in envs.iteritems():
  313. fenvs[k] = v
  314. if envs.has_key('HADOOP_OPTS'):
  315. fenvs['HADOOP_OPTS'] = envs['HADOOP_OPTS']
  316. self.log.debug("HADOOP_OPTS : %s" % fenvs['HADOOP_OPTS'])
  317. fenvs['JAVA_HOME'] = self.javahome
  318. fenvs['HADOOP_CONF_DIR'] = self.confdir
  319. fenvs['HADOOP_LOG_DIR'] = self.logdir
  320. self.log.info(pprint.pformat(fenvs))
  321. hadoopCommand = ''
  322. for item in args:
  323. hadoopCommand = "%s%s " % (hadoopCommand, item)
  324. self.log.debug('running command: %s' % (hadoopCommand))
  325. self.log.debug('hadoop env: %s' % fenvs)
  326. self.__hadoopThread = simpleCommand('hadoop', hadoopCommand, env=fenvs)
  327. self.__hadoopThread.start()
  328. while self.__hadoopThread.stdin == None:
  329. time.sleep(.2)
  330. self.log.debug("hadoopThread still == None ...")
  331. input = desc.getStdin()
  332. self.log.debug("hadoop input: %s" % input)
  333. if input:
  334. if self.__hadoopThread.is_running():
  335. print >>self.__hadoopThread.stdin, input
  336. else:
  337. self.log.error("hadoop command failed to start")
  338. self.__hadoopThread.stdin.close()
  339. self.log.debug("isForground: %s" % desc.isForeground())
  340. if desc.isForeground():
  341. self.log.debug("Waiting on hadoop to finish...")
  342. self.__hadoopThread.wait()
  343. self.log.debug("Joining hadoop thread...")
  344. self.__hadoopThread.join()
  345. if self.__hadoopThread.exit_code() != 0:
  346. status = False
  347. else:
  348. code = self.__hadoopThread.exit_code()
  349. if code != 0 and code != None:
  350. status = False
  351. self.log.debug("hadoop run status: %s" % status)
  352. if status == False:
  353. for item in self.__hadoopThread.output():
  354. self.log.error(item)
  355. self.log.error('hadoop error: %s' % (
  356. self.__hadoopThread.exit_status_string()))
  357. if (status == True) or (not desc.isIgnoreFailures()):
  358. return status
  359. else:
  360. self.log.error("Ignoring Failure")
  361. return True
  362. def kill(self):
  363. self.__hadoopThread.kill()
  364. if self.__hadoopThread:
  365. self.__hadoopThread.join()
  366. def addCleanup(self, list):
  367. list.extend(self.workdirs)
  368. list.append(self.confdir)
  369. class HodRing(hodBaseService):
  370. """The main class for hodring that
  371. polls the commands it runs"""
  372. def __init__(self, config):
  373. hodBaseService.__init__(self, 'hodring', config['hodring'])
  374. self.log = self.logs['main']
  375. self._http = None
  376. self.__pkg = None
  377. self.__pkgDir = None
  378. self.__tempDir = None
  379. self.__running = {}
  380. self.__hadoopLogDirs = []
  381. self.__init_temp_dir()
  382. def __init_temp_dir(self):
  383. self.__tempDir = os.path.join(self._cfg['temp-dir'],
  384. "%s.%s.hodring" % (self._cfg['userid'],
  385. self._cfg['service-id']))
  386. if not os.path.exists(self.__tempDir):
  387. os.makedirs(self.__tempDir)
  388. os.chdir(self.__tempDir)
  389. def __fetch(self, url, spath):
  390. retry = 3
  391. success = False
  392. while (retry != 0 and success != True):
  393. try:
  394. input = urllib.urlopen(url)
  395. bufsz = 81920
  396. buf = input.read(bufsz)
  397. out = open(spath, 'w')
  398. while len(buf) > 0:
  399. out.write(buf)
  400. buf = input.read(bufsz)
  401. input.close()
  402. out.close()
  403. success = True
  404. except:
  405. self.log.debug("Failed to copy file")
  406. retry = retry - 1
  407. if (retry == 0 and success != True):
  408. raise IOError, "Failed to copy the files"
  409. def __get_name(self, addr):
  410. parsedUrl = urlparse(addr)
  411. path = parsedUrl[2]
  412. split = path.split('/', 1)
  413. return split[1]
  414. def __get_dir(self, name):
  415. """Return the root directory inside the tarball
  416. specified by name. Assumes that the tarball begins
  417. with a root directory."""
  418. import tarfile
  419. myTarFile = tarfile.open(name)
  420. hadoopPackage = myTarFile.getnames()[0]
  421. self.log.debug("tarball name : %s hadoop package name : %s" %(name,hadoopPackage))
  422. return hadoopPackage
  423. def getRunningValues(self):
  424. return self.__running.values()
  425. def getTempDir(self):
  426. return self.__tempDir
  427. def getHadoopLogDirs(self):
  428. return self.__hadoopLogDirs
  429. def __download_package(self, ringClient):
  430. self.log.debug("Found download address: %s" %
  431. self._cfg['download-addr'])
  432. try:
  433. addr = 'none'
  434. downloadTime = self._cfg['tarball-retry-initial-time'] # download time depends on tarball size and network bandwidth
  435. increment = 0
  436. addr = ringClient.getTarList(self.hostname)
  437. while(addr == 'none'):
  438. rand = self._cfg['tarball-retry-initial-time'] + increment + \
  439. random.uniform(0,self._cfg['tarball-retry-interval'])
  440. increment = increment + 1
  441. self.log.debug("got no tarball. Retrying again in %s seconds." % rand)
  442. time.sleep(rand)
  443. addr = ringClient.getTarList(self.hostname)
  444. self.log.debug("got this address %s" % addr)
  445. tarName = self.__get_name(addr)
  446. self.log.debug("tar package name: %s" % tarName)
  447. fetchPath = os.path.join(os.getcwd(), tarName)
  448. self.log.debug("fetch path: %s" % fetchPath)
  449. self.__fetch(addr, fetchPath)
  450. self.log.debug("done fetching")
  451. tarUrl = "http://%s:%d/%s" % (self._http.server_address[0],
  452. self._http.server_address[1],
  453. tarName)
  454. try:
  455. ringClient.registerTarSource(self.hostname, tarUrl,addr)
  456. #ringClient.tarDone(addr)
  457. except KeyError, e:
  458. self.log.error("registerTarSource and tarDone failed: ", e)
  459. raise KeyError(e)
  460. check = untar(fetchPath, os.getcwd())
  461. if (check == False):
  462. raise IOError, "Untarring failed."
  463. self.__pkg = self.__get_dir(tarName)
  464. self.__pkgDir = os.path.join(os.getcwd(), self.__pkg)
  465. except Exception, e:
  466. self.log.error("Failed download tar package: %s" %
  467. get_exception_error_string())
  468. raise Exception(e)
  469. def __run_hadoop_commands(self, restart=True):
  470. id = 0
  471. for desc in self._cfg['commanddesc']:
  472. self.log.debug(pprint.pformat(desc.dict))
  473. mrSysDir = getMapredSystemDirectory(self._cfg['mapred-system-dir-root'],
  474. self._cfg['userid'], self._cfg['service-id'])
  475. self.log.debug('mrsysdir is %s' % mrSysDir)
  476. cmd = HadoopCommand(id, desc, self.__tempDir, self.__pkgDir, self.log,
  477. self._cfg['java-home'], mrSysDir, restart)
  478. self.__hadoopLogDirs.append(cmd.logdir)
  479. self.log.debug("hadoop log directory: %s" % self.__hadoopLogDirs)
  480. try:
  481. # if the tarball isn't there, we use the pkgs dir given.
  482. if self.__pkgDir == None:
  483. pkgdir = desc.getPkgDirs()
  484. else:
  485. pkgdir = self.__pkgDir
  486. self.log.debug('This is the packcage dir %s ' % (pkgdir))
  487. if not cmd.run(pkgdir):
  488. raise ValueError, "Can't launch command: %s" % pkgdir
  489. except Exception, e:
  490. print get_exception_string()
  491. self.__running[id] = cmd
  492. raise Exception(e)
  493. id += 1
  494. if desc.isForeground():
  495. continue
  496. self.__running[id-1] = cmd
  497. # ok.. now command is running. If this HodRing got jobtracker,
  498. # Check if it is ready for accepting jobs, and then only return
  499. self.__check_jobtracker(desc, id-1)
  500. def __check_jobtracker(self, desc, id):
  501. # Check jobtracker status. Return properly if it is ready to accept jobs.
  502. # Currently Checks for Jetty to come up, the last thing that can be checked
  503. # before JT completes initialisation. To be perfectly reliable, we need
  504. # hadoop support
  505. name = desc.getName()
  506. if name == 'jobtracker':
  507. # Yes I am the Jobtracker
  508. self.log.debug("Waiting for jobtracker to initialise")
  509. version = desc.getVersion()
  510. self.log.debug("jobtracker version : %s" % version)
  511. attrs = self.getRunningValues()[id].getFilledInKeyValues()
  512. attrs = parseEquals(attrs)
  513. jobTrackerAddr = attrs['mapred.job.tracker']
  514. self.log.debug("jobtracker rpc server : %s" % jobTrackerAddr)
  515. if version < 16:
  516. jettyAddr = jobTrackerAddr.split(':')[0] + ':' + \
  517. attrs['mapred.job.tracker.info.port']
  518. else:
  519. jettyAddr = attrs['mapred.job.tracker.http.address']
  520. self.log.debug("Jobtracker jetty : %s" % jettyAddr)
  521. # Check for Jetty to come up
  522. # For this do a http head, and then look at the status
  523. defaultTimeout = socket.getdefaulttimeout()
  524. # socket timeout isn`t exposed at httplib level. Setting explicitly.
  525. socket.setdefaulttimeout(1)
  526. sleepTime = 0.5
  527. jettyStatus = False
  528. jettyStatusmsg = ""
  529. while sleepTime <= 32:
  530. try:
  531. jettyConn = httplib.HTTPConnection(jettyAddr)
  532. jettyConn.request("HEAD", "/jobtracker.jsp")
  533. # httplib inherently retries the following till socket timeout
  534. resp = jettyConn.getresponse()
  535. if resp.status != 200:
  536. # Some problem?
  537. jettyStatus = False
  538. jettyStatusmsg = "Jetty gave a non-200 response to a HTTP-HEAD" +\
  539. " request. HTTP Status (Code, Msg): (%s, %s)" % \
  540. ( resp.status, resp.reason )
  541. break
  542. else:
  543. self.log.info("Jetty returned a 200 status (%s)" % resp.reason)
  544. self.log.info("JobTracker successfully initialised")
  545. return
  546. except socket.error:
  547. self.log.debug("Jetty gave a socket error. Sleeping for %s" \
  548. % sleepTime)
  549. time.sleep(sleepTime)
  550. sleepTime = sleepTime * 2
  551. except Exception, e:
  552. jettyStatus = False
  553. jettyStatusmsg = ("Process(possibly other than jetty) running on" + \
  554. " port assigned to jetty is returning invalid http response")
  555. break
  556. socket.setdefaulttimeout(defaultTimeout)
  557. if not jettyStatus:
  558. self.log.critical("Jobtracker failed to initialise.")
  559. if jettyStatusmsg:
  560. self.log.critical( "Reason: %s" % jettyStatusmsg )
  561. else: self.log.critical( "Reason: Jetty failed to give response")
  562. raise Exception("JobTracker failed to initialise")
  563. def stop(self):
  564. self.log.debug("Entered hodring stop.")
  565. if self._http:
  566. self.log.debug("stopping http server...")
  567. self._http.stop()
  568. self.log.debug("call hodsvcrgy stop...")
  569. hodBaseService.stop(self)
  570. def _xr_method_clusterStart(self, initialize=True):
  571. return self.clusterStart(initialize)
  572. def _xr_method_clusterStop(self):
  573. return self.clusterStop()
  574. def start(self):
  575. """Run and maintain hodring commands"""
  576. try:
  577. if self._cfg.has_key('download-addr'):
  578. self._http = threadedHTTPServer('', self._cfg['http-port-range'])
  579. self.log.info("Starting http server...")
  580. self._http.serve_forever()
  581. self.log.debug("http://%s:%d" % (self._http.server_address[0],
  582. self._http.server_address[1]))
  583. hodBaseService.start(self)
  584. ringXRAddress = None
  585. if self._cfg.has_key('ringmaster-xrs-addr'):
  586. ringXRAddress = "http://%s:%s/" % (self._cfg['ringmaster-xrs-addr'][0],
  587. self._cfg['ringmaster-xrs-addr'][1])
  588. self.log.debug("Ringmaster at %s" % ringXRAddress)
  589. self.log.debug("Creating service registry XML-RPC client.")
  590. serviceClient = hodXRClient(to_http_url(
  591. self._cfg['svcrgy-addr']))
  592. if ringXRAddress == None:
  593. self.log.info("Did not get ringmaster XML-RPC address. Fetching information from service registry.")
  594. ringList = serviceClient.getServiceInfo(self._cfg['userid'],
  595. self._cfg['service-id'], 'ringmaster', 'hod')
  596. self.log.debug(pprint.pformat(ringList))
  597. if len(ringList):
  598. if isinstance(ringList, list):
  599. ringXRAddress = ringList[0]['xrs']
  600. count = 0
  601. while (ringXRAddress == None and count < 3000):
  602. ringList = serviceClient.getServiceInfo(self._cfg['userid'],
  603. self._cfg['service-id'], 'ringmaster', 'hod')
  604. if len(ringList):
  605. if isinstance(ringList, list):
  606. ringXRAddress = ringList[0]['xrs']
  607. count = count + 1
  608. time.sleep(.2)
  609. if ringXRAddress == None:
  610. raise Exception("Could not get ringmaster XML-RPC server address.")
  611. self.log.debug("Creating ringmaster XML-RPC client.")
  612. ringClient = hodXRClient(ringXRAddress)
  613. id = self.hostname + "_" + str(os.getpid())
  614. if 'download-addr' in self._cfg:
  615. self.__download_package(ringClient)
  616. else:
  617. self.log.debug("Did not find a download address.")
  618. cmdlist = []
  619. firstTime = True
  620. increment = 0
  621. hadoopStartupTime = 2
  622. cmdlist = ringClient.getCommand(id)
  623. while (cmdlist == []):
  624. if firstTime:
  625. sleepTime = increment + self._cfg['cmd-retry-initial-time'] + hadoopStartupTime\
  626. + random.uniform(0,self._cfg['cmd-retry-interval'])
  627. firstTime = False
  628. else:
  629. sleepTime = increment + self._cfg['cmd-retry-initial-time'] + \
  630. + random.uniform(0,self._cfg['cmd-retry-interval'])
  631. self.log.debug("Did not get command list. Waiting for %s seconds." % (sleepTime))
  632. time.sleep(sleepTime)
  633. increment = increment + 1
  634. cmdlist = ringClient.getCommand(id)
  635. self.log.debug(pformat(cmdlist))
  636. cmdDescs = []
  637. for cmds in cmdlist:
  638. cmdDescs.append(CommandDesc(cmds['dict'], self.log))
  639. self._cfg['commanddesc'] = cmdDescs
  640. self.log.info("Running hadoop commands...")
  641. self.__run_hadoop_commands(False)
  642. masterParams = []
  643. for k, cmd in self.__running.iteritems():
  644. masterParams.extend(cmd.filledInKeyVals)
  645. self.log.debug("printing getparams")
  646. self.log.debug(pformat(id))
  647. self.log.debug(pformat(masterParams))
  648. # when this is on a required host, the ringMaster already has our masterParams
  649. if(len(masterParams) > 0):
  650. ringClient.addMasterParams(id, masterParams)
  651. except Exception, e:
  652. raise Exception(e)
  653. def clusterStart(self, initialize=True):
  654. """Start a stopped mapreduce/dfs cluster"""
  655. if initialize:
  656. self.log.debug('clusterStart Method Invoked - Initialize')
  657. else:
  658. self.log.debug('clusterStart Method Invoked - No Initialize')
  659. try:
  660. self.log.debug("Creating service registry XML-RPC client.")
  661. serviceClient = hodXRClient(to_http_url(self._cfg['svcrgy-addr']),
  662. None, None, 0, 0, 0)
  663. self.log.info("Fetching ringmaster information from service registry.")
  664. count = 0
  665. ringXRAddress = None
  666. while (ringXRAddress == None and count < 3000):
  667. ringList = serviceClient.getServiceInfo(self._cfg['userid'],
  668. self._cfg['service-id'], 'ringmaster', 'hod')
  669. if len(ringList):
  670. if isinstance(ringList, list):
  671. ringXRAddress = ringList[0]['xrs']
  672. count = count + 1
  673. if ringXRAddress == None:
  674. raise Exception("Could not get ringmaster XML-RPC server address.")
  675. self.log.debug("Creating ringmaster XML-RPC client.")
  676. ringClient = hodXRClient(ringXRAddress, None, None, 0, 0, 0)
  677. id = self.hostname + "_" + str(os.getpid())
  678. cmdlist = []
  679. if initialize:
  680. if 'download-addr' in self._cfg:
  681. self.__download_package(ringClient)
  682. else:
  683. self.log.debug("Did not find a download address.")
  684. while (cmdlist == []):
  685. cmdlist = ringClient.getCommand(id)
  686. else:
  687. while (cmdlist == []):
  688. cmdlist = ringClient.getAdminCommand(id)
  689. self.log.debug(pformat(cmdlist))
  690. cmdDescs = []
  691. for cmds in cmdlist:
  692. cmdDescs.append(CommandDesc(cmds['dict'], self.log))
  693. self._cfg['commanddesc'] = cmdDescs
  694. if initialize:
  695. self.log.info("Running hadoop commands again... - Initialize")
  696. self.__run_hadoop_commands()
  697. masterParams = []
  698. for k, cmd in self.__running.iteritems():
  699. self.log.debug(cmd)
  700. masterParams.extend(cmd.filledInKeyVals)
  701. self.log.debug("printing getparams")
  702. self.log.debug(pformat(id))
  703. self.log.debug(pformat(masterParams))
  704. # when this is on a required host, the ringMaster already has our masterParams
  705. if(len(masterParams) > 0):
  706. ringClient.addMasterParams(id, masterParams)
  707. else:
  708. self.log.info("Running hadoop commands again... - No Initialize")
  709. self.__run_hadoop_commands()
  710. except:
  711. self.log.error(get_exception_string())
  712. return True
  713. def clusterStop(self):
  714. """Stop a running mapreduce/dfs cluster without stopping the hodring"""
  715. self.log.debug('clusterStop Method Invoked')
  716. try:
  717. for cmd in self.__running.values():
  718. cmd.kill()
  719. self.__running = {}
  720. except:
  721. self.log.error(get_exception_string())
  722. return True