class MyApp(Application): name = Unicode(u'myapp') running = Bool(False, help="Is the app running?").tag(config=True) classes = List([Bar, Foo]) config_file = Unicode(u'', help="Load this config file").tag(config=True) warn_tpyo = Unicode(u"yes the name is wrong on purpose", config=True, help="Should print a warning if `MyApp.warn-typo=...` command is passed") aliases = Dict({ 'i' : 'Foo.i', 'j' : 'Foo.j', 'name' : 'Foo.name', 'enabled' : 'Bar.enabled', 'log-level' : 'Application.log_level', }) flags = Dict(dict(enable=({'Bar': {'enabled' : True}}, "Set Bar.enabled to True"), disable=({'Bar': {'enabled' : False}}, "Set Bar.enabled to False"), crit=({'Application' : {'log_level' : logging.CRITICAL}}, "set level=CRITICAL"), )) def init_foo(self): self.foo = Foo(parent=self) def init_bar(self): self.bar = Bar(parent=self)
class MyApp(Application): name = Unicode(u'myapp') running = Bool(False, config=True, help="Is the app running?") classes = List([Bar, Foo]) config_file = Unicode(u'', config=True, help="Load this config file") aliases = Dict({ 'i' : 'Foo.i', 'j' : 'Foo.j', 'name' : 'Foo.name', 'enabled' : 'Bar.enabled', 'log-level' : 'Application.log_level', }) flags = Dict(dict(enable=({'Bar': {'enabled' : True}}, "Set Bar.enabled to True"), disable=({'Bar': {'enabled' : False}}, "Set Bar.enabled to False"), crit=({'Application' : {'log_level' : logging.CRITICAL}}, "set level=CRITICAL"), )) def init_foo(self): self.foo = Foo(parent=self) def init_bar(self): self.bar = Bar(parent=self)
class Foo(Configurable): i = Integer(0, help="The integer i.").tag(config=True) j = Integer(1, help="The integer j.").tag(config=True) name = Unicode(u'Brian', help="First name.").tag(config=True) la = List([]).tag(config=True) fdict = Dict().tag(config=True, multiplicity='+')
class InnerTabContainer(ConfigurableQTabWidget): factories = List([FigureDispatcher], config=True) handler_registry = Dict(DottedObjectName(), config=True) def __init__(self, *args, **kwargs): self.update_config(load_config()) super().__init__(*args, **kwargs) self.run_router = QRunRouter( [factory(self.addTab) for factory in self.factories], handler_registry=self.handler_registry)
class Containers(Configurable): lis = List().tag(config=True) def _lis_default(self): return [-1] s = Set().tag(config=True) def _s_default(self): return {'a'} d = Dict().tag(config=True) def _d_default(self): return {'a' : 'b'}
class FigureManager(Configurable): """ For a given Viewer, encasulate the matplotlib Figures and associated tabs. """ factories = List([ LinePlotManager, LatestFrameImageManager], config=True) enabled = Bool(True, config=True) exclude_streams = Set([], config=True) def __init__(self, add_tab): self.update_config(load_config()) self.add_tab = add_tab self._figures = {} def get_figure(self, key, label, *args, **kwargs): try: return self._figures[key] except KeyError: return self._add_figure(key, label, *args, **kwargs) def _add_figure(self, key, label, *args, **kwargs): tab = QWidget() fig, _ = plt.subplots(*args, **kwargs) canvas = FigureCanvas(fig) canvas.setMinimumWidth(640) canvas.setParent(tab) toolbar = NavigationToolbar(canvas, tab) tab_label = QLabel(label) tab_label.setMaximumHeight(20) layout = QVBoxLayout() layout.addWidget(tab_label) layout.addWidget(canvas) layout.addWidget(toolbar) tab.setLayout(layout) self.add_tab(tab, label) self._figures[key] = fig return fig def __call__(self, name, start_doc): if not self.enabled: return [], [] dimensions = start_doc.get('hints', {}).get('dimensions', guess_dimensions(start_doc)) rr = RunRouter( [factory(self, dimensions) for factory in self.factories]) rr('start', start_doc) return [rr], []
class AgentGroup(HasTraits): """Group of agents Examples: >>> group = AgentGroup( >>> size=10, >>> agent_type=Circular, >>> attributes=..., >>> ) """ agent_type = Type(AgentType, allow_none=True, help='AgentType for generating agent from attributes.') size = Int( default_value=0, help='Size of the agent group. Optional is attributes are instance of ' 'collection') attributes = Union( (Instance(Collection), Instance(Generator), Instance(Callable)), allow_none=True, help='Attributes of the chosen agent type.') members = List(Instance(AgentType), help='') @observe('size', 'agent_type', 'attributes') def _observe_members(self, change): if self.size > 0 and self.attributes is not None and self.agent_type is not None: if isinstance(self.attributes, Collection): self.members = [self.agent_type(**a) for a in self.attributes] elif isinstance(self.attributes, Generator): self.members = [ self.agent_type(**next(self.attributes)) for _ in range(self.size) ] elif isinstance(self.attributes, Callable): self.members = [ self.agent_type(**self.attributes()) for _ in range(self.size) ] else: raise TraitError
class RunViewer(ConfigurableQTabWidget): """ Contains tabs showing various view on the data from one Run. """ factories = List([HeaderTreeFactory, BaselineFactory, FigureManager], config=True) handler_registry = Dict(DottedObjectName(), config=True) def __init__(self, *args, **kwargs): self.update_config(load_config()) super().__init__(*args, **kwargs) self._entries = [] self._uids = [] self._active_loaders = set() def filler_factory(name, doc): filler = Filler(parse_handler_registry(self.handler_registry), inplace=True) filler('start', doc) return [filler], [] self.run_router = RunRouter( [filler_factory] + [factory(self.addTab) for factory in self.factories]) @property def entries(self): return self._entries @property def uids(self): return self._uids def load_entry(self, entry): "Load all documents from databroker and push them through the RunRouter." self._entries.append(entry) self._uids.append(entry.describe()['metadata']['start']['uid']) entry_loader = EntryLoader(entry, self._active_loaders) entry_loader.signal.connect(self.run_router) entry_loader.start()
class Viewer(ConfigurableQObject): name_doc = Signal(str, dict) factories = List([FigureDispatcher], config=True) handler_registry = Dict(DottedObjectName(), config=True) def __init__(self, inner_tab_container, set_label, *args, **kwargs): self.update_config(load_config()) self._inner_tab_container = inner_tab_container self._set_label = set_label self._run_start_uids = [] factories = [ factory(self._inner_tab_container.addTab) for factory in self.factories ] factories.append(self._register_run) self.run_router = QRunRouter(factories, handler_registry=self.handler_registry) super().__init__(*args, **kwargs) self.name_doc.connect(self.run_router) def rename(self, label): self._set_label(label) def __repr__(self): return f"<{type(self).__name__}>" def add_run(self, run, fill='delayed'): for name, doc in run.canonical(fill=fill): self.name_doc.emit(name, doc) def __call__(self, name, doc): self.name_doc.emit(name, doc) def _register_run(self, name, doc): "Capture the uid of every Run added to this Viewer." assert name == 'start' self._run_start_uids.append(doc['uid']) return [], []
class Foo(Configurable): a = Integer(0, help="The integer a.").tag(config=True) b = Unicode('nope').tag(config=True) flist = List([]).tag(config=True) fdict = Dict().tag(config=True)
class LazyConfigValue(HasTraits): """Proxy object for exposing methods on configurable containers Exposes: - append, extend, insert on lists - update on dicts - update, add on sets """ _value = None # list methods _extend = List() _prepend = List() def append(self, obj): self._extend.append(obj) def extend(self, other): self._extend.extend(other) def prepend(self, other): """like list.extend, but for the front""" self._prepend[:0] = other _inserts = List() def insert(self, index, other): if not isinstance(index, int): raise TypeError("An integer is required") self._inserts.append((index, other)) # dict methods # update is used for both dict and set _update = Any() def update(self, other): if self._update is None: if isinstance(other, dict): self._update = {} else: self._update = set() self._update.update(other) # set methods def add(self, obj): self.update({obj}) def get_value(self, initial): """construct the value from the initial one after applying any insert / extend / update changes """ if self._value is not None: return self._value value = copy.deepcopy(initial) if isinstance(value, list): for idx, obj in self._inserts: value.insert(idx, obj) value[:0] = self._prepend value.extend(self._extend) elif isinstance(value, dict): if self._update: value.update(self._update) elif isinstance(value, set): if self._update: value.update(self._update) self._value = value return value def to_dict(self): """return JSONable dict form of my data Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples. """ d = {} if self._update: d['update'] = self._update if self._extend: d['extend'] = self._extend if self._prepend: d['prepend'] = self._prepend elif self._inserts: d['inserts'] = self._inserts return d def __repr__(self): if self._value is not None: return "<%s value=%r>" % (self.__class__.__name__, self._value) else: return "<%s %r>" % (self.__class__.__name__, self.to_dict())
class Application(SingletonConfigurable): """A singleton application with full configuration support.""" # The name of the application, will usually match the name of the command # line application name = Unicode('application') # The description of the application that is printed at the beginning # of the help. description = Unicode('This is an application.') # default section descriptions option_description = Unicode(option_description) keyvalue_description = Unicode(keyvalue_description) subcommand_description = Unicode(subcommand_description) python_config_loader_class = PyFileConfigLoader json_config_loader_class = JSONFileConfigLoader # The usage and example string that goes at the end of the help string. examples = Unicode() # A sequence of Configurable subclasses whose config=True attributes will # be exposed at the command line. classes = [] def _classes_inc_parents(self, classes=None): """Iterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once. """ if classes is None: classes = self.classes seen = set() for c in classes: # We want to sort parents before children, so we reverse the MRO for parent in reversed(c.mro()): if issubclass(parent, Configurable) and (parent not in seen): seen.add(parent) yield parent # The version string of this application. version = Unicode('0.0') # the argv used to initialize the application argv = List() # Whether failing to load config files should prevent startup raise_config_file_errors = Bool( TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR) # The log level for the application log_level = Enum( (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL'), default_value=logging.WARN, help="Set the log level by value or name.").tag(config=True) @observe('log_level') @observe_compat def _log_level_changed(self, change): """Adjust the log level when log_level is set.""" new = change.new if isinstance(new, str): new = getattr(logging, new) self.log_level = new self.log.setLevel(new) _log_formatter_cls = LevelFormatter log_datefmt = Unicode( "%Y-%m-%d %H:%M:%S", help="The date format used by logging formatters for %(asctime)s").tag( config=True) log_format = Unicode( "[%(name)s]%(highlevel)s %(message)s", help="The Logging format template", ).tag(config=True) @observe('log_datefmt', 'log_format') @observe_compat def _log_format_changed(self, change): """Change the log formatter when log_format is set.""" _log_handler = self._get_log_handler() if not _log_handler: warnings.warn( "No Handler found on {self.log}, setting log_format will have no effect", RuntimeWarning, ) return _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt) _log_handler.setFormatter(_log_formatter) @default('log') def _log_default(self): """Start logging for this application. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. """ log = logging.getLogger(self.__class__.__name__) log.setLevel(self.log_level) log.propagate = False _log = log # copied from Logger.hasHandlers() (new in Python 3.2) while _log: if _log.handlers: return log if not _log.propagate: break else: _log = _log.parent if sys.executable and sys.executable.endswith('pythonw.exe'): # this should really go to a file, but file-logging is only # hooked up in parallel applications _log_handler = logging.StreamHandler(open(os.devnull, 'w')) else: _log_handler = logging.StreamHandler() _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt) _log_handler.setFormatter(_log_formatter) log.addHandler(_log_handler) return log #: the alias map for configurables #: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`. #: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text). aliases = {'log-level': 'Application.log_level'} # flags for loading Configurables or store_const style flags # flags are loaded from this dict by '--key' flags # this must be a dict of two-tuples, the first element being the Config/dict # and the second being the help string for the flag flags = { 'debug': ({ 'Application': { 'log_level': logging.DEBUG, }, }, "Set log-level to debug, for the most verbose logging."), 'show-config': ({ 'Application': { 'show_config': True, }, }, "Show the application's configuration (human-readable format)"), 'show-config-json': ({ 'Application': { 'show_config_json': True, }, }, "Show the application's configuration (json format)"), } # subcommands for launching other applications # if this is not empty, this will be a parent Application # this must be a dict of two-tuples, # the first element being the application class/import string # and the second being the help string for the subcommand subcommands = Dict() # parse_command_line will initialize a subapp, if requested subapp = Instance('traitlets.config.application.Application', allow_none=True) # extra command-line arguments that don't set config values extra_args = List(Unicode()) cli_config = Instance( Config, (), {}, help="""The subset of our configuration that came from the command-line We re-load this configuration after loading config files, to ensure that it maintains highest priority. """) _loaded_config_files = List() show_config = Bool( help="Instead of starting the Application, dump configuration to stdout" ).tag(config=True) show_config_json = Bool( help= "Instead of starting the Application, dump configuration to stdout (as JSON)" ).tag(config=True) @observe('show_config_json') def _show_config_json_changed(self, change): self.show_config = change.new @observe('show_config') def _show_config_changed(self, change): if change.new: self._save_start = self.start self.start = self.start_show_config def __init__(self, **kwargs): SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. cls = self.__class__ if cls not in self.classes: if self.classes is cls.classes: # class attr, assign instead of insert self.classes = [cls] + self.classes else: self.classes.insert(0, self.__class__) @observe('config') @observe_compat def _config_changed(self, change): super(Application, self)._config_changed(change) self.log.debug('Config changed: %r', change.new) @catch_config_error def initialize(self, argv=None): """Do the basic steps to configure me. Override in subclasses. """ self.parse_command_line(argv) def start(self): """Start the app mainloop. Override in subclasses. """ if self.subapp is not None: return self.subapp.start() def start_show_config(self): """start function used when show_config is True""" config = self.config.copy() # exclude show_config flags from displayed config for cls in self.__class__.mro(): if cls.__name__ in config: cls_config = config[cls.__name__] cls_config.pop('show_config', None) cls_config.pop('show_config_json', None) if self.show_config_json: json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr) # add trailing newline sys.stdout.write('\n') return if self._loaded_config_files: print("Loaded config files:") for f in self._loaded_config_files: print(' ' + f) print() for classname in sorted(config): class_config = config[classname] if not class_config: continue print(classname) pformat_kwargs = dict(indent=4, compact=True) for traitname in sorted(class_config): value = class_config[traitname] print(' .{} = {}'.format( traitname, pprint.pformat(value, **pformat_kwargs), )) def print_alias_help(self): """Print the alias parts of the help.""" print('\n'.join(self.emit_alias_help())) def emit_alias_help(self): """Yield the lines for alias part of the help.""" if not self.aliases: return classdict = {} for cls in self.classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = c for alias, longname in self.aliases.items(): try: if isinstance(longname, tuple): longname, fhelp = longname else: fhelp = None classname, traitname = longname.split('.', 1) cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] fhelp = cls.class_get_trait_help(trait, helptext=fhelp).splitlines() if not isinstance(alias, tuple): alias = (alias, ) alias = sorted(alias, key=len) alias = ', '.join( ('--%s' if len(m) > 1 else '-%s') % m for m in alias) # reformat first line fhelp[0] = fhelp[0].replace('--' + longname, alias) for l in fhelp: yield l yield indent("Equivalent to: [--%s]" % longname) except Exception as ex: self.log.error( 'Failed collecting help-message for alias %r, due to: %s', alias, ex) raise def print_flag_help(self): """Print the flag part of the help.""" print('\n'.join(self.emit_flag_help())) def emit_flag_help(self): """Yield the lines for the flag part of the help.""" if not self.flags: return for flags, (cfg, fhelp) in self.flags.items(): try: if not isinstance(flags, tuple): flags = (flags, ) flags = sorted(flags, key=len) flags = ', '.join( ('--%s' if len(m) > 1 else '-%s') % m for m in flags) yield flags yield indent(dedent(fhelp.strip())) cfg_list = ' '.join('--%s.%s=%s' % (clname, prop, val) for clname, props_dict in cfg.items() for prop, val in props_dict.items()) cfg_txt = "Equivalent to: [%s]" % cfg_list yield indent(dedent(cfg_txt)) except Exception as ex: self.log.error( 'Failed collecting help-message for flag %r, due to: %s', flags, ex) raise def print_options(self): """Print the options part of the help.""" print('\n'.join(self.emit_options_help())) def emit_options_help(self): """Yield the lines for the options part of the help.""" if not self.flags and not self.aliases: return header = 'Options' yield header yield '=' * len(header) for p in wrap_paragraphs(self.option_description): yield p yield '' for l in self.emit_flag_help(): yield l for l in self.emit_alias_help(): yield l yield '' def print_subcommands(self): """Print the subcommand part of the help.""" print('\n'.join(self.emit_subcommands_help())) def emit_subcommands_help(self): """Yield the lines for the subcommand part of the help.""" if not self.subcommands: return header = "Subcommands" yield header yield '=' * len(header) for p in wrap_paragraphs( self.subcommand_description.format(app=self.name)): yield p yield '' for subc, (cls, help) in self.subcommands.items(): yield subc if help: yield indent(dedent(help.strip())) yield '' def emit_help_epilogue(self, classes): """Yield the very bottom lines of the help message. If classes=False (the default), print `--help-all` msg. """ if not classes: yield "To see all available configurables, use `--help-all`." yield '' def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ print('\n'.join(self.emit_help(classes=classes))) def emit_help(self, classes=False): """Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ for l in self.emit_description(): yield l for l in self.emit_subcommands_help(): yield l for l in self.emit_options_help(): yield l if classes: help_classes = self._classes_with_config_traits() if help_classes: yield "Class options" yield "=============" for p in wrap_paragraphs(self.keyvalue_description): yield p yield '' for cls in help_classes: yield cls.class_get_help() yield '' for l in self.emit_examples(): yield l for l in self.emit_help_epilogue(classes): yield l def document_config_options(self): """Generate rST format documentation for the config options this application Returns a multiline string. """ return '\n'.join(c.class_config_rst_doc() for c in self._classes_inc_parents()) def print_description(self): """Print the application description.""" print('\n'.join(self.emit_description())) def emit_description(self): """Yield lines with the application description.""" for p in wrap_paragraphs(self.description or self.__doc__): yield p yield '' def print_examples(self): """Print usage and examples (see `emit_examples()`). """ print('\n'.join(self.emit_examples())) def emit_examples(self): """Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: yield "Examples" yield "--------" yield '' yield indent(dedent(self.examples.strip())) yield '' def print_version(self): """Print the version string.""" print(self.version) @catch_config_error def initialize_subcommand(self, subc, argv=None): """Initialize a subcommand with argv.""" subapp, _ = self.subcommands.get(subc) if isinstance(subapp, str): subapp = import_item(subapp) ## Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430) if isinstance(subapp, type) and issubclass(subapp, Application): # Clear existing instances before... self.__class__.clear_instance() # instantiating subapp... self.subapp = subapp.instance(parent=self) elif callable(subapp): # or ask factory to create it... self.subapp = subapp(self) else: raise AssertionError("Invalid mappings for subcommand '%s'!" % subc) # ... and finally initialize subapp. self.subapp.initialize(argv) def flatten_flags(self): """Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ````key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self.classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases = {} for alias, longname in self.aliases.items(): if isinstance(longname, tuple): longname, _ = longname cls, trait = longname.split('.', 1) children = mro_tree[cls] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] if not isinstance(aliases, tuple): alias = (alias, ) for al in alias: aliases[al] = '.'.join([cls, trait]) # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in self.flags.items(): newflag = {} for cls, subdict in flagdict.items(): children = mro_tree[cls] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] if cls in newflag: newflag[cls].update(subdict) else: newflag[cls] = subdict if not isinstance(key, tuple): key = (key, ) for k in key: flags[k] = (newflag, help) return flags, aliases def _create_loader(self, argv, aliases, flags, classes): return KVArgParseConfigLoader(argv, aliases, flags, classes=classes, log=self.log) @catch_config_error def parse_command_line(self, argv=None): """Parse the command line arguments.""" assert not isinstance(argv, str) argv = sys.argv[1:] if argv is None else argv self.argv = [cast_unicode(arg) for arg in argv] if argv and argv[0] == 'help': # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ['-h'] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter return self.initialize_subcommand(subc, subargv) # Arguments after a '--' argument are for the script IPython may be # about to run, not IPython iteslf. For arguments parsed here (help and # version), we want to only search the arguments up to the first # occurrence of '--', which we're calling interpreted_argv. try: interpreted_argv = argv[:argv.index('--')] except ValueError: interpreted_argv = argv if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')): self.print_help('--help-all' in interpreted_argv) self.exit(0) if '--version' in interpreted_argv or '-V' in interpreted_argv: self.print_version() self.exit(0) # flatten flags&aliases, so cl-args get appropriate priority: flags, aliases = self.flatten_flags() classes = tuple(self._classes_with_config_traits()) loader = self._create_loader(argv, aliases, flags, classes=classes) try: self.cli_config = deepcopy(loader.load_config()) except SystemExit: # traitlets 5: no longer print help output on error # help output is huge, and comes after the error raise self.update_config(self.cli_config) # store unparsed args in extra_args self.extra_args = loader.extra_args @classmethod def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False): """Load config files (py,json) by filename and path. yield each config object in turn. """ if not isinstance(path, list): path = [path] for path in path[::-1]: # path list is in descending priority order, so load files backwards: pyloader = cls.python_config_loader_class(basefilename + '.py', path=path, log=log) if log: log.debug("Looking for %s in %s", basefilename, path or os.getcwd()) jsonloader = cls.json_config_loader_class(basefilename + '.json', path=path, log=log) loaded = [] filenames = [] for loader in [pyloader, jsonloader]: config = None try: config = loader.load_config() except ConfigFileNotFound: pass except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or basefilename # problem while running the file if raise_config_file_errors: raise if log: log.error("Exception while loading config file %s", filename, exc_info=True) else: if log: log.debug("Loaded config file: %s", loader.full_filename) if config: for filename, earlier_config in zip(filenames, loaded): collisions = earlier_config.collisions(config) if collisions and log: log.warning( "Collisions detected in {0} and {1} config files." " {1} has higher priority: {2}".format( filename, loader.full_filename, json.dumps(collisions, indent=2), )) yield (config, loader.full_filename) loaded.append(config) filenames.append(loader.full_filename) @property def loaded_config_files(self): """Currently loaded configuration files""" return self._loaded_config_files[:] @catch_config_error def load_config_file(self, filename, path=None): """Load config files by filename and path.""" filename, ext = os.path.splitext(filename) new_config = Config() for (config, filename) in self._load_config_files( filename, path=path, log=self.log, raise_config_file_errors=self.raise_config_file_errors, ): new_config.merge(config) if filename not in self._loaded_config_files: # only add to list of loaded files if not previously loaded self._loaded_config_files.append(filename) # add self.cli_config to preserve CLI config priority new_config.merge(self.cli_config) self.update_config(new_config) def _classes_with_config_traits(self, classes=None): """ Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves. """ if classes is None: classes = self.classes cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True))) for cls in self._classes_inc_parents(classes)) def is_any_parent_included(cls): return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__) ## Mark "empty" classes for inclusion if their parents own-traits, # and loop until no more classes gets marked. # while True: to_incl_orig = cls_to_config.copy() cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls)) for cls, inc_yes in cls_to_config.items()) if cls_to_config == to_incl_orig: break for cl, inc_yes in cls_to_config.items(): if inc_yes: yield cl def generate_config_file(self, classes=None): """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append('') classes = self.classes if classes is None else classes config_classes = list(self._classes_with_config_traits(classes)) for cls in config_classes: lines.append(cls.class_config_section(config_classes)) return '\n'.join(lines) def exit(self, exit_status=0): self.log.debug("Exiting application: %s" % self.name) sys.exit(exit_status) @classmethod def launch_instance(cls, argv=None, **kwargs): """Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it """ app = cls.instance(**kwargs) app.initialize(argv) app.start()
class Application(SingletonConfigurable): """A singleton application with full configuration support.""" # The name of the application, will usually match the name of the command # line application name = Unicode(u'application') # The description of the application that is printed at the beginning # of the help. description = Unicode(u'This is an application.') # default section descriptions option_description = Unicode(option_description) keyvalue_description = Unicode(keyvalue_description) subcommand_description = Unicode(subcommand_description) python_config_loader_class = PyFileConfigLoader json_config_loader_class = JSONFileConfigLoader # The usage and example string that goes at the end of the help string. examples = Unicode() # A sequence of Configurable subclasses whose config=True attributes will # be exposed at the command line. classes = [] @property def _help_classes(self): """Define `App.help_classes` if CLI classes should differ from config file classes""" return getattr(self, 'help_classes', self.classes) @property def _config_classes(self): """Define `App.config_classes` if config file classes should differ from CLI classes.""" return getattr(self, 'config_classes', self.classes) # The version string of this application. version = Unicode(u'0.0') # the argv used to initialize the application argv = List() # The log level for the application log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'), default_value=logging.WARN, config=True, help="Set the log level by value or name.") def _log_level_changed(self, name, old, new): """Adjust the log level when log_level is set.""" if isinstance(new, string_types): new = getattr(logging, new) self.log_level = new self.log.setLevel(new) _log_formatter_cls = LevelFormatter log_datefmt = Unicode("%Y-%m-%d %H:%M:%S", config=True, help="The date format used by logging formatters for %(asctime)s" ) def _log_datefmt_changed(self, name, old, new): self._log_format_changed('log_format', self.log_format, self.log_format) log_format = Unicode("[%(name)s]%(highlevel)s %(message)s", config=True, help="The Logging format template", ) def _log_format_changed(self, name, old, new): """Change the log formatter when log_format is set.""" _log_handler = self.log.handlers[0] _log_formatter = self._log_formatter_cls(fmt=new, datefmt=self.log_datefmt) _log_handler.setFormatter(_log_formatter) log = Instance(logging.Logger) def _log_default(self): """Start logging for this application. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. """ log = logging.getLogger(self.__class__.__name__) log.setLevel(self.log_level) log.propagate = False _log = log # copied from Logger.hasHandlers() (new in Python 3.2) while _log: if _log.handlers: return log if not _log.propagate: break else: _log = _log.parent if sys.executable.endswith('pythonw.exe'): # this should really go to a file, but file-logging is only # hooked up in parallel applications _log_handler = logging.StreamHandler(open(os.devnull, 'w')) else: _log_handler = logging.StreamHandler() _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt) _log_handler.setFormatter(_log_formatter) log.addHandler(_log_handler) return log # the alias map for configurables aliases = Dict({'log-level' : 'Application.log_level'}) # flags for loading Configurables or store_const style flags # flags are loaded from this dict by '--key' flags # this must be a dict of two-tuples, the first element being the Config/dict # and the second being the help string for the flag flags = Dict() def _flags_changed(self, name, old, new): """ensure flags dict is valid""" for key,value in iteritems(new): assert len(value) == 2, "Bad flag: %r:%s"%(key,value) assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value) assert isinstance(value[1], string_types), "Bad flag: %r:%s"%(key,value) # subcommands for launching other applications # if this is not empty, this will be a parent Application # this must be a dict of two-tuples, # the first element being the application class/import string # and the second being the help string for the subcommand subcommands = Dict() # parse_command_line will initialize a subapp, if requested subapp = Instance('traitlets.config.application.Application', allow_none=True) # extra command-line arguments that don't set config values extra_args = List(Unicode) def __init__(self, **kwargs): SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. if self.__class__ not in self.classes: self.classes.insert(0, self.__class__) def _config_changed(self, name, old, new): SingletonConfigurable._config_changed(self, name, old, new) self.log.debug('Config changed:') self.log.debug(repr(new)) @catch_config_error def initialize(self, argv=None): """Do the basic steps to configure me. Override in subclasses. """ self.parse_command_line(argv) def start(self): """Start the app mainloop. Override in subclasses. """ if self.subapp is not None: return self.subapp.start() def print_alias_help(self): """Print the alias part of the help.""" if not self.aliases: return lines = [] classdict = {} for cls in self._help_classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = c for alias, longname in iteritems(self.aliases): classname, traitname = longname.split('.',1) cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] help = cls.class_get_trait_help(trait).splitlines() # reformat first line help[0] = help[0].replace(longname, alias) + ' (%s)'%longname if len(alias) == 1: help[0] = help[0].replace('--%s='%alias, '-%s '%alias) lines.extend(help) # lines.append('') print(os.linesep.join(lines)) def print_flag_help(self): """Print the flag part of the help.""" if not self.flags: return lines = [] for m, (cfg,help) in iteritems(self.flags): prefix = '--' if len(m) > 1 else '-' lines.append(prefix+m) lines.append(indent(dedent(help.strip()))) # lines.append('') print(os.linesep.join(lines)) def print_options(self): if not self.flags and not self.aliases: return lines = ['Options'] lines.append('-'*len(lines[0])) lines.append('') for p in wrap_paragraphs(self.option_description): lines.append(p) lines.append('') print(os.linesep.join(lines)) self.print_flag_help() self.print_alias_help() print() def print_subcommands(self): """Print the subcommand part of the help.""" if not self.subcommands: return lines = ["Subcommands"] lines.append('-'*len(lines[0])) lines.append('') for p in wrap_paragraphs(self.subcommand_description.format( app=self.name)): lines.append(p) lines.append('') for subc, (cls, help) in iteritems(self.subcommands): lines.append(subc) if help: lines.append(indent(dedent(help.strip()))) lines.append('') print(os.linesep.join(lines)) def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ self.print_description() self.print_subcommands() self.print_options() if classes: help_classes = self._help_classes if help_classes: print("Class parameters") print("----------------") print() for p in wrap_paragraphs(self.keyvalue_description): print(p) print() for cls in help_classes: cls.class_print_help() print() else: print("To see all available configurables, use `--help-all`") print() self.print_examples() def print_description(self): """Print the application description.""" for p in wrap_paragraphs(self.description): print(p) print() def print_examples(self): """Print usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: print("Examples") print("--------") print() print(indent(dedent(self.examples.strip()))) print() def print_version(self): """Print the version string.""" print(self.version) def update_config(self, config): """Fire the traits events when the config is updated.""" # Save a copy of the current config. newconfig = deepcopy(self.config) # Merge the new config into the current one. newconfig.merge(config) # Save the combined config as self.config, which triggers the traits # events. self.config = newconfig @catch_config_error def initialize_subcommand(self, subc, argv=None): """Initialize a subcommand with argv.""" subapp,help = self.subcommands.get(subc) if isinstance(subapp, string_types): subapp = import_item(subapp) # clear existing instances self.__class__.clear_instance() # instantiate self.subapp = subapp.instance(config=self.config) # and initialize subapp self.subapp.initialize(argv) def flatten_flags(self): """flatten flags and aliases, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self._help_classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases = {} for alias, cls_trait in iteritems(self.aliases): cls,trait = cls_trait.split('.',1) children = mro_tree[cls] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] aliases[alias] = '.'.join([cls,trait]) # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in iteritems(self.flags): newflag = {} for cls, subdict in iteritems(flagdict): children = mro_tree[cls] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] newflag[cls] = subdict flags[key] = (newflag, help) return flags, aliases @catch_config_error def parse_command_line(self, argv=None): """Parse the command line arguments.""" argv = sys.argv[1:] if argv is None else argv self.argv = [ py3compat.cast_unicode(arg) for arg in argv ] if argv and argv[0] == 'help': # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ['-h'] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter return self.initialize_subcommand(subc, subargv) # Arguments after a '--' argument are for the script IPython may be # about to run, not IPython iteslf. For arguments parsed here (help and # version), we want to only search the arguments up to the first # occurrence of '--', which we're calling interpreted_argv. try: interpreted_argv = argv[:argv.index('--')] except ValueError: interpreted_argv = argv if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')): self.print_help('--help-all' in interpreted_argv) self.exit(0) if '--version' in interpreted_argv or '-V' in interpreted_argv: self.print_version() self.exit(0) # flatten flags&aliases, so cl-args get appropriate priority: flags,aliases = self.flatten_flags() loader = KVArgParseConfigLoader(argv=argv, aliases=aliases, flags=flags, log=self.log) config = loader.load_config() self.update_config(config) # store unparsed args in extra_args self.extra_args = loader.extra_args @classmethod def _load_config_files(cls, basefilename, path=None, log=None): """Load config files (py,json) by filename and path. yield each config object in turn. """ if not isinstance(path, list): path = [path] for path in path[::-1]: # path list is in descending priority order, so load files backwards: pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log) jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log) config = None for loader in [pyloader, jsonloader]: try: config = loader.load_config() except ConfigFileNotFound: pass except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or basefilename # problem while running the file if log: log.error("Exception while loading config file %s", filename, exc_info=True) else: if log: log.debug("Loaded config file: %s", loader.full_filename) if config: yield config raise StopIteration @catch_config_error def load_config_file(self, filename, path=None): """Load config files by filename and path.""" filename, ext = os.path.splitext(filename) loaded = [] for config in self._load_config_files(filename, path=path, log=self.log): loaded.append(config) self.update_config(config) if len(loaded) > 1: collisions = loaded[0].collisions(loaded[1]) if collisions: self.log.warn("Collisions detected in {0}.py and {0}.json config files." " {0}.json has higher priority: {1}".format( filename, json.dumps(collisions, indent=2), )) def generate_config_file(self): """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append('') for cls in self._config_classes: lines.append(cls.class_config_section()) return '\n'.join(lines) def exit(self, exit_status=0): self.log.debug("Exiting application: %s" % self.name) sys.exit(exit_status) @classmethod def launch_instance(cls, argv=None, **kwargs): """Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it """ app = cls.instance(**kwargs) app.initialize(argv) app.start()
class Application(SingletonConfigurable): """A singleton application with full configuration support.""" # The name of the application, will usually match the name of the command # line application name = Unicode("application") # The description of the application that is printed at the beginning # of the help. description = Unicode("This is an application.") # default section descriptions option_description = Unicode(option_description) keyvalue_description = Unicode(keyvalue_description) subcommand_description = Unicode(subcommand_description) python_config_loader_class = PyFileConfigLoader json_config_loader_class = JSONFileConfigLoader # The usage and example string that goes at the end of the help string. examples = Unicode() # A sequence of Configurable subclasses whose config=True attributes will # be exposed at the command line. classes: t.List[t.Type[t.Any]] = [] def _classes_inc_parents(self, classes=None): """Iterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once. """ if classes is None: classes = self.classes seen = set() for c in classes: # We want to sort parents before children, so we reverse the MRO for parent in reversed(c.mro()): if issubclass(parent, Configurable) and (parent not in seen): seen.add(parent) yield parent # The version string of this application. version = Unicode("0.0") # the argv used to initialize the application argv = List() # Whether failing to load config files should prevent startup raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR) # The log level for the application log_level = Enum( (0, 10, 20, 30, 40, 50, "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"), default_value=logging.WARN, help="Set the log level by value or name.", ).tag(config=True) _log_formatter_cls = LevelFormatter log_datefmt = Unicode( "%Y-%m-%d %H:%M:%S", help="The date format used by logging formatters for %(asctime)s" ).tag(config=True) log_format = Unicode( "[%(name)s]%(highlevel)s %(message)s", help="The Logging format template", ).tag(config=True) def get_default_logging_config(self): """Return the base logging configuration. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log handler level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. The ``logging_config`` trait is merged into this allowing for finer control of logging. """ config: t.Dict[str, t.Any] = { "version": 1, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "console", "level": logging.getLevelName(self.log_level), "stream": "ext://sys.stderr", }, }, "formatters": { "console": { "class": ( f"{self._log_formatter_cls.__module__}" f".{self._log_formatter_cls.__name__}" ), "format": self.log_format, "datefmt": self.log_datefmt, }, }, "loggers": { self.__class__.__name__: { "level": "DEBUG", "handlers": ["console"], } }, "disable_existing_loggers": False, } if sys.executable and sys.executable.endswith("pythonw.exe"): # disable logging # (this should really go to a file, but file-logging is only # hooked up in parallel applications) del config["handlers"]["loggers"] return config @observe("log_datefmt", "log_format", "log_level", "logging_config") def _observe_logging_change(self, change): # convert log level strings to ints log_level = self.log_level if isinstance(log_level, str): self.log_level = getattr(logging, log_level) self._configure_logging() @observe("log", type="default") def _observe_logging_default(self, change): self._configure_logging() def _configure_logging(self): config = self.get_default_logging_config() nested_update(config, self.logging_config or {}) dictConfig(config) # make a note that we have configured logging self._logging_configured = True @default("log") def _log_default(self): """Start logging for this application.""" log = logging.getLogger(self.__class__.__name__) log.propagate = False _log = log # copied from Logger.hasHandlers() (new in Python 3.2) while _log: if _log.handlers: return log if not _log.propagate: break else: _log = _log.parent # type:ignore[assignment] return log logging_config = Dict( help=""" Configure additional log handlers. The default stderr logs handler is configured by the log_level, log_datefmt and log_format settings. This configuration can be used to configure additional handlers (e.g. to output the log to a file) or for finer control over the default handlers. If provided this should be a logging configuration dictionary, for more information see: https://docs.python.org/3/library/logging.config.html#logging-config-dictschema This dictionary is merged with the base logging configuration which defines the following: * A logging formatter intended for interactive use called ``console``. * A logging handler that writes to stderr called ``console`` which uses the formatter ``console``. * A logger with the name of this application set to ``DEBUG`` level. This example adds a new handler that writes to a file: .. code-block:: python c.Application.logging_configuration = { 'handlers': { 'file': { 'class': 'logging.FileHandler', 'level': 'DEBUG', 'filename': '<path/to/file>', } }, 'loggers': { '<application-name>': { 'level': 'DEBUG', # NOTE: if you don't list the default "console" # handler here then it will be disabled 'handlers': ['console', 'file'], }, } } """, ).tag(config=True) #: the alias map for configurables #: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`. #: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text). aliases: t.Dict[str, str] = {"log-level": "Application.log_level"} # flags for loading Configurables or store_const style flags # flags are loaded from this dict by '--key' flags # this must be a dict of two-tuples, the first element being the Config/dict # and the second being the help string for the flag flags: t.Dict[str, t.Any] = { "debug": ( { "Application": { "log_level": logging.DEBUG, }, }, "Set log-level to debug, for the most verbose logging.", ), "show-config": ( { "Application": { "show_config": True, }, }, "Show the application's configuration (human-readable format)", ), "show-config-json": ( { "Application": { "show_config_json": True, }, }, "Show the application's configuration (json format)", ), } # subcommands for launching other applications # if this is not empty, this will be a parent Application # this must be a dict of two-tuples, # the first element being the application class/import string # and the second being the help string for the subcommand subcommands = Dict() # parse_command_line will initialize a subapp, if requested subapp = Instance("traitlets.config.application.Application", allow_none=True) # extra command-line arguments that don't set config values extra_args = List(Unicode()) cli_config = Instance( Config, (), {}, help="""The subset of our configuration that came from the command-line We re-load this configuration after loading config files, to ensure that it maintains highest priority. """, ) _loaded_config_files = List() show_config = Bool( help="Instead of starting the Application, dump configuration to stdout" ).tag(config=True) show_config_json = Bool( help="Instead of starting the Application, dump configuration to stdout (as JSON)" ).tag(config=True) @observe("show_config_json") def _show_config_json_changed(self, change): self.show_config = change.new @observe("show_config") def _show_config_changed(self, change): if change.new: self._save_start = self.start self.start = self.start_show_config # type:ignore[assignment] def __init__(self, **kwargs): SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. cls = self.__class__ if cls not in self.classes: if self.classes is cls.classes: # class attr, assign instead of insert self.classes = [cls] + self.classes else: self.classes.insert(0, self.__class__) @observe("config") @observe_compat def _config_changed(self, change): super()._config_changed(change) self.log.debug("Config changed: %r", change.new) @catch_config_error def initialize(self, argv=None): """Do the basic steps to configure me. Override in subclasses. """ self.parse_command_line(argv) def start(self): """Start the app mainloop. Override in subclasses. """ if self.subapp is not None: return self.subapp.start() def start_show_config(self): """start function used when show_config is True""" config = self.config.copy() # exclude show_config flags from displayed config for cls in self.__class__.mro(): if cls.__name__ in config: cls_config = config[cls.__name__] cls_config.pop("show_config", None) cls_config.pop("show_config_json", None) if self.show_config_json: json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr) # add trailing newline sys.stdout.write("\n") return if self._loaded_config_files: print("Loaded config files:") for f in self._loaded_config_files: print(" " + f) print() for classname in sorted(config): class_config = config[classname] if not class_config: continue print(classname) pformat_kwargs: t.Dict[str, t.Any] = dict(indent=4, compact=True) for traitname in sorted(class_config): value = class_config[traitname] print( " .{} = {}".format( traitname, pprint.pformat(value, **pformat_kwargs), ) ) def print_alias_help(self): """Print the alias parts of the help.""" print("\n".join(self.emit_alias_help())) def emit_alias_help(self): """Yield the lines for alias part of the help.""" if not self.aliases: return classdict = {} for cls in self.classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = c for alias, longname in self.aliases.items(): try: if isinstance(longname, tuple): longname, fhelp = longname else: fhelp = None classname, traitname = longname.split(".")[-2:] longname = classname + "." + traitname cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] fhelp = cls.class_get_trait_help(trait, helptext=fhelp).splitlines() if not isinstance(alias, tuple): alias = (alias,) # type:ignore[assignment] alias = sorted(alias, key=len) # type:ignore[assignment] alias = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in alias) # reformat first line fhelp[0] = fhelp[0].replace("--" + longname, alias) yield from fhelp yield indent("Equivalent to: [--%s]" % longname) except Exception as ex: self.log.error("Failed collecting help-message for alias %r, due to: %s", alias, ex) raise def print_flag_help(self): """Print the flag part of the help.""" print("\n".join(self.emit_flag_help())) def emit_flag_help(self): """Yield the lines for the flag part of the help.""" if not self.flags: return for flags, (cfg, fhelp) in self.flags.items(): try: if not isinstance(flags, tuple): flags = (flags,) # type:ignore[assignment] flags = sorted(flags, key=len) # type:ignore[assignment] flags = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in flags) yield flags yield indent(dedent(fhelp.strip())) cfg_list = " ".join( f"--{clname}.{prop}={val}" for clname, props_dict in cfg.items() for prop, val in props_dict.items() ) cfg_txt = "Equivalent to: [%s]" % cfg_list yield indent(dedent(cfg_txt)) except Exception as ex: self.log.error("Failed collecting help-message for flag %r, due to: %s", flags, ex) raise def print_options(self): """Print the options part of the help.""" print("\n".join(self.emit_options_help())) def emit_options_help(self): """Yield the lines for the options part of the help.""" if not self.flags and not self.aliases: return header = "Options" yield header yield "=" * len(header) for p in wrap_paragraphs(self.option_description): yield p yield "" yield from self.emit_flag_help() yield from self.emit_alias_help() yield "" def print_subcommands(self): """Print the subcommand part of the help.""" print("\n".join(self.emit_subcommands_help())) def emit_subcommands_help(self): """Yield the lines for the subcommand part of the help.""" if not self.subcommands: return header = "Subcommands" yield header yield "=" * len(header) for p in wrap_paragraphs(self.subcommand_description.format(app=self.name)): yield p yield "" for subc, (_, help) in self.subcommands.items(): yield subc if help: yield indent(dedent(help.strip())) yield "" def emit_help_epilogue(self, classes): """Yield the very bottom lines of the help message. If classes=False (the default), print `--help-all` msg. """ if not classes: yield "To see all available configurables, use `--help-all`." yield "" def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ print("\n".join(self.emit_help(classes=classes))) def emit_help(self, classes=False): """Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ yield from self.emit_description() yield from self.emit_subcommands_help() yield from self.emit_options_help() if classes: help_classes = self._classes_with_config_traits() if help_classes: yield "Class options" yield "=============" for p in wrap_paragraphs(self.keyvalue_description): yield p yield "" for cls in help_classes: yield cls.class_get_help() yield "" yield from self.emit_examples() yield from self.emit_help_epilogue(classes) def document_config_options(self): """Generate rST format documentation for the config options this application Returns a multiline string. """ return "\n".join(c.class_config_rst_doc() for c in self._classes_inc_parents()) def print_description(self): """Print the application description.""" print("\n".join(self.emit_description())) def emit_description(self): """Yield lines with the application description.""" for p in wrap_paragraphs(self.description or self.__doc__ or ""): yield p yield "" def print_examples(self): """Print usage and examples (see `emit_examples()`).""" print("\n".join(self.emit_examples())) def emit_examples(self): """Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: yield "Examples" yield "--------" yield "" yield indent(dedent(self.examples.strip())) yield "" def print_version(self): """Print the version string.""" print(self.version) @catch_config_error def initialize_subcommand(self, subc, argv=None): """Initialize a subcommand with argv.""" subapp, _ = self.subcommands.get(subc) if isinstance(subapp, str): subapp = import_item(subapp) # Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430) if isinstance(subapp, type) and issubclass(subapp, Application): # Clear existing instances before... self.__class__.clear_instance() # instantiating subapp... self.subapp = subapp.instance(parent=self) elif callable(subapp): # or ask factory to create it... self.subapp = subapp(self) # type:ignore[call-arg] else: raise AssertionError("Invalid mappings for subcommand '%s'!" % subc) # ... and finally initialize subapp. self.subapp.initialize(argv) def flatten_flags(self): """Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ````key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self.classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases: t.Dict[str, str] = {} for alias, longname in self.aliases.items(): if isinstance(longname, tuple): longname, _ = longname cls, trait = longname.split(".", 1) # type:ignore[assignment] children = mro_tree[cls] # type:ignore[index] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] # type:ignore[assignment] if not isinstance(aliases, tuple): alias = (alias,) # type:ignore[assignment] for al in alias: aliases[al] = ".".join([cls, trait]) # type:ignore[list-item] # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in self.flags.items(): newflag: t.Dict[t.Any, t.Any] = {} for cls, subdict in flagdict.items(): children = mro_tree[cls] # type:ignore[index] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] # type:ignore[assignment] if cls in newflag: newflag[cls].update(subdict) else: newflag[cls] = subdict if not isinstance(key, tuple): key = (key,) # type:ignore[assignment] for k in key: flags[k] = (newflag, help) return flags, aliases def _create_loader(self, argv, aliases, flags, classes): return KVArgParseConfigLoader(argv, aliases, flags, classes=classes, log=self.log) @catch_config_error def parse_command_line(self, argv=None): """Parse the command line arguments.""" assert not isinstance(argv, str) argv = sys.argv[1:] if argv is None else argv self.argv = [cast_unicode(arg) for arg in argv] if argv and argv[0] == "help": # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ["-h"] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r"^\w(\-?\w)*$", subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter return self.initialize_subcommand(subc, subargv) # Arguments after a '--' argument are for the script IPython may be # about to run, not IPython iteslf. For arguments parsed here (help and # version), we want to only search the arguments up to the first # occurrence of '--', which we're calling interpreted_argv. try: interpreted_argv = argv[: argv.index("--")] except ValueError: interpreted_argv = argv if any(x in interpreted_argv for x in ("-h", "--help-all", "--help")): self.print_help("--help-all" in interpreted_argv) self.exit(0) if "--version" in interpreted_argv or "-V" in interpreted_argv: self.print_version() self.exit(0) # flatten flags&aliases, so cl-args get appropriate priority: flags, aliases = self.flatten_flags() classes = tuple(self._classes_with_config_traits()) loader = self._create_loader(argv, aliases, flags, classes=classes) try: self.cli_config = deepcopy(loader.load_config()) except SystemExit: # traitlets 5: no longer print help output on error # help output is huge, and comes after the error raise self.update_config(self.cli_config) # store unparsed args in extra_args self.extra_args = loader.extra_args @classmethod def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False): """Load config files (py,json) by filename and path. yield each config object in turn. """ if not isinstance(path, list): path = [path] for path in path[::-1]: # path list is in descending priority order, so load files backwards: pyloader = cls.python_config_loader_class(basefilename + ".py", path=path, log=log) if log: log.debug("Looking for %s in %s", basefilename, path or os.getcwd()) jsonloader = cls.json_config_loader_class(basefilename + ".json", path=path, log=log) loaded: t.List[t.Any] = [] filenames: t.List[str] = [] for loader in [pyloader, jsonloader]: config = None try: config = loader.load_config() except ConfigFileNotFound: pass except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or basefilename # problem while running the file if raise_config_file_errors: raise if log: log.error("Exception while loading config file %s", filename, exc_info=True) else: if log: log.debug("Loaded config file: %s", loader.full_filename) if config: for filename, earlier_config in zip(filenames, loaded): collisions = earlier_config.collisions(config) if collisions and log: log.warning( "Collisions detected in {0} and {1} config files." " {1} has higher priority: {2}".format( filename, loader.full_filename, json.dumps(collisions, indent=2), ) ) yield (config, loader.full_filename) loaded.append(config) filenames.append(loader.full_filename) @property def loaded_config_files(self): """Currently loaded configuration files""" return self._loaded_config_files[:] @catch_config_error def load_config_file(self, filename, path=None): """Load config files by filename and path.""" filename, ext = os.path.splitext(filename) new_config = Config() for (config, filename) in self._load_config_files( filename, path=path, log=self.log, raise_config_file_errors=self.raise_config_file_errors, ): new_config.merge(config) if ( filename not in self._loaded_config_files ): # only add to list of loaded files if not previously loaded self._loaded_config_files.append(filename) # add self.cli_config to preserve CLI config priority new_config.merge(self.cli_config) self.update_config(new_config) def _classes_with_config_traits(self, classes=None): """ Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves. """ if classes is None: classes = self.classes cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True))) for cls in self._classes_inc_parents(classes) ) def is_any_parent_included(cls): return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__) # Mark "empty" classes for inclusion if their parents own-traits, # and loop until no more classes gets marked. # while True: to_incl_orig = cls_to_config.copy() cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls)) for cls, inc_yes in cls_to_config.items() ) if cls_to_config == to_incl_orig: break for cl, inc_yes in cls_to_config.items(): if inc_yes: yield cl def generate_config_file(self, classes=None): """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append("") classes = self.classes if classes is None else classes config_classes = list(self._classes_with_config_traits(classes)) for cls in config_classes: lines.append(cls.class_config_section(config_classes)) return "\n".join(lines) def close_handlers(self): if getattr(self, "_logging_configured", False): # don't attempt to close handlers unless they have been opened # (note accessing self.log.handlers will create handlers if they # have not yet been initialised) for handler in self.log.handlers: with suppress(Exception): handler.close() self._logging_configured = False def exit(self, exit_status=0): self.log.debug("Exiting application: %s" % self.name) self.close_handlers() sys.exit(exit_status) def __del__(self): self.close_handlers() @classmethod def launch_instance(cls, argv=None, **kwargs): """Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it """ app = cls.instance(**kwargs) app.initialize(argv) app.start()
class MixedContentsManager(ContentsManager): filesystem_scheme = List([{ 'root': 'local', 'contents': "IPython.html.services.contents.filemanager.FileContentsManager" }, { 'root': 'gdrive', 'contents': 'jupyterdrive.clientsidenbmanager.ClientSideContentsManager' }], help=""" List of virtual mount point name and corresponding contents manager """, config=True) def __init__(self, **kwargs): super(MixedContentsManager, self).__init__(**kwargs) self.managers = {} ## check consistency of scheme. if not len(set(map(lambda x: x['root'], self.filesystem_scheme))) == len( self.filesystem_scheme): raise ValueError( 'Scheme should not mount two contents manager on the same mountpoint' ) kwargs.update({'parent': self}) for scheme in self.filesystem_scheme: manager_class = import_item(scheme['contents']) self.managers[scheme['root']] = manager_class(**kwargs) def path_dispatch1(method): def _wrapper_method(self, path, *args, **kwargs): sentinel, _path, path = _split_path(path) man = self.managers.get(sentinel, None) if man is not None: meth = getattr(man, method.__name__) sub = meth('/'.join(_path), *args, **kwargs) return sub else: return method(self, path, *args, **kwargs) return _wrapper_method def path_dispatch2(method): def _wrapper_method(self, other, path, *args, **kwargs): sentinel, _path, path = _split_path(path) man = self.managers.get(sentinel, None) if man is not None: meth = getattr(man, method.__name__) sub = meth(other, '/'.join(_path), *args, **kwargs) return sub else: return method(self, other, path, *args, **kwargs) return _wrapper_method def path_dispatch_kwarg(method): def _wrapper_method(self, path=''): sentinel, _path, path = _split_path(path) man = self.managers.get(sentinel, None) if man is not None: meth = getattr(man, method.__name__) sub = meth(path='/'.join(_path)) return sub else: return method(self, path=path) return _wrapper_method # ContentsManager API part 1: methods that must be # implemented in subclasses. @path_dispatch1 def dir_exists(self, path): ## root exists if len(path) == 0: return True if path in self.managers.keys(): return True return False @path_dispatch1 def is_hidden(self, path): if (len(path) == 0) or path in self.managers.keys(): return False raise NotImplementedError('....' + path) @path_dispatch_kwarg def file_exists(self, path=''): if len(path) == 0: return False raise NotImplementedError('NotImplementedError') @path_dispatch1 def exists(self, path): if len(path) == 0: return True raise NotImplementedError('NotImplementedError') @path_dispatch1 def get(self, path, **kwargs): if len(path) == 0: return [{'type': 'directory'}] raise NotImplementedError('NotImplementedError') @path_dispatch2 def save(self, model, path): raise NotImplementedError('NotImplementedError') def update(self, model, path): sentinel, listpath, path = _split_path(path) m_sentinel, m_listpath, orig_path = _split_path(model['path']) if sentinel != m_sentinel: raise ValueError( 'Does not know how to move model across mountpoints') model['path'] = '/'.join(m_listpath) man = self.managers.get(sentinel, None) if man is not None: meth = getattr(man, 'update') sub = meth(model, '/'.join(listpath)) return sub else: return self.method(model, path) @path_dispatch1 def delete(self, path): raise NotImplementedError('NotImplementedError') @path_dispatch1 def create_checkpoint(self, path): raise NotImplementedError('NotImplementedError') @path_dispatch1 def list_checkpoints(self, path): raise NotImplementedError('NotImplementedError') @path_dispatch2 def restore_checkpoint(self, checkpoint_id, path): raise NotImplementedError('NotImplementedError') @path_dispatch2 def delete_checkpoint(self, checkpoint_id, path): raise NotImplementedError('NotImplementedError') # ContentsManager API part 2: methods that have useable default # implementations, but can be overridden in subclasses. # TODO (route optional methods too) ## Path dispatch on args 2 and 3 for rename. def path_dispatch_rename(rename_like_method): """ decorator for rename-like function, that need dispatch on 2 arguments """ def _wrapper_method(self, old_path, new_path): old_path, _old_path, old_sentinel = _split_path(old_path) new_path, _new_path, new_sentinel = _split_path(new_path) if old_sentinel != new_sentinel: raise ValueError( 'Does not know how to move things across contents manager mountpoints' ) else: sentinel = new_sentinel man = self.managers.get(sentinel, None) if man is not None: rename_meth = getattr(man, rename_like_method.__name__) sub = rename_meth('/'.join(_old_path), '/'.join(_new_path)) return sub else: return rename_meth(self, old_path, new_path) return _wrapper_method @path_dispatch_rename def rename_file(self, old_path, new_path): """Rename a file.""" raise NotImplementedError('must be implemented in a subclass') @path_dispatch_rename def rename(self, old_path, new_path): """Rename a file.""" raise NotImplementedError('must be implemented in a subclass')
class MixedContentsManager(LargeFileManager): mixed_path = Unicode( "datahub", help="path were the mixed content managers will reside", config=True) filesystem_scheme = List( [ { "root": "space1", "class": "onedatafs_jupyter.OnedataFSContentsManager", "config": { "space": u"/space1" }, }, { "root": "space2", "class": "onedatafs_jupyter.OnedataFSContentsManager", "config": { "space": u"/space2" }, }, ], help= """List of virtual mount point name and corresponding contents manager""", config=True, ) files_handler_class = MixedFileHandler def __init__(self, **kwargs): super(MixedContentsManager, self).__init__(**kwargs) self.managers = {} ## check consistency of scheme. if not len(set(map(lambda x: x["root"], self.filesystem_scheme))) == len( self.filesystem_scheme): raise ValueError( "Scheme should not mount two contents manager on the same mountpoint" ) kwargs.update({"parent": self}) for scheme in self.filesystem_scheme: manager_class = import_item(scheme["class"]) self.managers[scheme["root"]] = manager_class(**kwargs) if scheme["config"]: for k, v in scheme["config"].items(): setattr(self.managers[scheme["root"]], k, v) self.log.debug("MANAGERS: %s", self.managers) def _fix_paths(self, sub, base_path): self.log.debug("RETURNING: %s %s", sub, base_path) if type(sub) != dict: return sub if "path" in sub: sub["path"] = os.path.join(base_path, sub["path"]) if sub.get("type") == "directory" and sub.get("content"): for e in sub.get("content"): if "path" in e: e["path"] = os.path.join(base_path, e["path"].lstrip("/")) return sub def _get_cm(self, sentinel, listpath): self.log.debug("Finding cm for %s and %s", sentinel, listpath) if sentinel != self.mixed_path or not len(listpath): self.log.debug("Not found!") return None self.log.debug("FIND %s!", listpath[0]) return self.managers.get(listpath[0], None) def path_dispatch1(method): def _wrapper_method(self, path, *args, **kwargs): sentinel, _path, path = _split_path(path) self.log.debug( "M: %s, S: %s, M: %s P: %s", method.__name__, sentinel, self.mixed_path, path, ) man = self._get_cm(sentinel, _path) if man is not None: base_path = os.path.join(sentinel, _path[0]) meth = getattr(man, method.__name__) sub = meth("/".join(_path[1:]), *args, **kwargs) return self._fix_paths(sub, base_path) else: return method(self, path, *args, **kwargs) return _wrapper_method def path_dispatch2(method): def _wrapper_method(self, other, path, *args, **kwargs): sentinel, _path, path = _split_path(path) self.log.debug( "M: %s, S: %s, M: %s P: %s", method.__name__, sentinel, self.mixed_path, path, ) man = self._get_cm(sentinel, _path) if man is not None: base_path = os.path.join(sentinel, _path[0]) meth = getattr(man, method.__name__) sub = meth(other, "/".join(_path[1:]), *args, **kwargs) return self._fix_paths(sub, base_path) else: return method(self, other, path, *args, **kwargs) return _wrapper_method def path_dispatch_kwarg(method): def _wrapper_method(self, path=""): sentinel, _path, path = _split_path(path) self.log.debug( "M: %s, S: %s, M: %s P: %s", method.__name__, sentinel, self.mixed_path, path, ) man = self._get_cm(sentinel, _path) if man is not None: base_path = os.path.join(sentinel, _path[0]) meth = getattr(man, method.__name__) sub = meth(path="/".join(_path[1:])) return self._fix_paths(sub, base_path) else: return method(self, path=path) return _wrapper_method # ContentsManager API part 1: methods that must be # implemented in subclasses. @path_dispatch1 def dir_exists(self, path): ## root exists if (len(path) == 0) or path == self.mixed_path: return True return super(MixedContentsManager, self).dir_exists(os.path.join("/", path)) @path_dispatch1 def is_hidden(self, path): if (len(path) == 0) or path == self.mixed_path: return False return super(MixedContentsManager, self).is_hidden(os.path.join("/", path)) @path_dispatch_kwarg def file_exists(self, path=""): if (len(path) == 0) or path == self.mixed_path: return False return super(MixedContentsManager, self).file_exists(os.path.join("/", path)) @path_dispatch1 def exists(self, path): if (len(path) == 0) or path == self.mixed_path: return True return super(MixedContentsManager, self).exists(os.path.join("/", path)) @path_dispatch1 def get(self, path, **kwargs): if len(path) == 0: root = super(MixedContentsManager, self).get("/", **kwargs) root["content"].append({ "type": "directory", "name": self.mixed_path, "path": self.mixed_path }) return root if path == self.mixed_path: root = { "type": "directory", "name": self.mixed_path, "path": self.mixed_path, "content": [], "last_modified": None, "created": None, "format": "json", "mimetype": None, "size": None, "writable": False, "type": "directory", } lm = [] for subpath, manager in self.managers.items(): try: d = manager.get("/", **kwargs) d["content"] = None d["name"] = subpath d["path"] = os.path.join(self.mixed_path, subpath) root["content"].append(d) lm.append(d["last_modified"]) # TODO: have a better exception here except: pass root["last_modified"] = max(lm) root["created"] = min(lm) return root return super(MixedContentsManager, self).get(os.path.join("/", path), **kwargs) @path_dispatch2 def save(self, model, path): return super(MixedContentsManager, self).save(model, path) def update(self, model, path): sentinel, listpath, _path = _split_path(path) m_sentinel, m_listpath, orig_path = _split_path(model["path"]) self.log.debug("UPDATE!") self.log.debug("s %s, l %s, p %s", sentinel, listpath, path) self.log.debug("s %s, l %s, p %s", m_sentinel, m_listpath, orig_path) man = self._get_cm(sentinel, listpath) m_man = self._get_cm(m_sentinel, m_listpath) if man != m_man: raise ValueError( "Does not know how to move model across mountpoints") if man is not None: base_path = os.path.join(sentinel, listpath[0]) model["path"] = "/".join(m_listpath[1:]) meth = getattr(man, "update") sub = meth(model, "/".join(listpath[1:])) return self._fix_paths(sub, base_path) else: return super(MixedContentsManager, self).update(model, path) @path_dispatch1 def delete(self, path): return super(MixedContentsManager, self).delete(path) @path_dispatch1 def create_checkpoint(self, path): return super(MixedContentsManager, self).create_checkpoint(path) @path_dispatch1 def list_checkpoints(self, path): return super(MixedContentsManager, self).list_checkpoints(path) @path_dispatch2 def restore_checkpoint(self, checkpoint_id, path): return super(MixedContentsManager, self).restore_checkpoints(path) @path_dispatch2 def delete_checkpoint(self, checkpoint_id, path): return super(MixedContentsManager, self).delete_checkpoints(path) # ContentsManager API part 2: methods that have useable default # implementations, but can be overridden in subclasses. # TODO (route optional methods too) # FIXME(enolfc) This is not yet reviewed ## Path dispatch on args 2 and 3 for rename. def path_dispatch_rename(rename_like_method): """ decorator for rename-like function, that need dispatch on 2 arguments """ def _wrapper_method(self, old_path, new_path): old_sentinel, old_listpath, old_path = _split_path(old_path) new_sentinel, new_listpath, new_path = _split_path(new_path) cm = self._get_cm(old_sentinel, old_path) new_cm = self._get_cm(new_sentinel, new_path) if cm != new_cm: raise ValueError( "Does not know how to move things across contents manager mountpoints" ) if not cm: if old_sentinel == self.mixed_path or new_sentinel == self.mixed_path: raise ValueError( "Does not know how to move things across contents manager mountpoints" ) return rename_like_method(self, old_path, new_path) else: base_path = os.path.join(sentinel, old_listpath[0]) rename_meth = getattr(cm, rename_like_method.__name__) sub = rename_meth("/".join(old_listpath[1:]), "/".join(new_listpath[1:])) return self.fix_path(sub) return _wrapper_method @path_dispatch_rename def rename_file(self, old_path, new_path): return super(MixedContentsManager, self).rename_file(old_path, new_path) @path_dispatch_rename def rename(self, old_path, new_path): """Rename a file.""" return super(MixedContentsManager, self).rename(old_path, new_path)
class VoilaKernelManager(base_class): """This class adds pooling heated kernels and pre-rendered notebook feature to a normal kernel manager. The 'pooling heated kernels' part is heavily inspired from `hotpot_km`(https://github.com/voila-dashboards/hotpot_km) library. """ kernel_pools_config = Dict( config=True, help='''Mapping from notebook name to the kernel configuration like: number of started kernels to keep on standby, environment variables used to start kernel''', ) preheat_blacklist = List([], config=True, help='List of notebooks which do not use pre-heated kernel.') fill_delay = Float( 1, config=True, help='Wait time before re-filling the pool after a kernel is used', ) @default('kernel_pools_config') def _kernel_pools_config(self): return {'default': {'pool_size': max(default_pool_size, 0), 'kernel_env_variables': {}}} def __init__(self, **kwargs): super().__init__(**kwargs) self._wait_at_startup = True self.notebook_data: TypeDict = {} self._pools: TypeDict[str, List[TypeDict]] = {} self.root_dir = self.parent.root_dir if self.parent.notebook_path is not None: self.notebook_path = os.path.relpath( self.parent.notebook_path, self.root_dir ) self.fill_if_needed(delay=0, notebook_name=self.notebook_path) else: self.notebook_path = None all_notebooks = [ x.relative_to(self.root_dir) for x in list(Path(self.root_dir).rglob('*.ipynb')) if self._notebook_filter(x) ] for nb in all_notebooks: self.fill_if_needed(delay=0, notebook_name=str(nb)) async def get_rendered_notebook( self, notebook_name: str, **kwargs ) -> Tuple[asyncio.Task, TypeList[str]]: """ Get the notebook rendering task and the rendered cell. By setting the `stop_generator` to True, the running task `render_task` used for rendering notebook will be stopped after finishing the running cell. The results of this task will contain the rendered cells and a generator for continuing render the remaining cells. We need to return also `renderer.rendered_cache` since it contains the rendered cells before the moment we set `stop_generator` to `True`, so that we can flush data immediately without waiting for running cell to be finished. Args: notebook_name (str): Path to notebook Raises: NameError: Raised if no notebook is provided. Exception: Raised if the kernel pool is empty. Returns: Tuple[asyncio.Task, List[str]]: """ if notebook_name is None: raise NameError('Notebook name must be provided!') if (len(self._pools.get(notebook_name, ())) == 0): raise Exception(f'Kernel pool for {notebook_name} is empty!') pool_item = self._pools[notebook_name].pop(0) content = await pool_item renderer: NotebookRenderer = content['renderer'] render_task: asyncio.Task = content['task'] kernel_id: str = content['kernel_id'] renderer.stop_generator = True self.log.info('Using pre-heated kernel: %s for %s', kernel_id, notebook_name) self.fill_if_needed(delay=None, notebook_name=notebook_name, **kwargs) return render_task, renderer.rendered_cache, kernel_id def get_pool_size(self, notebook_name: str) -> int: return len(self._pools.get(notebook_name, [])) def fill_if_needed( self, delay: Union[float, None] = None, notebook_name: Union[str, None] = None, **kwargs, ) -> None: """Start kernels until the pool is full Args: - delay (Union[float, None], optional): Delay time before starting refill kernel. Defaults to None. - notebook_name (Union[str, None], optional): Name of notebook to create kernel pool. Defaults to None. """ delay = delay if delay is not None else self.fill_delay try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) default_config: dict = self.kernel_pools_config.get('default', {}) notebook_config: dict = self.kernel_pools_config.get( notebook_name, default_config ) kernel_env_variables: dict = notebook_config.get( 'kernel_env_variables', default_config.get('kernel_env_variables', {}) ) kernel_size: int = notebook_config.get( 'pool_size', default_config.get('pool_size', 1) ) pool = self._pools.get(notebook_name, []) self._pools[notebook_name] = pool if 'path' not in kwargs: kwargs['path'] = ( os.path.dirname(notebook_name) if notebook_name is not None else self.root_dir ) kernel_env = os.environ.copy() kernel_env_arg = kwargs.get('env', {}) kernel_env.update(kernel_env_arg) for key in kernel_env_variables: if key not in kernel_env: kernel_env[key] = kernel_env_variables[key] kernel_env[ENV_VARIABLE.VOILA_BASE_URL] = self.parent.base_url kernel_env[ENV_VARIABLE.VOILA_SERVER_URL] = self.parent.server_url kernel_env[ENV_VARIABLE.VOILA_PREHEAT] = 'True' kwargs['env'] = kernel_env heated = len(pool) def task_counter(tk): nonlocal heated heated += 1 if (heated == kernel_size): self.log.info( 'Kernel pool of %s is filled with %s kernel(s)', notebook_name, kernel_size) for _ in range(kernel_size - len(pool)): # Start the work on the loop immediately, so it is ready when needed: task = loop.create_task( wait_before(delay, self._initialize(notebook_name, None, **kwargs)) ) pool.append(task) task.add_done_callback(task_counter) async def restart_kernel(self, kernel_id: str, **kwargs) -> None: await ensure_async(super().restart_kernel(kernel_id, **kwargs)) notebook_name = self._get_notebook_from_kernel(kernel_id) if notebook_name is not None: await self._initialize(notebook_name, kernel_id, **kwargs) async def shutdown_kernel(self, kernel_id: str, *args, **kwargs): for pool in self._pools.values(): for i, f in enumerate(pool): if f.done() and f.result().get('kernel_id') == kernel_id: pool.pop(i) break else: continue break for value in self.notebook_data.values(): if kernel_id in value['kernel_ids']: value['kernel_ids'].remove(kernel_id) return await ensure_async( super().shutdown_kernel(kernel_id, *args, **kwargs) ) async def shutdown_all(self, *args, **kwargs): await ensure_async(super().shutdown_all(*args, **kwargs)) # Parent doesn't correctly add all created kernels until they have completed startup: pools = self._pools self._pools = {} for value in self.notebook_data.values(): value['kernel_ids'] = set() for pool in pools.values(): # The iteration gets confused if we don't copy pool for task in tuple(pool): try: result = await task except Exception: pass else: kid = result['kernel_id'] if kid in self: try: await ensure_async( self.shutdown_kernel(kid, *args, **kwargs) ) except RuntimeError: pass # Kernel is not running async def _initialize( self, notebook_path: str, kernel_id: str = None, **kwargs) -> str: """Run any configured initialization code in the kernel""" renderer = self._notebook_renderer_factory(notebook_path) await renderer.initialize() kernel_name = renderer.notebook.metadata.kernelspec.name if kernel_id is None: kernel_id = await super().start_kernel(kernel_name=kernel_name, **kwargs) if renderer.notebook_path not in self.notebook_data: self.notebook_data[renderer.notebook_path] = { 'notebook': renderer.notebook, 'template': renderer.template_name, 'theme': renderer.theme, 'kernel_name': kernel_name, 'kernel_ids': {kernel_id} } else: self.notebook_data[renderer.notebook_path]['kernel_ids'].add(kernel_id) kernel_future = self.get_kernel(kernel_id) task = asyncio.get_event_loop().create_task(renderer.generate_content_hybrid(kernel_id, kernel_future)) return {'task': task, 'renderer': renderer, 'kernel_id': kernel_id} async def cull_kernel_if_idle(self, kernel_id: str): """Ensure we don't cull pooled kernels: (this logic assumes the init time is shorter than the cull time) """ for pool in self._pools.values(): for i, f in enumerate(pool): try: if f.done() and f.result().get('kernel_id') == kernel_id: return except Exception: pool.pop(i) return await ensure_async(super().cull_kernel_if_idle(kernel_id)) def _notebook_renderer_factory( self, notebook_path: Union[str, None] = None ) -> NotebookRenderer: """Helper function to create `NotebookRenderer` instance. Args: - notebook_path (Union[str, None], optional): Path to the notebook. Defaults to None. """ return NotebookRenderer( voila_configuration=self.parent.voila_configuration, traitlet_config=self.parent.config, notebook_path=notebook_path, template_paths=self.parent.template_paths, config_manager=self.parent.config_manager, contents_manager=self.parent.contents_manager, base_url=self.parent.base_url, kernel_spec_manager=self.parent.kernel_spec_manager, ) def _notebook_filter(self, nb_path: Path) -> bool: """Helper to filter blacklisted notebooks. Args: nb_path (Path): Path to notebook Returns: bool: return `False` if notebook is in `ipynb_checkpoints` folder or is blacklisted, `True` otherwise. """ nb_name = str(nb_path) if '.ipynb_checkpoints' in nb_name: return False for nb_pattern in self.preheat_blacklist: pattern = re.compile(nb_pattern) if (nb_pattern in nb_name) or bool(pattern.match(nb_name)): return False return True def _get_notebook_from_kernel(self, kernel_id: str) -> Union[None, str]: """Helper to get notebook name from heated kernel id. Args: kernel_id (str): Kernel id Returns: Union[None, str]: return associated notebook with kernel id. """ for nb_name, data in self.notebook_data.items(): if kernel_id in data['kernel_ids']: return nb_name return None
class KBaseWSManager(KBaseWSManagerMixin, ContentsManager): """ A notebook manager that uses the KBase workspace for storage. The Workspace backend simply adds a few metadata fields into the notebook object and pushes it into the workspace as the 'data' part of a workspace object Additional metadata fields { 'id' : User specified title for the narrative alphanumeric + _ 'creator' : {username of the creator of this notebook}, 'description' : 'description of notebook', 'data_dependencies' : { list of kbase id strings } 'format' : self.node_format 'workspace' : the workspace that it was loaded from or saved to } This handler expects that on every request, the session attribute for an instance will be populated by the front end handlers. That's gross, but that's what we're running with for now. Note: you'll probably see "That's gross, but..." a lot in this rev of the code Notebooks are identified with workspace identifiers of the format {workspace_name}.{object_name} Object format: (New) { 'dependencies' : List of workspace refs, 'notebook' : { <mostly, the IPython notebook object>, 'metadata' : } } """ kbasews_uri = Unicode(URLS.workspace, config=True, help='Workspace service endpoint URI') ipynb_type = Unicode('ipynb') allowed_formats = List(['json']) node_format = ipynb_type ws_type = Unicode('KBaseNarrative.Narrative', config=True, help='Type to store narratives within workspace service') # regex for parsing out workspace_id and object_id from # a "ws.{workspace}.{object}" string # should accept any of the following formats (the numbers are just random): # ws.123.obj.456.ver.789 # ws.123.obj.456 # ws.123 # 123 path_regex = re.compile('^(ws\.)?(?P<wsid>\d+)((\.obj\.(?P<objid>\d+))(\.ver\.(?P<ver>\d+))?)?$') # This is a regular expression to make sure that the workspace ID # doesn't contain non-legit characters in the object ID field # We use it like this to to translate names: # wsid_regex.sub('',"Hello! Freaking World! 123".replace(' ','_')) # to get an id of 'Hello_Freaking_World_123' # We will enforce validation on the narrative naming GUI, but this is # a safety net wsid_regex = re.compile('[\W]+', re.UNICODE) def __init__(self, *args, **kwargs): """Verify that we can connect to the configured WS instance""" super(KBaseWSManager, self).__init__(*args, **kwargs) if not self.kbasews_uri: raise HTTPError(412, "Missing KBase workspace service endpoint URI.") # Init the session info we need. self.narrative_logger = get_narrative_logger() self.user_service = UserService() def _checkpoints_class_default(self): return KBaseCheckpoints def get_userid(self): """Return the current user id (if logged in), or None """ return util.kbase_env.user def _clean_id(self, id): """Clean any whitespace out of the given id""" return self.wsid_regex.sub('', id.replace(' ', '_')) ##### # API part 1: methods that must be implemented in subclasses. ##### def dir_exists(self, path): """If it's blank, just return True - we'll be looking up the list of all Narratives from that dir, so it's real.""" if not path: return True else: return False def is_hidden(self, path): """We can only see what gets returned from Workspace lookup, so nothing should be hidden""" return False def file_exists(self, path): """We only support narratives right now, so look up a narrative from that path.""" ref = self._parse_path(path) self.log.warn('looking up whether a narrative exists') try: self.log.warn('trying to get narrative {}'.format(ref)) return self.narrative_exists(ref) except WorkspaceError as err: self.log.warn("Error while testing narrative existence: {}".format(str(err))) if err.http_code == 403: raise HTTPError(403, "You do not have permission to view the narrative with id {}".format(path)) else: raise HTTPError(err.http_code, "An error occurred while trying to find the Narrative with id {}".format(path)) def exists(self, path): """Looks up whether a directory or file path (i.e. narrative) exists""" path = path.strip('/') if not path: # it's a directory, for all narratives return True return self.file_exists(path) def _wsobj_to_model(self, nar, content=True): nar_id = 'ws.{}.obj.{}'.format(nar['wsid'], nar['objid']) model = base_model('{} - {} - {}'.format(nar['saved_by'], nar_id, nar['name']), nar_id) model['format'] = 'json' model['last_modified'] = nar['save_date'] model['type'] = 'notebook' return model def _parse_path(self, path): """ From the URL path for a Narrative, returns a NarrativeRef if the path isn't parseable, this raises a 404 with the invalid path. """ path = path.strip('/') m = self.path_regex.match(path) if m is None: raise HTTPError(404, "Invalid Narrative path {}".format(path)) try: return NarrativeRef(dict( wsid=m.group('wsid'), objid=m.group('objid'), ver=m.group('ver') )) except RuntimeError as e: raise HTTPError(500, str(e)) except WorkspaceError as e: raise HTTPError(e.http_code, e.message) def get(self, path, content=True, type=None, format=None): """Get the model of a file or directory with or without content.""" path = path.strip('/') model = base_model(path, path) try: if self.exists(path) and type != 'directory': #It's a narrative object, so try to fetch it. ref = self._parse_path(path) if not ref: raise HTTPError(404, 'Unknown Narrative "{}"'.format(path)) nar_obj = self.read_narrative(ref, content=content) model['type'] = 'notebook' user = self.get_userid() if content: model['format'] = 'json' nb = nbformat.reads(json.dumps(nar_obj['data']), 4) nb['metadata'].pop('orig_nbformat', None) self.mark_trusted_cells(nb, nar_obj['info'][5], path) model['content'] = nb model['name'] = nar_obj['data']['metadata'].get('name', 'Untitled') util.kbase_env.narrative = 'ws.{}.obj.{}'.format(ref.wsid, ref.objid) util.kbase_env.workspace = model['content'].metadata.ws_name self.narrative_logger.narrative_open('{}/{}'.format(ref.wsid, ref.objid), nar_obj['info'][4]) if user is not None: model['writable'] = self.narrative_writable(ref, user) self.log.info('Got narrative {}'.format(model['name'])) except WorkspaceError as e: raise HTTPError(e.http_code, e.message) if not path or type == 'directory': #if it's the empty string, look up all narratives, treat them as a dir self.log.info('Getting narrative list') model['type'] = type model['format'] = 'json' if content: contents = [] nar_list = self.list_narratives() self.log.info('Found {} narratives'.format(len(nar_list))) for nar in nar_list: contents.append(self._wsobj_to_model(nar, content=False)) model['content'] = contents return model def save(self, model, path): """Save the file or directory and return the model with no content. Save implementations should call self.run_pre_save_hook(model=model, path=path) prior to writing any data. """ path = path.strip('/') if 'type' not in model: raise HTTPError(400, 'No IPython model type provided') if model['type'] != 'notebook': raise HTTPError(400, 'We currently only support saving Narratives!') if 'content' not in model and model['type'] != 'directory': raise HTTPError(400, 'No Narrative content found while trying to save') self.log.debug("writing Narrative %s." % path) nb = nbformat.from_dict(model['content']) self.check_and_sign(nb, path) try: ref = self._parse_path(path) result = self.write_narrative(ref, nb, self.get_userid()) new_id = "ws.%s.obj.%s" % (result[1], result[2]) util.kbase_env.narrative = new_id nb = result[0] self.validate_notebook_model(model) validation_message = model.get('message', None) model = self.get(path, content=False) if validation_message: model['message'] = validation_message self.narrative_logger.narrative_save('{}/{}'.format(result[1], result[2]), result[3]) return model except WorkspaceError as err: raise HTTPError(err.http_code, "While saving your Narrative: {}".format(err.message)) def delete_file(self, path): """Delete file or directory by path.""" raise HTTPError(501, 'Narrative deletion not implemented here. Deletion is handled elsewhere.') def rename_file(self, path, new_name): """Rename a file from old_path to new_path. This gets tricky in KBase since we don't deal with paths, but with actual file names. For now, assume that 'old_path' won't actually change, but the 'new_path' is actually the new Narrative name.""" try: self.rename_narrative(self._parse_path(path), self.get_userid(), new_name) except WorkspaceError as err: raise HTTPError(err.http_code, err.message) except Exception as err: raise HTTPError(500, 'An error occurred while renaming your Narrative: {}'.format(err)) # API part 2: methods that have useable default # implementations, but can be overridden in subclasses. def delete(self, path): """Delete a file/directory and any associated checkpoints.""" path = path.strip('/') if not path: raise HTTPError(400, "Can't delete root") self.delete_file(path) self.checkpoints.delete_all_checkpoints(path) def rename(self, old_path, new_path): """Rename a file and any checkpoints associated with that file.""" self.rename_file(old_path, new_path) self.checkpoints.rename_all_checkpoints(old_path, new_path) def update(self, model, path): """Update the file's path For use in PATCH requests, to enable renaming a file without re-uploading its contents. Only used for renaming at the moment. """ self.log.warn('update') self.log.warn(model) self.log.warn(path) path = path.strip('/') new_path = model.get('path', path).strip('/') if new_path.endswith('.ipynb'): new_path = new_path[:-len('.ipynb')] self.rename(path, new_path) model = self.get(path, content=False) self.log.warn(model) return model def increment_filename(self, filename, path='', insert=''): """Increment a filename until it is unique. Parameters ---------- filename : unicode The name of a file, including extension path : unicode The API path of the target's directory Returns ------- name : unicode A filename that is unique, based on the input filename. """ path = path.strip('/') basename, ext = os.path.splitext(filename) for i in itertools.count(): if i: insert_i = '{}{}'.format(insert, i) else: insert_i = '' name = '{basename}{insert}{ext}'.format(basename=basename, insert=insert_i, ext=ext) if not self.exists('{}/{}'.format(path, name)): break return name def validate_notebook_model(self, model): """Add failed-validation message to model""" try: validate(model['content']) except ValidationError as e: model['message'] = 'Notebook Validation failed: {}:\n{}'.format( e.message, json.dumps(e.instance, indent=1, default=lambda obj: '<UNKNOWN>'), ) return model def new_untitled(self, path='', type='', ext=''): """Create a new untitled file or directory in path path must be a directory File extension can be specified. Use `new` to create files with a fully specified path (including filename). """ path = path.strip('/') if not self.dir_exists(path): raise HTTPError(404, 'No such directory: %s' % path) model = {} if type: model['type'] = type if ext == '.ipynb': model.setdefault('type', 'notebook') else: model.setdefault('type', 'file') insert = '' if model['type'] == 'directory': untitled = self.untitled_directory insert = ' ' elif model['type'] == 'notebook': untitled = self.untitled_notebook ext = '.ipynb' elif model['type'] == 'file': untitled = self.untitled_file else: raise HTTPError(400, "Unexpected model type: %r" % model['type']) name = self.increment_filename(untitled + ext, path, insert=insert) path = '{0}/{1}'.format(path, name) return self.new(model, path) def new(self, model=None, path=''): """Create a new file or directory and return its model with no content. To create a new untitled entity in a directory, use `new_untitled`. """ # TODO path = path.strip('/') if model is None: model = {} if path.endswith('.ipynb'): model.setdefault('type', 'notebook') else: model.setdefault('type', 'file') # no content, not a directory, so fill out new-file model if 'content' not in model and model['type'] != 'directory': if model['type'] == 'notebook': model['content'] = new_notebook() model['format'] = 'json' else: model['content'] = '' model['type'] = 'file' model['format'] = 'text' model = self.save(model, path) return model def copy(self, from_path, to_path=None): """Copy an existing file and return its new model. If to_path not specified, it will be the parent directory of from_path. If to_path is a directory, filename will increment `from_path-Copy#.ext`. from_path must be a full path to a file. """ # TODO path = from_path.strip('/') if to_path is not None: to_path = to_path.strip('/') if '/' in path: from_dir, from_name = path.rsplit('/', 1) else: from_dir = '' from_name = path model = self.get(path) model.pop('path', None) model.pop('name', None) if model['type'] == 'directory': raise HTTPError(400, "Can't copy directories") if to_path is None: to_path = from_dir if self.dir_exists(to_path): name = copy_pat.sub('.', from_name) to_name = self.increment_filename(name, to_path, insert='-Copy') to_path = '{0}/{1}'.format(to_path, to_name) model = self.save(model, to_path) return model def log_info(self): self.log.info(self.info_string()) def trust_notebook(self, path): """Explicitly trust a notebook Parameters ---------- path : string The path of a notebook """ model = self.get(path) nb = model['content'] self.log.warn("Trusting notebook %s", path) self.notary.mark_cells(nb, True) self.save(model, path) def check_and_sign(self, nb, path=''): """Check for trusted cells, and sign the notebook. Called as a part of saving notebooks. Parameters ---------- nb : dict The notebook dict path : string The notebook's path (for logging) """ if self.notary.check_cells(nb): self.notary.sign(nb) else: self.log.warn("Saving untrusted notebook %s", path) def mark_trusted_cells(self, nb, saved_by, path=''): """Mark cells as trusted if the notebook signature matches. Called as a part of loading notebooks. Parameters ---------- nb : dict The notebook object (in current nbformat) path : string The notebook's path (for logging) """ if self.user_service.is_trusted_user(saved_by): self.notary.mark_cells(nb, True) else: # commenting out, but leaving behind for a while. trusted = self.notary.check_signature(nb) if not trusted: self.log.warn("Notebook %s is not trusted", path) self.notary.mark_cells(nb, trusted) # self.log.warn("Notebook %s is totally trusted", path) # # all notebooks are trustworthy, because KBase is Pollyanna. def should_list(self, name): """Should this file/directory name be displayed in a listing?""" return not any(fnmatch(name, glob) for glob in self.hide_globs) def info_string(self): return "Workspace Narrative Service with workspace endpoint at %s" % self.kbasews_uri
class LazyConfigValue(HasTraits): """Proxy object for exposing methods on configurable containers These methods allow appending/extending/updating to add to non-empty defaults instead of clobbering them. Exposes: - append, extend, insert on lists - update on dicts - update, add on sets """ _value = None # list methods _extend = List() _prepend = List() _inserts = List() def append(self, obj): """Append an item to a List""" self._extend.append(obj) def extend(self, other): """Extend a list""" self._extend.extend(other) def prepend(self, other): """like list.extend, but for the front""" self._prepend[:0] = other def merge_into(self, other): """ Merge with another earlier LazyConfigValue or an earlier container. This is useful when having global system-wide configuration files. Self is expected to have higher precedence. Parameters ---------- other : LazyConfigValue or container Returns ------- LazyConfigValue if ``other`` is also lazy, a reified container otherwise. """ if isinstance(other, LazyConfigValue): other._extend.extend(self._extend) self._extend = other._extend self._prepend.extend(other._prepend) other._inserts.extend(self._inserts) self._inserts = other._inserts if self._update: other.update(self._update) self._update = other._update return self else: # other is a container, reify now. return self.get_value(other) def insert(self, index, other): if not isinstance(index, int): raise TypeError("An integer is required") self._inserts.append((index, other)) # dict methods # update is used for both dict and set _update = Any() def update(self, other): """Update either a set or dict""" if self._update is None: if isinstance(other, dict): self._update = {} else: self._update = set() self._update.update(other) # set methods def add(self, obj): """Add an item to a set""" self.update({obj}) def get_value(self, initial): """construct the value from the initial one after applying any insert / extend / update changes """ if self._value is not None: return self._value value = copy.deepcopy(initial) if isinstance(value, list): for idx, obj in self._inserts: value.insert(idx, obj) value[:0] = self._prepend value.extend(self._extend) elif isinstance(value, dict): if self._update: value.update(self._update) elif isinstance(value, set): if self._update: value.update(self._update) self._value = value return value def to_dict(self): """return JSONable dict form of my data Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples. """ d = {} if self._update: d["update"] = self._update if self._extend: d["extend"] = self._extend if self._prepend: d["prepend"] = self._prepend elif self._inserts: d["inserts"] = self._inserts return d def __repr__(self): if self._value is not None: return f"<{self.__class__.__name__} value={self._value!r}>" else: return f"<{self.__class__.__name__} {self.to_dict()!r}>"