bindcmd.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. # Copyright (C) 2009 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. """This module holds the BindCmdInterpreter class. This provides the
  16. core functionality for bindctl. It maintains a session with
  17. b10-cmdctl, holds local configuration and module information, and
  18. handles command line interface commands"""
  19. import sys
  20. from cmd import Cmd
  21. from bindctl.exception import *
  22. from bindctl.moduleinfo import *
  23. from bindctl.cmdparse import BindCmdParse
  24. from xml.dom import minidom
  25. import isc
  26. import isc.cc.data
  27. import http.client
  28. import json
  29. import inspect
  30. import pprint
  31. import ssl, socket
  32. import os, time, random, re
  33. import getpass
  34. from hashlib import sha1
  35. import csv
  36. import pwd
  37. import getpass
  38. try:
  39. from collections import OrderedDict
  40. except ImportError:
  41. from bindctl.mycollections import OrderedDict
  42. # if we have readline support, use that, otherwise use normal stdio
  43. try:
  44. import readline
  45. my_readline = readline.get_line_buffer
  46. except ImportError:
  47. my_readline = sys.stdin.readline
  48. CSV_FILE_NAME = 'default_user.csv'
  49. CONFIG_MODULE_NAME = 'config'
  50. CONST_BINDCTL_HELP = """
  51. usage: <module name> <command name> [param1 = value1 [, param2 = value2]]
  52. Type Tab character to get the hint of module/command/parameters.
  53. Type \"help(? h)\" for help on bindctl.
  54. Type \"<module_name> help\" for help on the specific module.
  55. Type \"<module_name> <command_name> help\" for help on the specific command.
  56. \nAvailable module names: """
  57. class ValidatedHTTPSConnection(http.client.HTTPSConnection):
  58. '''Overrides HTTPSConnection to support certification
  59. validation. '''
  60. def __init__(self, host, ca_certs):
  61. http.client.HTTPSConnection.__init__(self, host)
  62. self.ca_certs = ca_certs
  63. def connect(self):
  64. ''' Overrides the connect() so that we do
  65. certificate validation. '''
  66. sock = socket.create_connection((self.host, self.port),
  67. self.timeout)
  68. if self._tunnel_host:
  69. self.sock = sock
  70. self._tunnel()
  71. req_cert = ssl.CERT_NONE
  72. if self.ca_certs:
  73. req_cert = ssl.CERT_REQUIRED
  74. self.sock = ssl.wrap_socket(sock, self.key_file,
  75. self.cert_file,
  76. cert_reqs=req_cert,
  77. ca_certs=self.ca_certs)
  78. class BindCmdInterpreter(Cmd):
  79. """simple bindctl example."""
  80. def __init__(self, server_port = 'localhost:8080', pem_file = None):
  81. Cmd.__init__(self)
  82. self.location = ""
  83. self.prompt_end = '> '
  84. if sys.stdin.isatty():
  85. self.prompt = self.prompt_end
  86. else:
  87. self.prompt = ""
  88. self.ruler = '-'
  89. self.modules = OrderedDict()
  90. self.add_module_info(ModuleInfo("help", desc = "Get help for bindctl"))
  91. self.server_port = server_port
  92. self.conn = ValidatedHTTPSConnection(self.server_port,
  93. ca_certs=pem_file)
  94. self.session_id = self._get_session_id()
  95. self.config_data = None
  96. def _get_session_id(self):
  97. '''Generate one session id for the connection. '''
  98. rand = os.urandom(16)
  99. now = time.time()
  100. session_id = sha1(("%s%s%s" %(rand, now,
  101. socket.gethostname())).encode())
  102. digest = session_id.hexdigest()
  103. return digest
  104. def run(self):
  105. '''Parse commands from user and send them to cmdctl. '''
  106. try:
  107. if not self.login_to_cmdctl():
  108. return
  109. self.cmdloop()
  110. except FailToLogin as err:
  111. # error already printed when this was raised, ignoring
  112. pass
  113. except KeyboardInterrupt:
  114. print('\nExit from bindctl')
  115. def _get_saved_user_info(self, dir, file_name):
  116. ''' Read all the available username and password pairs saved in
  117. file(path is "dir + file_name"), Return value is one list of elements
  118. ['name', 'password'], If get information failed, empty list will be
  119. returned.'''
  120. if (not dir) or (not os.path.exists(dir)):
  121. return []
  122. try:
  123. csvfile = None
  124. users = []
  125. csvfile = open(dir + file_name)
  126. users_info = csv.reader(csvfile)
  127. for row in users_info:
  128. users.append([row[0], row[1]])
  129. except (IOError, IndexError) as err:
  130. print("Error reading saved username and password from %s%s: %s" % (dir, file_name, err))
  131. finally:
  132. if csvfile:
  133. csvfile.close()
  134. return users
  135. def _save_user_info(self, username, passwd, dir, file_name):
  136. ''' Save username and password in file "dir + file_name"
  137. If it's saved properly, return True, or else return False. '''
  138. try:
  139. if not os.path.exists(dir):
  140. os.mkdir(dir, 0o700)
  141. csvfilepath = dir + file_name
  142. csvfile = open(csvfilepath, 'w')
  143. os.chmod(csvfilepath, 0o600)
  144. writer = csv.writer(csvfile)
  145. writer.writerow([username, passwd])
  146. csvfile.close()
  147. except IOError as err:
  148. print("Error saving user information:", err)
  149. print("user info file name: %s%s" % (dir, file_name))
  150. return False
  151. return True
  152. def login_to_cmdctl(self):
  153. '''Login to cmdctl with the username and password inputted
  154. from user. After the login is sucessful, the username and
  155. password will be saved in 'default_user.csv', when run the next
  156. time, username and password saved in 'default_user.csv' will be
  157. used first.
  158. '''
  159. csv_file_dir = pwd.getpwnam(getpass.getuser()).pw_dir
  160. csv_file_dir += os.sep + '.bind10' + os.sep
  161. users = self._get_saved_user_info(csv_file_dir, CSV_FILE_NAME)
  162. for row in users:
  163. param = {'username': row[0], 'password' : row[1]}
  164. try:
  165. response = self.send_POST('/login', param)
  166. data = response.read().decode()
  167. except socket.error as err:
  168. print("Socket error while sending login information:", err)
  169. raise FailToLogin()
  170. if response.status == http.client.OK:
  171. print(data + ' login as ' + row[0] )
  172. return True
  173. count = 0
  174. print("[TEMP MESSAGE]: username :root password :bind10")
  175. while True:
  176. count = count + 1
  177. if count > 3:
  178. print("Too many authentication failures")
  179. return False
  180. username = input("Username:")
  181. passwd = getpass.getpass()
  182. param = {'username': username, 'password' : passwd}
  183. try:
  184. response = self.send_POST('/login', param)
  185. data = response.read().decode()
  186. print(data)
  187. except socket.error as err:
  188. print("Socket error while sending login information:", err)
  189. raise FailToLogin()
  190. if response.status == http.client.OK:
  191. self._save_user_info(username, passwd, csv_file_dir, CSV_FILE_NAME)
  192. return True
  193. def _update_commands(self):
  194. '''Update the commands of all modules. '''
  195. for module_name in self.config_data.get_config_item_list():
  196. self._prepare_module_commands(self.config_data.get_module_spec(module_name))
  197. def _send_message(self, url, body):
  198. headers = {"cookie" : self.session_id}
  199. self.conn.request('GET', url, body, headers)
  200. res = self.conn.getresponse()
  201. return res.status, res.read()
  202. def send_GET(self, url, body = None):
  203. '''Send GET request to cmdctl, session id is send with the name
  204. 'cookie' in header.
  205. '''
  206. status, reply_msg = self._send_message(url, body)
  207. if status == http.client.UNAUTHORIZED:
  208. if self.login_to_cmdctl():
  209. # successful, so try send again
  210. status, reply_msg = self._send_message(url, body)
  211. if reply_msg:
  212. return json.loads(reply_msg.decode())
  213. else:
  214. return {}
  215. def send_POST(self, url, post_param = None):
  216. '''Send POST request to cmdctl, session id is send with the name
  217. 'cookie' in header.
  218. Format: /module_name/command_name
  219. parameters of command is encoded as a map
  220. '''
  221. param = None
  222. if (len(post_param) != 0):
  223. param = json.dumps(post_param)
  224. headers = {"cookie" : self.session_id}
  225. self.conn.request('POST', url, param, headers)
  226. return self.conn.getresponse()
  227. def _update_all_modules_info(self):
  228. ''' Get all modules' information from cmdctl, including
  229. specification file and configuration data. This function
  230. should be called before interpreting command line or complete-key
  231. is entered. This may not be the best way to keep bindctl
  232. and cmdctl share same modules information, but it works.'''
  233. if self.config_data is not None:
  234. self.config_data.update_specs_and_config()
  235. else:
  236. self.config_data = isc.config.UIModuleCCSession(self)
  237. self._update_commands()
  238. def precmd(self, line):
  239. self._update_all_modules_info()
  240. return line
  241. def postcmd(self, stop, line):
  242. '''Update the prompt after every command, but only if we
  243. have a tty as output'''
  244. if sys.stdin.isatty():
  245. self.prompt = self.location + self.prompt_end
  246. return stop
  247. def _prepare_module_commands(self, module_spec):
  248. '''Prepare the module commands'''
  249. module = ModuleInfo(name = module_spec.get_module_name(),
  250. desc = module_spec.get_module_description())
  251. for command in module_spec.get_commands_spec():
  252. cmd = CommandInfo(name = command["command_name"],
  253. desc = command["command_description"])
  254. for arg in command["command_args"]:
  255. param = ParamInfo(name = arg["item_name"],
  256. type = arg["item_type"],
  257. optional = bool(arg["item_optional"]),
  258. param_spec = arg)
  259. if ("item_default" in arg):
  260. param.default = arg["item_default"]
  261. cmd.add_param(param)
  262. module.add_command(cmd)
  263. self.add_module_info(module)
  264. def _validate_cmd(self, cmd):
  265. '''validate the parameters and merge some parameters together,
  266. merge algorithm is based on the command line syntax, later, if
  267. a better command line syntax come out, this function should be
  268. updated first.
  269. '''
  270. if not cmd.module in self.modules:
  271. raise CmdUnknownModuleSyntaxError(cmd.module)
  272. module_info = self.modules[cmd.module]
  273. if not module_info.has_command_with_name(cmd.command):
  274. raise CmdUnknownCmdSyntaxError(cmd.module, cmd.command)
  275. command_info = module_info.get_command_with_name(cmd.command)
  276. manda_params = command_info.get_mandatory_param_names()
  277. all_params = command_info.get_param_names()
  278. # If help is entered, don't do further parameter validation.
  279. for val in cmd.params.keys():
  280. if val == "help":
  281. return
  282. params = cmd.params.copy()
  283. if not params and manda_params:
  284. raise CmdMissParamSyntaxError(cmd.module, cmd.command, manda_params[0])
  285. elif params and not all_params:
  286. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command,
  287. list(params.keys())[0])
  288. elif params:
  289. param_name = None
  290. param_count = len(params)
  291. for name in params:
  292. # either the name of the parameter must be known, or
  293. # the 'name' must be an integer (ie. the position of
  294. # an unnamed argument
  295. if type(name) == int:
  296. # lump all extraneous arguments together as one big final one
  297. # todo: check if last param type is a string?
  298. if (param_count > 2):
  299. while (param_count > len(command_info.params) - 1):
  300. params[param_count - 2] += params[param_count - 1]
  301. del(params[param_count - 1])
  302. param_count = len(params)
  303. cmd.params = params.copy()
  304. # (-1, help is always in the all_params list)
  305. if name >= len(all_params) - 1:
  306. # add to last known param
  307. if param_name:
  308. cmd.params[param_name] += cmd.params[name]
  309. else:
  310. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command, cmd.params[name])
  311. else:
  312. # replace the numbered items by named items
  313. param_name = command_info.get_param_name_by_position(name, param_count)
  314. cmd.params[param_name] = cmd.params[name]
  315. del cmd.params[name]
  316. elif not name in all_params:
  317. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command, name)
  318. param_nr = 0
  319. for name in manda_params:
  320. if not name in params and not param_nr in params:
  321. raise CmdMissParamSyntaxError(cmd.module, cmd.command, name)
  322. param_nr += 1
  323. # Convert parameter value according parameter spec file.
  324. # Ignore check for commands belongs to module 'config'
  325. if cmd.module != CONFIG_MODULE_NAME:
  326. for param_name in cmd.params:
  327. param_spec = command_info.get_param_with_name(param_name).param_spec
  328. try:
  329. cmd.params[param_name] = isc.config.config_data.convert_type(param_spec, cmd.params[param_name])
  330. except isc.cc.data.DataTypeError as e:
  331. raise isc.cc.data.DataTypeError('Invalid parameter value for \"%s\", the type should be \"%s\" \n'
  332. % (param_name, param_spec['item_type']) + str(e))
  333. def _handle_cmd(self, cmd):
  334. '''Handle a command entered by the user'''
  335. if cmd.command == "help" or ("help" in cmd.params.keys()):
  336. self._handle_help(cmd)
  337. elif cmd.module == CONFIG_MODULE_NAME:
  338. try:
  339. self.apply_config_cmd(cmd)
  340. except isc.cc.data.DataTypeError as dte:
  341. print("Error: " + str(dte))
  342. except isc.cc.data.DataNotFoundError as dnfe:
  343. print("Error: " + str(dnfe))
  344. except KeyError as ke:
  345. print("Error: missing " + str(ke))
  346. raise ke
  347. else:
  348. self.apply_cmd(cmd)
  349. def add_module_info(self, module_info):
  350. '''Add the information about one module'''
  351. self.modules[module_info.name] = module_info
  352. def get_module_names(self):
  353. '''Return the names of all known modules'''
  354. return list(self.modules.keys())
  355. #override methods in cmd
  356. def default(self, line):
  357. self._parse_cmd(line)
  358. def emptyline(self):
  359. pass
  360. def do_help(self, name):
  361. print(CONST_BINDCTL_HELP)
  362. for k in self.modules.values():
  363. n = k.get_name()
  364. if len(n) >= CONST_BINDCTL_HELP_INDENT_WIDTH:
  365. print(" %s" % n)
  366. print(textwrap.fill(k.get_desc(),
  367. initial_indent=" ",
  368. subsequent_indent=" " +
  369. " " * CONST_BINDCTL_HELP_INDENT_WIDTH,
  370. width=70))
  371. else:
  372. print(textwrap.fill("%s%s%s" %
  373. (k.get_name(),
  374. " "*(CONST_BINDCTL_HELP_INDENT_WIDTH - len(k.get_name())),
  375. k.get_desc()),
  376. initial_indent=" ",
  377. subsequent_indent=" " +
  378. " " * CONST_BINDCTL_HELP_INDENT_WIDTH,
  379. width=70))
  380. def onecmd(self, line):
  381. if line == 'EOF' or line.lower() == "quit":
  382. self.conn.close()
  383. return True
  384. if line == 'h':
  385. line = 'help'
  386. Cmd.onecmd(self, line)
  387. def remove_prefix(self, list, prefix):
  388. return [(val[len(prefix):]) for val in list]
  389. def complete(self, text, state):
  390. if 0 == state:
  391. self._update_all_modules_info()
  392. text = text.strip()
  393. hints = []
  394. cur_line = my_readline()
  395. try:
  396. cmd = BindCmdParse(cur_line)
  397. if not cmd.params and text:
  398. hints = self._get_command_startswith(cmd.module, text)
  399. else:
  400. hints = self._get_param_startswith(cmd.module, cmd.command,
  401. text)
  402. if cmd.module == CONFIG_MODULE_NAME:
  403. # grm text has been stripped of slashes...
  404. my_text = self.location + "/" + cur_line.rpartition(" ")[2]
  405. list = self.config_data.get_config_item_list(my_text.rpartition("/")[0], True)
  406. hints.extend([val for val in list if val.startswith(my_text[1:])])
  407. # remove the common prefix from the hints so we don't get it twice
  408. hints = self.remove_prefix(hints, my_text.rpartition("/")[0])
  409. except CmdModuleNameFormatError:
  410. if not text:
  411. hints = self.get_module_names()
  412. except CmdMissCommandNameFormatError as e:
  413. if not text.strip(): # command name is empty
  414. hints = self.modules[e.module].get_command_names()
  415. else:
  416. hints = self._get_module_startswith(text)
  417. except CmdCommandNameFormatError as e:
  418. if e.module in self.modules:
  419. hints = self._get_command_startswith(e.module, text)
  420. except CmdParamFormatError as e:
  421. hints = self._get_param_startswith(e.module, e.command, text)
  422. except BindCtlException:
  423. hints = []
  424. self.hint = hints
  425. #self._append_space_to_hint()
  426. if state < len(self.hint):
  427. return self.hint[state]
  428. else:
  429. return None
  430. def _get_module_startswith(self, text):
  431. return [module
  432. for module in self.modules
  433. if module.startswith(text)]
  434. def _get_command_startswith(self, module, text):
  435. if module in self.modules:
  436. return [command
  437. for command in self.modules[module].get_command_names()
  438. if command.startswith(text)]
  439. return []
  440. def _get_param_startswith(self, module, command, text):
  441. if module in self.modules:
  442. module_info = self.modules[module]
  443. if command in module_info.get_command_names():
  444. cmd_info = module_info.get_command_with_name(command)
  445. params = cmd_info.get_param_names()
  446. hint = []
  447. if text:
  448. hint = [val for val in params if val.startswith(text)]
  449. else:
  450. hint = list(params)
  451. if len(hint) == 1 and hint[0] != "help":
  452. hint[0] = hint[0] + " ="
  453. return hint
  454. return []
  455. def _parse_cmd(self, line):
  456. try:
  457. cmd = BindCmdParse(line)
  458. self._validate_cmd(cmd)
  459. self._handle_cmd(cmd)
  460. except (IOError, http.client.HTTPException) as err:
  461. print('Error: ', err)
  462. except BindCtlException as err:
  463. print("Error! ", err)
  464. self._print_correct_usage(err)
  465. except isc.cc.data.DataTypeError as err:
  466. print("Error! ", err)
  467. def _print_correct_usage(self, ept):
  468. if isinstance(ept, CmdUnknownModuleSyntaxError):
  469. self.do_help(None)
  470. elif isinstance(ept, CmdUnknownCmdSyntaxError):
  471. self.modules[ept.module].module_help()
  472. elif isinstance(ept, CmdMissParamSyntaxError) or \
  473. isinstance(ept, CmdUnknownParamSyntaxError):
  474. self.modules[ept.module].command_help(ept.command)
  475. def _append_space_to_hint(self):
  476. """Append one space at the end of complete hint."""
  477. self.hint = [(val + " ") for val in self.hint]
  478. def _handle_help(self, cmd):
  479. if cmd.command == "help":
  480. self.modules[cmd.module].module_help()
  481. else:
  482. self.modules[cmd.module].command_help(cmd.command)
  483. def apply_config_cmd(self, cmd):
  484. '''Handles a configuration command.
  485. Raises a DataTypeError if a wrong value is set.
  486. Raises a DataNotFoundError if a wrong identifier is used.
  487. Raises a KeyError if the command was not complete
  488. '''
  489. identifier = self.location
  490. if 'identifier' in cmd.params:
  491. if not identifier.endswith("/"):
  492. identifier += "/"
  493. if cmd.params['identifier'].startswith("/"):
  494. identifier = cmd.params['identifier']
  495. else:
  496. if cmd.params['identifier'].startswith('['):
  497. identifier = identifier[:-1]
  498. identifier += cmd.params['identifier']
  499. # Check if the module is known; for unknown modules
  500. # we currently deny setting preferences, as we have
  501. # no way yet to determine if they are ok.
  502. module_name = identifier.split('/')[1]
  503. if module_name != "" and (self.config_data is None or \
  504. not self.config_data.have_specification(module_name)):
  505. print("Error: Module '" + module_name + "' unknown or not running")
  506. return
  507. if cmd.command == "show":
  508. # check if we have the 'all' argument
  509. show_all = False
  510. if 'argument' in cmd.params:
  511. if cmd.params['argument'] == 'all':
  512. show_all = True
  513. elif 'identifier' not in cmd.params:
  514. # no 'all', no identifier, assume this is the
  515. #identifier
  516. identifier += cmd.params['argument']
  517. else:
  518. print("Error: unknown argument " + cmd.params['argument'] + ", or multiple identifiers given")
  519. return
  520. values = self.config_data.get_value_maps(identifier, show_all)
  521. for value_map in values:
  522. line = value_map['name']
  523. if value_map['type'] in [ 'module', 'map' ]:
  524. line += "/"
  525. elif value_map['type'] == 'list' \
  526. and value_map['value'] != []:
  527. # do not print content of non-empty lists if
  528. # we have more data to show
  529. line += "/"
  530. else:
  531. line += "\t" + json.dumps(value_map['value'])
  532. line += "\t" + value_map['type']
  533. line += "\t"
  534. if value_map['default']:
  535. line += "(default)"
  536. if value_map['modified']:
  537. line += "(modified)"
  538. print(line)
  539. elif cmd.command == "show_json":
  540. if identifier == "":
  541. print("Need at least the module to show the configuration in JSON format")
  542. else:
  543. data, default = self.config_data.get_value(identifier)
  544. print(json.dumps(data))
  545. elif cmd.command == "add":
  546. if 'value' in cmd.params:
  547. self.config_data.add_value(identifier, cmd.params['value'])
  548. else:
  549. self.config_data.add_value(identifier)
  550. elif cmd.command == "remove":
  551. if 'value' in cmd.params:
  552. self.config_data.remove_value(identifier, cmd.params['value'])
  553. else:
  554. self.config_data.remove_value(identifier, None)
  555. elif cmd.command == "set":
  556. if 'identifier' not in cmd.params:
  557. print("Error: missing identifier or value")
  558. else:
  559. parsed_value = None
  560. try:
  561. parsed_value = json.loads(cmd.params['value'])
  562. except Exception as exc:
  563. # ok could be an unquoted string, interpret as such
  564. parsed_value = cmd.params['value']
  565. self.config_data.set_value(identifier, parsed_value)
  566. elif cmd.command == "unset":
  567. self.config_data.unset(identifier)
  568. elif cmd.command == "revert":
  569. self.config_data.clear_local_changes()
  570. elif cmd.command == "commit":
  571. self.config_data.commit()
  572. elif cmd.command == "diff":
  573. print(self.config_data.get_local_changes());
  574. elif cmd.command == "go":
  575. self.go(identifier)
  576. def go(self, identifier):
  577. '''Handles the config go command, change the 'current' location
  578. within the configuration tree. '..' will be interpreted as
  579. 'up one level'.'''
  580. id_parts = isc.cc.data.split_identifier(identifier)
  581. new_location = ""
  582. for id_part in id_parts:
  583. if (id_part == ".."):
  584. # go 'up' one level
  585. new_location, a, b = new_location.rpartition("/")
  586. else:
  587. new_location += "/" + id_part
  588. # check if exists, if not, revert and error
  589. v = self.config_data.find_spec_part(new_location)
  590. if v is None:
  591. print("Error: " + identifier + " not found")
  592. return
  593. self.location = new_location
  594. def apply_cmd(self, cmd):
  595. '''Handles a general module command'''
  596. url = '/' + cmd.module + '/' + cmd.command
  597. cmd_params = None
  598. if (len(cmd.params) != 0):
  599. cmd_params = json.dumps(cmd.params)
  600. reply = self.send_POST(url, cmd.params)
  601. data = reply.read().decode()
  602. # The reply is a string containing JSON data,
  603. # parse it, then prettyprint
  604. if data != "" and data != "{}":
  605. print(json.dumps(json.loads(data), sort_keys=True, indent=4))