CustomServiceOrchestrator.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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 logging
  18. import os
  19. import ambari_simplejson as json
  20. import sys
  21. from ambari_commons import shell
  22. import threading
  23. from FileCache import FileCache
  24. from AgentException import AgentException
  25. from PythonExecutor import PythonExecutor
  26. from PythonReflectiveExecutor import PythonReflectiveExecutor
  27. from resource_management.core.utils import PasswordString
  28. import subprocess
  29. import Constants
  30. import hostname
  31. logger = logging.getLogger()
  32. class CustomServiceOrchestrator():
  33. """
  34. Executes a command for custom service. stdout and stderr are written to
  35. tmpoutfile and to tmperrfile respectively.
  36. """
  37. SCRIPT_TYPE_PYTHON = "PYTHON"
  38. COMMAND_TYPE = "commandType"
  39. COMMAND_NAME_STATUS = "STATUS"
  40. COMMAND_NAME_SECURITY_STATUS = "SECURITY_STATUS"
  41. CUSTOM_ACTION_COMMAND = 'ACTIONEXECUTE'
  42. CUSTOM_COMMAND_COMMAND = 'CUSTOM_COMMAND'
  43. PRE_HOOK_PREFIX="before"
  44. POST_HOOK_PREFIX="after"
  45. HOSTS_LIST_KEY = "all_hosts"
  46. PING_PORTS_KEY = "all_ping_ports"
  47. RACKS_KEY = "all_racks"
  48. IPV4_ADDRESSES_KEY = "all_ipv4_ips"
  49. AMBARI_SERVER_HOST = "ambari_server_host"
  50. AMBARI_SERVER_PORT = "ambari_server_port"
  51. AMBARI_SERVER_USE_SSL = "ambari_server_use_ssl"
  52. FREQUENT_COMMANDS = [COMMAND_NAME_SECURITY_STATUS, COMMAND_NAME_STATUS]
  53. DONT_DEBUG_FAILURES_FOR_COMMANDS = FREQUENT_COMMANDS
  54. REFLECTIVELY_RUN_COMMANDS = FREQUENT_COMMANDS # -- commands which run a lot and often (this increases their speed)
  55. DONT_BACKUP_LOGS_FOR_COMMANDS = FREQUENT_COMMANDS
  56. # Path where hadoop credential JARS will be available
  57. DEFAULT_CREDENTIAL_SHELL_LIB_PATH = '/var/lib/ambari-agent/cred/lib'
  58. DEFAULT_CREDENTIAL_CONF_DIR = '/var/lib/ambari-agent/cred/conf'
  59. DEFAULT_CREDENTIAL_SHELL_CMD = 'org.apache.hadoop.security.alias.CredentialShell'
  60. def __init__(self, config, controller):
  61. self.config = config
  62. self.tmp_dir = config.get('agent', 'prefix')
  63. self.exec_tmp_dir = Constants.AGENT_TMP_DIR
  64. self.file_cache = FileCache(config)
  65. self.status_commands_stdout = os.path.join(self.tmp_dir,
  66. 'status_command_stdout.txt')
  67. self.status_commands_stderr = os.path.join(self.tmp_dir,
  68. 'status_command_stderr.txt')
  69. self.public_fqdn = hostname.public_hostname(config)
  70. # cache reset will be called on every agent registration
  71. controller.registration_listeners.append(self.file_cache.reset)
  72. # Construct the hadoop credential lib JARs path
  73. self.credential_shell_lib_path = os.path.join(config.get('security', 'credential_lib_dir',
  74. self.DEFAULT_CREDENTIAL_SHELL_LIB_PATH), '*')
  75. self.credential_conf_dir = config.get('security', 'credential_conf_dir', self.DEFAULT_CREDENTIAL_CONF_DIR)
  76. self.credential_shell_cmd = config.get('security', 'credential_shell_cmd', self.DEFAULT_CREDENTIAL_SHELL_CMD)
  77. # Clean up old status command files if any
  78. try:
  79. os.unlink(self.status_commands_stdout)
  80. os.unlink(self.status_commands_stderr)
  81. except OSError:
  82. pass # Ignore fail
  83. self.commands_in_progress_lock = threading.RLock()
  84. self.commands_in_progress = {}
  85. def map_task_to_process(self, task_id, processId):
  86. with self.commands_in_progress_lock:
  87. logger.debug('Maps taskId=%s to pid=%s' % (task_id, processId))
  88. self.commands_in_progress[task_id] = processId
  89. def cancel_command(self, task_id, reason):
  90. with self.commands_in_progress_lock:
  91. if task_id in self.commands_in_progress.keys():
  92. pid = self.commands_in_progress.get(task_id)
  93. self.commands_in_progress[task_id] = reason
  94. logger.info("Canceling command with taskId = {tid}, " \
  95. "reason - {reason} . Killing process {pid}"
  96. .format(tid=str(task_id), reason=reason, pid=pid))
  97. shell.kill_process_with_children(pid)
  98. else:
  99. logger.warn("Unable to find process associated with taskId = %s" % task_id)
  100. def get_py_executor(self, forced_command_name):
  101. """
  102. Wrapper for unit testing
  103. :return:
  104. """
  105. if forced_command_name in self.REFLECTIVELY_RUN_COMMANDS:
  106. return PythonReflectiveExecutor(self.tmp_dir, self.config)
  107. else:
  108. return PythonExecutor(self.tmp_dir, self.config)
  109. def getProviderDirectory(self, service_name):
  110. """
  111. Gets the path to the service conf folder where the JCEKS file will be created.
  112. :param service_name: Name of the service, for example, HIVE
  113. :return: lower case path to the service conf folder
  114. """
  115. # The stack definition scripts of the service can move the
  116. # JCEKS file around to where it wants, which is usually
  117. # /etc/<service_name>/conf
  118. conf_dir = os.path.join(self.credential_conf_dir, service_name.lower())
  119. if not os.path.exists(conf_dir):
  120. os.makedirs(conf_dir, 0644)
  121. return conf_dir
  122. def getAffectedConfigTypes(self, commandJson):
  123. """
  124. Gets the affected config types for the service in this command
  125. :param commandJson:
  126. :return:
  127. """
  128. return commandJson.get('configuration_attributes')
  129. def getCredentialProviderPropertyName(self):
  130. """
  131. Gets the property name used by the hadoop credential provider
  132. :return:
  133. """
  134. return 'hadoop.security.credential.provider.path'
  135. def generateJceks(self, commandJson):
  136. """
  137. Generates the JCEKS file with passwords for the service specified in commandJson
  138. :param commandJson: command JSON
  139. :return: An exit value from the external process that generated the JCEKS file. None if
  140. there are no passwords in the JSON.
  141. """
  142. cmd_result = None
  143. roleCommand = None
  144. if 'roleCommand' in commandJson:
  145. roleCommand = commandJson['roleCommand']
  146. logger.info('generateJceks: roleCommand={0}'.format(roleCommand))
  147. # Password properties for a config type, if present,
  148. # are under configuration_attributes:config_type:hidden:{prop1:attributes1, prop2, attributes2}
  149. passwordProperties = {}
  150. config_types = self.getAffectedConfigTypes(commandJson)
  151. for config_type in config_types:
  152. elem = config_types.get(config_type)
  153. hidden = elem.get('hidden')
  154. if hidden is not None:
  155. passwordProperties[config_type] = hidden
  156. # Set up the variables for the external command to generate a JCEKS file
  157. java_home = commandJson['hostLevelParams']['java_home']
  158. java_bin = '{java_home}/bin/java'.format(java_home=java_home)
  159. cs_lib_path = self.credential_shell_lib_path
  160. serviceName = commandJson['serviceName']
  161. # Gather the password values and remove them from the configuration
  162. configs = commandJson.get('configurations')
  163. for key, value in passwordProperties.items():
  164. config = configs.get(key)
  165. if config is not None:
  166. file_path = os.path.join(self.getProviderDirectory(serviceName), "{0}.jceks".format(key))
  167. if os.path.exists(file_path):
  168. os.remove(file_path)
  169. provider_path = 'jceks://file{file_path}'.format(file_path=file_path)
  170. logger.info('provider_path={0}'.format(provider_path))
  171. for alias in value:
  172. pwd = config.get(alias)
  173. if pwd is not None:
  174. # Remove the clear text password
  175. config.pop(alias, None)
  176. # Add JCEKS provider path instead
  177. config[self.getCredentialProviderPropertyName()] = provider_path
  178. logger.debug("config={0}".format(config))
  179. protected_pwd = PasswordString(pwd)
  180. # Generate the JCEKS file
  181. cmd = (java_bin, '-cp', cs_lib_path, self.credential_shell_cmd, 'create',
  182. alias, '-value', protected_pwd, '-provider', provider_path)
  183. logger.info(cmd)
  184. cmd_result = subprocess.call(cmd)
  185. logger.info('cmd_result = {0}'.format(cmd_result))
  186. os.chmod(file_path, 0644) # group and others should have read access so that the service user can read
  187. return cmd_result
  188. def runCommand(self, command, tmpoutfile, tmperrfile, forced_command_name=None,
  189. override_output_files=True, retry=False):
  190. """
  191. forced_command_name may be specified manually. In this case, value, defined at
  192. command json, is ignored.
  193. """
  194. try:
  195. script_type = command['commandParams']['script_type']
  196. script = command['commandParams']['script']
  197. timeout = int(command['commandParams']['command_timeout'])
  198. if 'hostLevelParams' in command and 'jdk_location' in command['hostLevelParams']:
  199. server_url_prefix = command['hostLevelParams']['jdk_location']
  200. else:
  201. server_url_prefix = command['commandParams']['jdk_location']
  202. task_id = "status"
  203. try:
  204. task_id = command['taskId']
  205. command_name = command['roleCommand']
  206. except KeyError:
  207. pass # Status commands have no taskId
  208. if forced_command_name is not None: # If not supplied as an argument
  209. command_name = forced_command_name
  210. if command_name == self.CUSTOM_ACTION_COMMAND:
  211. base_dir = self.file_cache.get_custom_actions_base_dir(server_url_prefix)
  212. script_tuple = (os.path.join(base_dir, 'scripts', script), base_dir)
  213. hook_dir = None
  214. else:
  215. if command_name == self.CUSTOM_COMMAND_COMMAND:
  216. command_name = command['hostLevelParams']['custom_command']
  217. # forces a hash challenge on the directories to keep them updated, even
  218. # if the return type is not used
  219. self.file_cache.get_host_scripts_base_dir(server_url_prefix)
  220. hook_dir = self.file_cache.get_hook_base_dir(command, server_url_prefix)
  221. base_dir = self.file_cache.get_service_base_dir(command, server_url_prefix)
  222. from ActionQueue import ActionQueue # To avoid cyclic dependency
  223. if self.COMMAND_TYPE in command and command[self.COMMAND_TYPE] == ActionQueue.EXECUTION_COMMAND:
  224. logger.info("Found it - " + str(command[self.COMMAND_TYPE]) + " yeah")
  225. # limiting to only EXECUTION_COMMANDs for now
  226. # TODO need a design for limiting to specific role/component such as METRICS_GRAFANA
  227. self.file_cache.get_dashboard_base_dir(server_url_prefix)
  228. script_path = self.resolve_script_path(base_dir, script)
  229. script_tuple = (script_path, base_dir)
  230. tmpstrucoutfile = os.path.join(self.tmp_dir,
  231. "structured-out-{0}.json".format(task_id))
  232. # We don't support anything else yet
  233. if script_type.upper() != self.SCRIPT_TYPE_PYTHON:
  234. message = "Unknown script type {0}".format(script_type)
  235. raise AgentException(message)
  236. # Execute command using proper interpreter
  237. handle = None
  238. if command.has_key('__handle'):
  239. handle = command['__handle']
  240. handle.on_background_command_started = self.map_task_to_process
  241. del command['__handle']
  242. # If command contains credentialStoreEnabled, then
  243. # generate the JCEKS file for the configurations.
  244. credentialStoreEnabled = False
  245. if 'credentialStoreEnabled' in command:
  246. credentialStoreEnabled = (command['credentialStoreEnabled'] == "true")
  247. if credentialStoreEnabled == True:
  248. self.generateJceks(command)
  249. json_path = self.dump_command_to_json(command, retry)
  250. pre_hook_tuple = self.resolve_hook_script_path(hook_dir,
  251. self.PRE_HOOK_PREFIX, command_name, script_type)
  252. post_hook_tuple = self.resolve_hook_script_path(hook_dir,
  253. self.POST_HOOK_PREFIX, command_name, script_type)
  254. py_file_list = [pre_hook_tuple, script_tuple, post_hook_tuple]
  255. # filter None values
  256. filtered_py_file_list = [i for i in py_file_list if i]
  257. logger_level = logging.getLevelName(logger.level)
  258. # Executing hooks and script
  259. ret = None
  260. from ActionQueue import ActionQueue
  261. if command.has_key('commandType') and command['commandType'] == ActionQueue.BACKGROUND_EXECUTION_COMMAND and len(filtered_py_file_list) > 1:
  262. raise AgentException("Background commands are supported without hooks only")
  263. python_executor = self.get_py_executor(forced_command_name)
  264. backup_log_files = not command_name in self.DONT_BACKUP_LOGS_FOR_COMMANDS
  265. log_out_files = self.config.get("logging","log_out_files", default="0") != "0"
  266. for py_file, current_base_dir in filtered_py_file_list:
  267. log_info_on_failure = not command_name in self.DONT_DEBUG_FAILURES_FOR_COMMANDS
  268. script_params = [command_name, json_path, current_base_dir, tmpstrucoutfile, logger_level, self.exec_tmp_dir]
  269. if log_out_files:
  270. script_params.append("-o")
  271. ret = python_executor.run_file(py_file, script_params,
  272. tmpoutfile, tmperrfile, timeout,
  273. tmpstrucoutfile, self.map_task_to_process,
  274. task_id, override_output_files, backup_log_files = backup_log_files,
  275. handle = handle, log_info_on_failure=log_info_on_failure)
  276. # Next run_file() invocations should always append to current output
  277. override_output_files = False
  278. if ret['exitcode'] != 0:
  279. break
  280. if not ret: # Something went wrong
  281. raise AgentException("No script has been executed")
  282. # if canceled and not background command
  283. if handle is None:
  284. cancel_reason = self.command_canceled_reason(task_id)
  285. if cancel_reason is not None:
  286. ret['stdout'] += cancel_reason
  287. ret['stderr'] += cancel_reason
  288. with open(tmpoutfile, "a") as f:
  289. f.write(cancel_reason)
  290. with open(tmperrfile, "a") as f:
  291. f.write(cancel_reason)
  292. except Exception, e: # We do not want to let agent fail completely
  293. exc_type, exc_obj, exc_tb = sys.exc_info()
  294. message = "Caught an exception while executing "\
  295. "custom service command: {0}: {1}; {2}".format(exc_type, exc_obj, str(e))
  296. logger.exception(message)
  297. ret = {
  298. 'stdout' : message,
  299. 'stderr' : message,
  300. 'structuredOut' : '{}',
  301. 'exitcode': 1,
  302. }
  303. return ret
  304. def command_canceled_reason(self, task_id):
  305. with self.commands_in_progress_lock:
  306. if self.commands_in_progress.has_key(task_id):#Background command do not push in this collection (TODO)
  307. logger.debug('Pop with taskId %s' % task_id)
  308. pid = self.commands_in_progress.pop(task_id)
  309. if not isinstance(pid, int):
  310. reason = pid
  311. if reason:
  312. return "\nCommand aborted. Reason: '{0}'".format(reason)
  313. else:
  314. return "\nCommand aborted."
  315. return None
  316. def requestComponentStatus(self, command):
  317. """
  318. Component status is determined by exit code, returned by runCommand().
  319. Exit code 0 means that component is running and any other exit code means that
  320. component is not running
  321. """
  322. override_output_files=True # by default, we override status command output
  323. if logger.level == logging.DEBUG:
  324. override_output_files = False
  325. res = self.runCommand(command, self.status_commands_stdout,
  326. self.status_commands_stderr, self.COMMAND_NAME_STATUS,
  327. override_output_files=override_output_files)
  328. return res
  329. def requestComponentSecurityState(self, command):
  330. """
  331. Determines the current security state of the component
  332. A command will be issued to trigger the security_status check and the result of this check will
  333. returned to the caller. If the component lifecycle script has no security_status method the
  334. check will return non zero exit code and "UNKNOWN" will be returned.
  335. """
  336. override_output_files=True # by default, we override status command output
  337. if logger.level == logging.DEBUG:
  338. override_output_files = False
  339. security_check_res = self.runCommand(command, self.status_commands_stdout,
  340. self.status_commands_stderr, self.COMMAND_NAME_SECURITY_STATUS,
  341. override_output_files=override_output_files)
  342. result = 'UNKNOWN'
  343. if security_check_res is None:
  344. logger.warn("The return value of the security_status check was empty, the security status is unknown")
  345. elif 'exitcode' not in security_check_res:
  346. logger.warn("Missing 'exitcode' value from the security_status check result, the security status is unknown")
  347. elif security_check_res['exitcode'] != 0:
  348. logger.debug("The 'exitcode' value from the security_status check result indicated the check routine failed to properly execute, the security status is unknown")
  349. elif 'structuredOut' not in security_check_res:
  350. logger.warn("Missing 'structuredOut' value from the security_status check result, the security status is unknown")
  351. elif 'securityState' not in security_check_res['structuredOut']:
  352. logger.warn("Missing 'securityState' value from the security_status check structuredOut data set, the security status is unknown")
  353. else:
  354. result = security_check_res['structuredOut']['securityState']
  355. return result
  356. def resolve_script_path(self, base_dir, script):
  357. """
  358. Encapsulates logic of script location determination.
  359. """
  360. path = os.path.join(base_dir, script)
  361. if not os.path.exists(path):
  362. message = "Script {0} does not exist".format(path)
  363. raise AgentException(message)
  364. return path
  365. def resolve_hook_script_path(self, stack_hooks_dir, prefix, command_name, script_type):
  366. """
  367. Returns a tuple(path to hook script, hook base dir) according to string prefix
  368. and command name. If script does not exist, returns None
  369. """
  370. if not stack_hooks_dir:
  371. return None
  372. hook_dir = "{0}-{1}".format(prefix, command_name)
  373. hook_base_dir = os.path.join(stack_hooks_dir, hook_dir)
  374. hook_script_path = os.path.join(hook_base_dir, "scripts", "hook.py")
  375. if not os.path.isfile(hook_script_path):
  376. logger.debug("Hook script {0} not found, skipping".format(hook_script_path))
  377. return None
  378. return hook_script_path, hook_base_dir
  379. def dump_command_to_json(self, command, retry=False):
  380. """
  381. Converts command to json file and returns file path
  382. """
  383. # Perform few modifications to stay compatible with the way in which
  384. public_fqdn = self.public_fqdn
  385. command['public_hostname'] = public_fqdn
  386. # Add cache dir to make it visible for commands
  387. command["hostLevelParams"]["agentCacheDir"] = self.config.get('agent', 'cache_dir')
  388. command["agentConfigParams"] = {"agent": {"parallel_execution": self.config.get_parallel_exec_option()}}
  389. # Now, dump the json file
  390. command_type = command['commandType']
  391. from ActionQueue import ActionQueue # To avoid cyclic dependency
  392. if command_type == ActionQueue.STATUS_COMMAND:
  393. # These files are frequently created, that's why we don't
  394. # store them all, but only the latest one
  395. file_path = os.path.join(self.tmp_dir, "status_command.json")
  396. else:
  397. task_id = command['taskId']
  398. if 'clusterHostInfo' in command and command['clusterHostInfo'] and not retry:
  399. command['clusterHostInfo'] = self.decompressClusterHostInfo(command['clusterHostInfo'])
  400. file_path = os.path.join(self.tmp_dir, "command-{0}.json".format(task_id))
  401. if command_type == ActionQueue.AUTO_EXECUTION_COMMAND:
  402. file_path = os.path.join(self.tmp_dir, "auto_command-{0}.json".format(task_id))
  403. # Json may contain passwords, that's why we need proper permissions
  404. if os.path.isfile(file_path):
  405. os.unlink(file_path)
  406. with os.fdopen(os.open(file_path, os.O_WRONLY | os.O_CREAT,
  407. 0600), 'w') as f:
  408. content = json.dumps(command, sort_keys = False, indent = 4)
  409. f.write(content)
  410. return file_path
  411. def decompressClusterHostInfo(self, clusterHostInfo):
  412. info = clusterHostInfo.copy()
  413. #Pop info not related to host roles
  414. hostsList = info.pop(self.HOSTS_LIST_KEY)
  415. pingPorts = info.pop(self.PING_PORTS_KEY)
  416. racks = info.pop(self.RACKS_KEY)
  417. ipv4_addresses = info.pop(self.IPV4_ADDRESSES_KEY)
  418. ambariServerHost = info.pop(self.AMBARI_SERVER_HOST)
  419. ambariServerPort = info.pop(self.AMBARI_SERVER_PORT)
  420. ambariServerUseSsl = info.pop(self.AMBARI_SERVER_USE_SSL)
  421. decompressedMap = {}
  422. for k,v in info.items():
  423. # Convert from 1-3,5,6-8 to [1,2,3,5,6,7,8]
  424. indexes = self.convertRangeToList(v)
  425. # Convert from [1,2,3,5,6,7,8] to [host1,host2,host3...]
  426. decompressedMap[k] = [hostsList[i] for i in indexes]
  427. #Convert from ['1:0-2,4', '42:3,5-7'] to [1,1,1,42,1,42,42,42]
  428. pingPorts = self.convertMappedRangeToList(pingPorts)
  429. racks = self.convertMappedRangeToList(racks)
  430. ipv4_addresses = self.convertMappedRangeToList(ipv4_addresses)
  431. #Convert all elements to str
  432. pingPorts = map(str, pingPorts)
  433. #Add ping ports to result
  434. decompressedMap[self.PING_PORTS_KEY] = pingPorts
  435. #Add hosts list to result
  436. decompressedMap[self.HOSTS_LIST_KEY] = hostsList
  437. #Add racks list to result
  438. decompressedMap[self.RACKS_KEY] = racks
  439. #Add ips list to result
  440. decompressedMap[self.IPV4_ADDRESSES_KEY] = ipv4_addresses
  441. #Add ambari-server properties to result
  442. decompressedMap[self.AMBARI_SERVER_HOST] = ambariServerHost
  443. decompressedMap[self.AMBARI_SERVER_PORT] = ambariServerPort
  444. decompressedMap[self.AMBARI_SERVER_USE_SSL] = ambariServerUseSsl
  445. return decompressedMap
  446. # Converts from 1-3,5,6-8 to [1,2,3,5,6,7,8]
  447. def convertRangeToList(self, list):
  448. resultList = []
  449. for i in list:
  450. ranges = i.split(',')
  451. for r in ranges:
  452. rangeBounds = r.split('-')
  453. if len(rangeBounds) == 2:
  454. if not rangeBounds[0] or not rangeBounds[1]:
  455. raise AgentException("Broken data in given range, expected - ""m-n"" or ""m"", got : " + str(r))
  456. resultList.extend(range(int(rangeBounds[0]), int(rangeBounds[1]) + 1))
  457. elif len(rangeBounds) == 1:
  458. resultList.append((int(rangeBounds[0])))
  459. else:
  460. raise AgentException("Broken data in given range, expected - ""m-n"" or ""m"", got : " + str(r))
  461. return resultList
  462. #Converts from ['1:0-2,4', '42:3,5-7'] to [1,1,1,42,1,42,42,42]
  463. def convertMappedRangeToList(self, list):
  464. resultDict = {}
  465. for i in list:
  466. valueToRanges = i.split(":")
  467. if len(valueToRanges) <> 2:
  468. raise AgentException("Broken data in given value to range, expected format - ""value:m-n"", got - " + str(i))
  469. value = valueToRanges[0]
  470. rangesToken = valueToRanges[1]
  471. for r in rangesToken.split(','):
  472. rangeIndexes = r.split('-')
  473. if len(rangeIndexes) == 2:
  474. if not rangeIndexes[0] or not rangeIndexes[1]:
  475. raise AgentException("Broken data in given value to range, expected format - ""value:m-n"", got - " + str(r))
  476. start = int(rangeIndexes[0])
  477. end = int(rangeIndexes[1])
  478. for k in range(start, end + 1):
  479. resultDict[k] = value if not value.isdigit() else int(value)
  480. elif len(rangeIndexes) == 1:
  481. index = int(rangeIndexes[0])
  482. resultDict[index] = value if not value.isdigit() else int(value)
  483. resultList = dict(sorted(resultDict.items())).values()
  484. return resultList