bindcmd.py 28 KB

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