def run(self, context, args, kwargs, opargs): update_ops = update_check_utility(context) self.parent.load() if update_ops: return update_ops else: output_msg(_("No new updates available."))
def run(self, context, args, kwargs, opargs): if not args: raise CommandException( _("'chdir' requires 1 argument. For help see 'help chdir'")) name = args[0] if name == '..': dest = self.parent.curr_obj.parent elif name == '.': dest = self.parent.curr_obj else: dest = self.parent.curr_obj.get_child(name) if not dest.is_dir: raise CommandException( 'Cannot "cd" into object of type: {0}'.format(dest.type.name)) else: self.parent.curr_obj = dest output_msg(_(">{0}".format(str(self.parent.curr_obj)))) contents = [{ 'name': o.name, 'type': o.type.name } for o in self.parent.curr_obj.readdir()] return Table(contents, [ Table.Column('Name', 'name'), Table.Column('Type', 'type'), ])
def run(self, context, args, kwargs, opargs): if not args: raise CommandException(_("'mkdir' requires 1 argument. For help see 'help mkdir'")) self.parent.curr_obj.mkdir(args[0]) output_msg(_(">{0}".format(str(self.parent.curr_obj)))) contents = [{'name': o.name, 'type': o.type.name} for o in self.parent.curr_obj.readdir()] return Table(contents, [ Table.Column('Name', 'name'), Table.Column('Type', 'type'), ])
def task_callback(self, task_state, task_data): if task_state == 'FINISHED' and task_data["result"]: if self.reboot: output_msg( _("Updates Downloaded and Installed Successfully." " System going for a reboot now.")) else: output_msg( _("System successfully updated." " Please reboot now using the '/ system reboot' command") )
def run(self, context, args, kwargs, opargs): if not kwargs: raise CommandException(_("Upload requires more arguments. For help see 'help upload'")) if 'path' not in kwargs: raise CommandException(_("Please specify path to the source config file." "For help see 'help upload'")) p = Path(kwargs['path']) with p.open('r') as fo: output_msg(_('Restoring the Database. Reboot will occur immediately after the restore operation.')) context.call_task_sync('database.restore', FileDescriptor(fd=fo.fileno(), close=False))
def run(self, context, args, kwargs, opargs): if not args: raise CommandException(_("Open requires 1 argument. For help see 'help open'")) self.parent.curr_obj = FileProvider.open(args[0], remote_logpass=self.parent.remote_logpass) output_msg(_("Connection opened: {0}".format(str(self.parent.curr_obj)))) contents = [{'name': o.name, 'type': o.type.name} for o in self.parent.curr_obj.readdir()] return Table(contents, [ Table.Column('Name', 'name'), Table.Column('Type', 'type'), ])
def task_callback(self, task_state, task_data): if task_state == 'FINISHED' and task_data["result"]: if self.reboot: output_msg(_( "Updates Downloaded and Installed Successfully." " System going for a reboot now." )) else: output_msg(_( "System successfully updated." " Please reboot now using the '/ system reboot' command" ))
def run(self, context, args, kwargs, opargs): def resize(signo, frame): self.resize = True def read(data): sys.stdout.write(data.decode('utf8')) sys.stdout.flush() def close(): self.closed = True self.closed = False name = ' '.join(str(i) for i in args) if len(args) > 0 else '/bin/sh' if name == '/bin/sh': output_msg(context.connection.call_sync( 'system.general.cowsay', "To make configuration changes, return to CLI and use the CLI command set.\n" + " Any configuration changes used outside " + "of the FreeNAS CLI are not saved to the configuration database.", "/usr/local/share/cows/surgery.cow" )[0]) size = get_terminal_size() token = context.call_sync('shell.spawn', name, size[1], size[0]) shell = ShellClient(context.hostname, token) shell.on_data(read) shell.on_close(close) shell.open() fd = sys.stdin.fileno() if platform.system() != 'Windows': signal.signal(signal.SIGWINCH, resize) old_settings = termios.tcgetattr(fd) tty.setraw(fd) while not self.closed: if self.resize: try: size = get_terminal_size(fd) context.call_sync('shell.resize', token, size[1], size[0]) except: pass self.resize = False r, w, x = select.select([fd], [], [], 0.1) if fd in r: ch = os.read(fd, 1) shell.write(ch) if platform.system() != 'Windows': signal.signal(signal.SIGWINCH, signal.SIG_DFL) termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
def run(self, context, args, kwargs, opargs): trains = context.call_sync('update.trains') if trains is None: output_msg(_( "Could not fetch Available Trains from the Update Server. " "Please Check internet connectivity and try again." )) else: return Table(trains, [ Table.Column('Name', 'name'), Table.Column('Description', 'description'), Table.Column('Sequence', 'sequence'), Table.Column('Current', 'current', vt=ValueType.BOOLEAN) ])
def run(self, context, args, kwargs, opargs): if not args: raise CommandException( _("'mkdir' requires 1 argument. For help see 'help mkdir'")) self.parent.curr_obj.mkdir(args[0]) output_msg(_(">{0}".format(str(self.parent.curr_obj)))) contents = [{ 'name': o.name, 'type': o.type.name } for o in self.parent.curr_obj.readdir()] return Table(contents, [ Table.Column('Name', 'name'), Table.Column('Type', 'type'), ])
def run(self, context, args, kwargs, opargs): if not args: raise CommandException(_("'rmdir' requires 1 argument. For help see 'help rmdir'")) name = args[0] try: self.parent.curr_obj.rmdir(name) except ValueError as err: output_msg(_(err.args)) finally: output_msg(_(">{0}".format(str(self.parent.curr_obj)))) contents = [{'name': o.name, 'type': o.type.name} for o in self.parent.curr_obj.readdir()] return Table(contents, [ Table.Column('Name', 'name'), Table.Column('Type', 'type'), ])
def run(self, context, args, kwargs, opargs): if not args: raise CommandException( _("Open requires 1 argument. For help see 'help open'")) self.parent.curr_obj = FileProvider.open( args[0], remote_logpass=self.parent.remote_logpass) output_msg( _("Connection opened: {0}".format(str(self.parent.curr_obj)))) contents = [{ 'name': o.name, 'type': o.type.name } for o in self.parent.curr_obj.readdir()] return Table(contents, [ Table.Column('Name', 'name'), Table.Column('Type', 'type'), ])
def run(self, context, args, kwargs, opargs): if not args: raise CommandException( _("'rmdir' requires 1 argument. For help see 'help rmdir'")) name = args[0] try: self.parent.curr_obj.rmdir(name) except ValueError as err: output_msg(_(err.args)) finally: output_msg(_(">{0}".format(str(self.parent.curr_obj)))) contents = [{ 'name': o.name, 'type': o.type.name } for o in self.parent.curr_obj.readdir()] return Table(contents, [ Table.Column('Name', 'name'), Table.Column('Type', 'type'), ])
def run(self, context, args, kwargs, opargs): if not args: raise CommandException(_("'chdir' requires 1 argument. For help see 'help chdir'")) name = args[0] if name == '..': dest = self.parent.curr_obj.parent elif name == '.': dest = self.parent.curr_obj else: dest = self.parent.curr_obj.get_child(name) if not dest.is_dir: raise CommandException('Cannot "cd" into object of type: {0}'.format(dest.type.name)) else: self.parent.curr_obj = dest output_msg(_(">{0}".format(str(self.parent.curr_obj)))) contents = [{'name': o.name, 'type': o.type.name} for o in self.parent.curr_obj.readdir()] return Table(contents, [ Table.Column('Name', 'name'), Table.Column('Type', 'type'), ])
def run(self, context, args, kwargs, opargs): def read(data): sys.stdout.write(data.decode('utf8')) sys.stdout.flush() def close(): self.closed = True self.closed = False name = ' '.join(str(i) for i in args) if len(args) > 0 else '/bin/sh' if name == '/bin/sh': output_msg(context.connection.call_sync( 'system.general.cowsay', "To make configuration changes, return to CLI and use the CLI command set.\n" + " Any configuration changes used outside " + "of the FreeNAS CLI are not saved to the configuration database.", "/usr/local/share/cows/surgery.cow" )[0]) token = context.call_sync('shell.spawn', name) shell = ShellClient(context.hostname, token) shell.on_data(read) shell.on_close(close) shell.open() fd = sys.stdin.fileno() if platform.system() != 'Windows': old_settings = termios.tcgetattr(fd) tty.setraw(fd) while not self.closed: r, w, x = select.select([fd], [], [], 0.1) if fd in r: ch = os.read(fd, 1) shell.write(ch) if platform.system() != 'Windows': termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
def run(self, context, args, kwargs, opargs): if not args: output_msg("attach_disk requires more arguments.\n{0}".format(inspect.getdoc(self))) return disk = args.pop(0) # The all_disks below is a temporary fix, use this after "select" is working # all_disks = context.call_sync('disk.query', [], {"select":"path"}) all_disks = [d["path"] for d in context.call_sync("disk.query")] available_disks = context.call_sync('volume.get_available_disks') disk = correct_disk_path(disk) if disk not in all_disks: output_msg("Disk " + disk + " does not exist.") return if disk not in available_disks: output_msg("Disk " + disk + " is not usable.") return volume = context.call_sync('zfs.pool.get_boot_pool') context.submit_task('boot.attach_disk', volume['groups']['data'][0]['guid'], disk) return
def run(self, context, args, kwargs, opargs): if not args: output_msg("attach_disk requires more arguments.\n{0}".format(inspect.getdoc(self))) return disk = args.pop(0) # The all_disks below is a temporary fix, use this after "select" is working # all_disks = context.call_sync('disk.query', [], {"select":"path"}) all_disks = [d["path"] for d in context.call_sync("disk.query")] available_disks = context.call_sync('volume.get_available_disks') disk = correct_disk_path(disk) if disk not in all_disks: output_msg("Disk " + disk + " does not exist.") return if disk not in available_disks: output_msg("Disk " + disk + " is not usable.") return context.submit_task('boot.disk.attach', disk) return
def run(self, context, args, kwargs, opargs): self.curr_obj = None output_msg(_("Connection closed"))
def run(self, context, args, kwargs, opargs): ns = SingleItemNamespace(None, self.parent, context) ns.orig_entity = copy.deepcopy(self.parent.skeleton_entity) ns.entity = copy.deepcopy(self.parent.skeleton_entity) kwargs = collections.OrderedDict(kwargs) if len(args) > 0: # Do not allow user to specify name as both implicit and explicit parameter as this suggests a mistake if 'name' in kwargs: raise CommandException( _("Both implicit and explicit 'name' parameters are specified." )) else: prop = self.parent.primary_key kwargs[prop.name] = args.pop(0) kwargs.move_to_end(prop.name, False) for k, v in list(kwargs.items()): if not self.parent.has_property(k): output_msg('Property {0} not found'.format(k)) return mapping = self.parent.get_mapping(k) if mapping.set is None or not mapping.createsetable: output_msg('Property {0} is not writable'.format(k)) return if mapping.regex is not None and not re.match( mapping.regex, str(v)): output_msg('Invalid input {0} for property {1}.'.format(v, k)) return if self.parent.required_props: missing_args = [] for prop in self.parent.required_props: if isinstance(prop, list): has_arg = False for p in prop: if p in kwargs.keys(): has_arg = True if not has_arg: missing_args.append("{0}".format(' or '.join(prop))) else: if prop not in kwargs.keys(): missing_args.append(prop) if self.parent.extra_required_props: for prop_set in self.parent.extra_required_props: found_one = False missing = False for prop in prop_set: if prop in kwargs.keys(): found_one = True else: if found_one: missing = True if found_one and missing: missing_args.append(' and '.join(prop_set)) if hasattr(self.parent, 'conditional_required_props'): for prop in self.parent.conditional_required_props(kwargs): if prop not in kwargs.keys(): missing_args.append(prop) if len(missing_args) > 0: output_msg( _('Required properties not provided: {0}'.format( ', '.join(missing_args)))) return else: if not args and not kwargs: return mappings = map(lambda i: (self.parent.get_mapping(i[0]), i[1]), kwargs.items()) for prop, v in sorted(mappings, key=lambda i: i[0].index): if prop.create_arg: prop.do_set(ns.create_args, v, ns.entity) elif not prop.update_arg: prop.do_set(ns.entity, v) tid = self.parent.save(ns, new=True) return EntityPromise(context, tid, ns)
def run(self, context, args, kwargs, opargs): ns = SingleItemNamespace(None, self.parent, context) ns.orig_entity = copy.deepcopy(self.parent.skeleton_entity) ns.entity = copy.deepcopy(self.parent.skeleton_entity) kwargs = collections.OrderedDict(kwargs) if len(args) > 0: # Do not allow user to specify name as both implicit and explicit parameter as this suggests a mistake if 'name' in kwargs: raise CommandException(_("Both implicit and explicit 'name' parameters are specified.")) else: prop = self.parent.primary_key kwargs[prop.name] = args.pop(0) kwargs.move_to_end(prop.name, False) for k, v in list(kwargs.items()): if not self.parent.has_property(k): output_msg('Property {0} not found'.format(k)) return mapping = self.parent.get_mapping(k) if mapping.set is None or not mapping.createsetable: output_msg('Property {0} is not writable'.format(k)) return if mapping.regex is not None and not re.match(mapping.regex, str(v)): output_msg('Invalid input {0} for property {1}.'.format(v, k)) return if self.parent.required_props: missing_args = [] for prop in self.parent.required_props: if isinstance(prop, list): has_arg = False for p in prop: if p in kwargs.keys(): has_arg = True if not has_arg: missing_args.append("{0}".format(' or '.join(prop))) else: if prop not in kwargs.keys(): missing_args.append(prop) if self.parent.extra_required_props: for prop_set in self.parent.extra_required_props: found_one = False missing = False for prop in prop_set: if prop in kwargs.keys(): found_one = True else: if found_one: missing = True if found_one and missing: missing_args.append(' and '.join(prop_set)) if hasattr(self.parent, 'conditional_required_props'): for prop in self.parent.conditional_required_props(kwargs): if prop not in kwargs.keys(): missing_args.append(prop) if len(missing_args) > 0: output_msg(_('Required properties not provided: {0}'.format(', '.join(missing_args)))) return else: if not args and not kwargs: return mappings = map(lambda i: (self.parent.get_mapping(i[0]), i[1]), kwargs.items()) for prop, v in sorted(mappings, key=lambda i: i[0].index): if prop.create_arg: prop.do_set(ns.create_args, v, ns.entity) elif not prop.update_arg: prop.do_set(ns.entity, v) tid = self.parent.save(ns, new=True) return EntityPromise(context, tid, ns)
def unparse_(fn): output_msg(unparse(FunctionDefinition(fn.name, fn.param_names, fn.exp)))
def print_(*items): for i in items: format_output(i, newline=False) output_msg('')
def run(self, context, args, kwargs, opargs): reboot = None if 'reboot' in kwargs and kwargs['reboot']: reboot = RebootCommand() output_msg(_("Checking for new updates...")) update_ops = update_check_utility(context) if update_ops: output_msg(_("The following update packages are available: ")) output_table(update_ops) else: output_msg(_("No updates currently available for download and installation")) return original_tasks_blocking = context.variables.variables['tasks_blocking'].value context.variables.set('tasks_blocking', True) output_msg(_("Downloading update packages now...")) download_task_id = context.submit_task( 'update.download', message_formatter=download_message_formatter) download_details = context.call_sync('task.status', download_task_id) while download_details['state'] == 'EXECUTING': time.sleep(1) download_details = context.call_sync('task.status', download_task_id) if download_details['state'] != 'FINISHED': raise CommandException(_("Updates failed to download")) output_msg(_("System going for an update now...")) apply_task_id = context.submit_task('update.update') context.variables.set('tasks_blocking', original_tasks_blocking) apply_details = context.call_sync('task.status', apply_task_id) while apply_details['state'] == 'EXECUTING': time.sleep(1) apply_details = context.call_sync('task.status', apply_task_id) if apply_details['state'] != 'FINISHED': raise CommandException(_("Updates failed to apply")) else: if reboot: reboot.run(context, args, kwargs, opargs) else: output_msg(_( "System successfully updated. Please reboot now using the 'reboot' command" ))
def unparse_(fn): output_msg(unparse(FunctionDefinition( fn.name, fn.param_names, fn.exp )))
def run(self, context, args, kwargs, opargs): if args: try: tid = int(args[0]) except ValueError: raise CommandException('Task id argument must be an integer') else: tid = None try: tid = context.global_env.find('_last_task_id').value except KeyError: pass if tid is None: raise CommandException( _('No recently submitted tasks (which are still active) found') ) def update(progress, task): message = task['progress'][ 'message'] if 'progress' in task else task['state'] percentage = task['progress'][ 'percentage'] if 'progress' in task else None progress.update(percentage=percentage, message=message) generator = None progress = None try: task = context.entity_subscribers['task'].get(tid, timeout=1) if task['state'] in ('FINISHED', 'FAILED', 'ABORTED'): return _("The task with id: {0} ended in {1} state".format( tid, task['state'])) # lets set the SIGTSTP (Ctrl+Z) handler SIGTSTP_setter(set_flag=True) output_msg(_("Hit Ctrl+C to terminate task if needed")) output_msg(_("To background running task press 'Ctrl+Z'")) progress = ProgressBar() update(progress, task) generator = context.entity_subscribers['task'].listen(tid) for op, old, new in generator: update(progress, new) if new['state'] == 'FINISHED': progress.finish() break if new['state'] == 'FAILED': six.print_() break if new['state'] == 'ABORTED': six.print_() break except KeyboardInterrupt: if progress: progress.end() six.print_() output_msg(_("User requested task termination. Abort signal sent")) context.call_sync('task.abort', tid) except SIGTSTPException: # The User backgrounded the task by sending SIGTSTP (Ctrl+Z) if progress: progress.end() six.print_() output_msg( _("Task {0} will continue to run in the background.".format( tid))) output_msg( _("To bring it back to the foreground execute 'wait {0}'". format(tid))) output_msg( _("Use the 'pending' command to see pending tasks (of this session)" )) finally: # Now that we are done with the task unset the Ctrl+Z handler # lets set the SIGTSTP (Ctrl+Z) handler if progress: progress.end() if generator: del generator SIGTSTP_setter(set_flag=False)
def run(self, context, args, kwargs, opargs): if args: try: tid = int(args[0]) except ValueError: raise CommandException('Task id argument must be an integer') else: tid = None try: tid = context.global_env.find('_last_task_id').value except KeyError: pass if tid is None: raise CommandException(_( 'No recently submitted tasks (which are still active) found' )) def update(progress, task): message = task['progress']['message'] if 'progress' in task else task['state'] percentage = task['progress']['percentage'] if 'progress' in task else 0 progress.update(percentage=percentage, message=message) try: generator = None task = context.entity_subscribers['task'].get(tid, timeout=1) if task['state'] in ('FINISHED', 'FAILED', 'ABORTED'): return _("The task with id: {0} ended in {1} state".format(tid, task['state'])) # lets set the SIGTSTP (Ctrl+Z) handler SIGTSTP_setter(set_flag=True) output_msg(_("Hit Ctrl+C to terminate task if needed")) output_msg(_("To background running task press 'Ctrl+Z'")) progress = ProgressBar() update(progress, task) generator = context.entity_subscribers['task'].listen(tid) for op, old, new in generator: update(progress, new) if new['state'] == 'FINISHED': progress.finish() break if new['state'] == 'FAILED': six.print_() break if new['state'] == 'ABORTED': six.print_() break except KeyboardInterrupt: six.print_() output_msg(_("User requested task termination. Abort signal sent")) context.call_sync('task.abort', tid) except SIGTSTPException: # The User backgrounded the task by sending SIGTSTP (Ctrl+Z) six.print_() output_msg(_("Task {0} will continue to run in the background.".format(tid))) output_msg(_("To bring it back to the foreground execute 'wait {0}'".format(tid))) output_msg(_("Use the 'pending' command to see pending tasks (of this session)")) finally: # Now that we are done with the task unset the Ctrl+Z handler # lets set the SIGTSTP (Ctrl+Z) handler del generator SIGTSTP_setter(set_flag=False)
def run(self, context, args, kwargs, opargs): ds_id = self.parent.entity['id'] dcs = context.call_sync('directoryservices.get', ds_id, 'dcs') if dcs: for dc in dcs: output_msg(dc)