bindcmd.py 28 KB

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