util.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. '''
  2. /*#############################################################################
  3. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. ############################################################################ */
  14. '''
  15. import argparse
  16. import platform
  17. import logging
  18. import os
  19. import subprocess
  20. from ..common.error import Error
  21. from ..common.shell import Shell
  22. from ..common.config import Config
  23. def isPositiveIntNum(string):
  24. for i in range(0, len(string)):
  25. if (string[i] < '0') or (string[i] > '9'):
  26. return False
  27. return True
  28. def checkPqParam(string):
  29. param = str(string)
  30. if isPositiveIntNum(string) or (string == '-1'):
  31. value = int(string)
  32. else:
  33. msg = "Wrong value of threadNumber parameter: '"+string+"' !"
  34. raise argparse.ArgumentTypeError(msg)
  35. return value
  36. def checkXParam(string):
  37. param=str(string)
  38. if len(param):
  39. if ('=' in param) or ('None' == param):
  40. value = param
  41. else:
  42. #logging.error("%s. Missing or wrong argument '%s' after -X parameter!\nIt should be 'name=val[,name2=val2..]'\n5000\n" % (1, param))
  43. value="5000"
  44. else:
  45. msg = "Missing argument of -X parameter!"
  46. raise argparse.ArgumentTypeError(msg)
  47. return value
  48. def getVersionNumbers():
  49. version = platform.python_version_tuple()
  50. verNum = {'main':0, 'minor':0, 'patch':0}
  51. if isPositiveIntNum(version[0]):
  52. verNum['main'] = int(version[0])
  53. if isPositiveIntNum(version[1]):
  54. verNum['minor'] = int(version[1])
  55. if isPositiveIntNum(version[2]):
  56. verNum['patch'] = int(version[2])
  57. return(verNum);
  58. def parentPath(osPath):
  59. # remove current dir
  60. [osPath, sep, curDir] = osPath.rpartition(os.sep)
  61. return osPath
  62. def convertPath(osPath):
  63. hpccPath = ''
  64. osPath = osPath.lstrip(os.sep)
  65. osPath = osPath.replace(os.sep, '::')
  66. for i in range(0, len(osPath)):
  67. if osPath[i] >= 'A' and osPath[i] <= 'Z':
  68. hpccPath = hpccPath +'^'
  69. hpccPath = hpccPath +osPath[i]
  70. return hpccPath
  71. import json
  72. import urllib2
  73. gConfig = None
  74. def setConfig(config):
  75. global gConfig
  76. gConfig = config
  77. def getConfig():
  78. return gConfig
  79. def queryWuid(jobname, taskId):
  80. shell = Shell()
  81. cmd = shell.which('ecl')
  82. defaults = []
  83. args = []
  84. args.append('status')
  85. args.append('-v')
  86. args.append('-n=' + jobname)
  87. args.append('--server=' + gConfig.ip)
  88. args.append('--username=' + gConfig.username)
  89. args.append('--password=' + gConfig.password)
  90. res = shell.command(cmd, *defaults)(*args)
  91. logging.debug("%3d. queryWuid(%s, cmd :'%s') result is: '%s'", taskId, jobname, cmd, res)
  92. wuid = "Not found"
  93. state = 'N/A'
  94. result = 'Fail'
  95. if len(res):
  96. resultItems = res.split(',')
  97. if len(resultItems) == 3:
  98. result = 'OK'
  99. for resultItem in resultItems:
  100. resultItem = resultItem.strip()
  101. [key, val] = resultItem.split(':')
  102. if key == 'ID':
  103. wuid = val
  104. if key == 'state':
  105. state = val
  106. return {'wuid':wuid, 'state':state, 'result':result}
  107. def abortWorkunit(wuid):
  108. shell = Shell()
  109. cmd = shell.which('ecl')
  110. defaults=[]
  111. args = []
  112. args.append('abort')
  113. args.append('-wu=' + wuid)
  114. args.append('--server=' + gConfig.ip)
  115. args.append('--username=' + gConfig.username)
  116. args.append('--password=' + gConfig.password)
  117. state=shell.command(cmd, *defaults)(*args)
  118. return state
  119. import subprocess
  120. def getRealIPAddress():
  121. ipAddress = '127.0.0.1'
  122. found = False
  123. try:
  124. proc = subprocess.Popen(['ip', '-o', '-4', 'addr', 'show'], shell=False, bufsize=8192, stdout=subprocess.PIPE, stderr=None)
  125. result = proc.communicate()[0]
  126. results = result.split('\n')
  127. for line in results:
  128. if 'scope global' in line:
  129. items = line.split()
  130. ipAddress = items[3].split('/')[0]
  131. found = True
  132. break;
  133. if not found:
  134. for line in results:
  135. items = line.split()
  136. ipAddress = items[3].split('/')[0]
  137. break;
  138. except OSError:
  139. pass
  140. finally:
  141. pass
  142. return ipAddress
  143. def checkClusters(clusters, targetSet):
  144. targetClusters =[]
  145. if 'all' in clusters:
  146. for cluster in gConfig.Clusters:
  147. targetClusters.append(str(cluster))
  148. else:
  149. for cluster in clusters:
  150. cluster = cluster.strip()
  151. if cluster in gConfig.Clusters:
  152. targetClusters.append(cluster)
  153. else:
  154. logging.error("%s. Unknown cluster:'%s' in %s:'%s'!" % (1, cluster, targetSet, clusters))
  155. raise Error("4000")
  156. return targetClusters
  157. def isLocalIP(ip):
  158. retVal=False
  159. if '127.0.0.1' == ip:
  160. retVal = True
  161. elif ip == getRealIPAddress():
  162. retVal = True
  163. return retVal
  164. def checkHpccStatus(targets):
  165. # Check HPCC Systems status on all local/remote target
  166. isLocal = False
  167. isLocalChecked = False
  168. isIpChecked={}
  169. config = getConfig()
  170. for target in targets:
  171. ip = config.IpAddress[target]
  172. if not ip in isIpChecked:
  173. isIpChecked[ip] = False
  174. isLocal = isLocalIP(ip)
  175. if isIpChecked[ip] or (isLocal and isLocalChecked):
  176. continue
  177. try:
  178. if isLocal:
  179. # There is no remote version (yet)
  180. myProc = subprocess.Popen(["ecl --version"], shell=True, bufsize=8192, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  181. result = myProc.stdout.read() + myProc.stderr.read()
  182. results = result.split('\n')
  183. for line in results:
  184. if 'not found' in line:
  185. err = Error("6000")
  186. logging.error("%s. %s:'%s'" % (1, err, line))
  187. raise err
  188. break
  189. myProc = subprocess.Popen("ecl getname --wuid 'W*' --limit=5 --server="+ip, shell=True, bufsize=8192, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  190. result = myProc.stdout.read() + myProc.stderr.read()
  191. results = result.split('\n')
  192. for line in results:
  193. if "Error connecting" in line:
  194. if isLocal:
  195. err = Error("6001")
  196. logging.error("%s. %s:'%s local %s target!'" % (1, err, line, target))
  197. raise (err)
  198. else:
  199. err = Error("6004")
  200. logging.error("%s. %s:'%s remote %s target!'" % (1, err, line, target))
  201. raise (err)
  202. break
  203. if "command not found" in line:
  204. err = Error("6002")
  205. logging.error("%s. %s:'%s'" % (1, err, line))
  206. raise (err)
  207. break
  208. if isLocal:
  209. isLocalChecked = True
  210. isIpChecked[ip] = True
  211. except OSError:
  212. err = Error("6002")
  213. logging.error("%s. checkHpccStatus error:%s!" % (1, err))
  214. raise Error(err)
  215. except ValueError:
  216. err = Error("6003")
  217. logging.error("%s. checkHpccStatus error:%s!" % (1, err))
  218. raise Error(err)
  219. finally:
  220. pass