bindcmd.py 29 KB

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