bindcmd.py 29 KB

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