id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,600
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
Deduplicate.canonical_path
def canonical_path(path): """ Return a normalized, canonical path to a file or folder. Removes all symbolic links encountered in the path to detect natural mail and maildir duplicates on the fly. """ return os.path.normcase(os.path.realpath(os.path.abspath( os.path.expanduser(path))))
python
def canonical_path(path): return os.path.normcase(os.path.realpath(os.path.abspath( os.path.expanduser(path))))
[ "def", "canonical_path", "(", "path", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", ")", ...
Return a normalized, canonical path to a file or folder. Removes all symbolic links encountered in the path to detect natural mail and maildir duplicates on the fly.
[ "Return", "a", "normalized", "canonical", "path", "to", "a", "file", "or", "folder", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L489-L496
26,601
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
Deduplicate.add_maildir
def add_maildir(self, maildir_path): """ Load up a maildir and compute hash for each mail found. """ maildir_path = self.canonical_path(maildir_path) logger.info("Opening maildir at {} ...".format(maildir_path)) # Maildir parser requires a string, not a unicode, as path. maildir = Maildir(str(maildir_path), factory=None, create=False) # Group folders by hash. logger.info("{} mails found.".format(len(maildir))) if self.conf.progress: bar = ProgressBar(widgets=[Percentage(), Bar()], max_value=len(maildir), redirect_stderr=True, redirect_stdout=True) else: def bar(x): return x for mail_id in bar(maildir.iterkeys()): self.stats['mail_found'] += 1 mail_path = self.canonical_path(os.path.join( maildir._path, maildir._lookup(mail_id))) mail = Mail(mail_path, self.conf) try: mail_hash = mail.hash_key except (InsufficientHeadersError, MissingMessageID) as expt: logger.warning( "Rejecting {}: {}".format(mail_path, expt.args[0])) self.stats['mail_rejected'] += 1 else: logger.debug( "Hash is {} for mail {!r}.".format(mail_hash, mail_id)) # Use a set to deduplicate entries pointing to the same file. self.mails.setdefault(mail_hash, set()).add(mail_path) self.stats['mail_kept'] += 1
python
def add_maildir(self, maildir_path): maildir_path = self.canonical_path(maildir_path) logger.info("Opening maildir at {} ...".format(maildir_path)) # Maildir parser requires a string, not a unicode, as path. maildir = Maildir(str(maildir_path), factory=None, create=False) # Group folders by hash. logger.info("{} mails found.".format(len(maildir))) if self.conf.progress: bar = ProgressBar(widgets=[Percentage(), Bar()], max_value=len(maildir), redirect_stderr=True, redirect_stdout=True) else: def bar(x): return x for mail_id in bar(maildir.iterkeys()): self.stats['mail_found'] += 1 mail_path = self.canonical_path(os.path.join( maildir._path, maildir._lookup(mail_id))) mail = Mail(mail_path, self.conf) try: mail_hash = mail.hash_key except (InsufficientHeadersError, MissingMessageID) as expt: logger.warning( "Rejecting {}: {}".format(mail_path, expt.args[0])) self.stats['mail_rejected'] += 1 else: logger.debug( "Hash is {} for mail {!r}.".format(mail_hash, mail_id)) # Use a set to deduplicate entries pointing to the same file. self.mails.setdefault(mail_hash, set()).add(mail_path) self.stats['mail_kept'] += 1
[ "def", "add_maildir", "(", "self", ",", "maildir_path", ")", ":", "maildir_path", "=", "self", ".", "canonical_path", "(", "maildir_path", ")", "logger", ".", "info", "(", "\"Opening maildir at {} ...\"", ".", "format", "(", "maildir_path", ")", ")", "# Maildir ...
Load up a maildir and compute hash for each mail found.
[ "Load", "up", "a", "maildir", "and", "compute", "hash", "for", "each", "mail", "found", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L498-L533
26,602
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
Deduplicate.run
def run(self): """ Run the deduplication process. We apply the removal strategy one duplicate set at a time to keep memory footprint low and make the log of actions easier to read. """ logger.info( "The {} strategy will be applied on each duplicate set.".format( self.conf.strategy)) self.stats['set_total'] = len(self.mails) for hash_key, mail_path_set in self.mails.items(): # Print visual clue to separate duplicate sets. logger.info('---') duplicates = DuplicateSet(hash_key, mail_path_set, self.conf) # Perfom the deduplication. duplicates.dedupe() # Merge stats resulting of actions on duplicate sets. self.stats += duplicates.stats
python
def run(self): logger.info( "The {} strategy will be applied on each duplicate set.".format( self.conf.strategy)) self.stats['set_total'] = len(self.mails) for hash_key, mail_path_set in self.mails.items(): # Print visual clue to separate duplicate sets. logger.info('---') duplicates = DuplicateSet(hash_key, mail_path_set, self.conf) # Perfom the deduplication. duplicates.dedupe() # Merge stats resulting of actions on duplicate sets. self.stats += duplicates.stats
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"The {} strategy will be applied on each duplicate set.\"", ".", "format", "(", "self", ".", "conf", ".", "strategy", ")", ")", "self", ".", "stats", "[", "'set_total'", "]", "=", "len", "(",...
Run the deduplication process. We apply the removal strategy one duplicate set at a time to keep memory footprint low and make the log of actions easier to read.
[ "Run", "the", "deduplication", "process", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L535-L557
26,603
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
Deduplicate.report
def report(self): """ Print user-friendly statistics and metrics. """ table = [["Mails", "Metric"]] table.append(["Found", self.stats['mail_found']]) table.append(["Skipped", self.stats['mail_skipped']]) table.append(["Rejected", self.stats['mail_rejected']]) table.append(["Kept", self.stats['mail_kept']]) table.append(["Unique", self.stats['mail_unique']]) table.append(["Duplicates", self.stats['mail_duplicates']]) table.append(["Deleted", self.stats['mail_deleted']]) logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow')) table = [["Duplicate sets", "Metric"]] table.append(["Total", self.stats['set_total']]) table.append(["Ignored", self.stats['set_ignored']]) table.append(["Skipped", self.stats['set_skipped']]) table.append([ "Rejected (bad encoding)", self.stats['set_rejected_encoding']]) table.append([ "Rejected (too dissimilar in size)", self.stats['set_rejected_size']]) table.append([ "Rejected (too dissimilar in content)", self.stats['set_rejected_content']]) table.append(["Deduplicated", self.stats['set_deduplicated']]) logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow')) # Perform some high-level consistency checks on metrics. assert self.stats['mail_found'] == ( self.stats['mail_skipped'] + self.stats['mail_rejected'] + self.stats['mail_kept']) assert self.stats['mail_kept'] >= self.stats['mail_unique'] assert self.stats['mail_kept'] >= self.stats['mail_duplicates'] assert self.stats['mail_kept'] >= self.stats['mail_deleted'] assert self.stats['mail_kept'] == ( self.stats['mail_unique'] + self.stats['mail_duplicates']) assert self.stats['mail_duplicates'] > self.stats['mail_deleted'] assert self.stats['set_ignored'] == self.stats['mail_unique'] assert self.stats['set_total'] == ( self.stats['set_ignored'] + self.stats['set_skipped'] + self.stats['set_rejected_encoding'] + self.stats['set_rejected_size'] + self.stats['set_rejected_content'] + self.stats['set_deduplicated'])
python
def report(self): table = [["Mails", "Metric"]] table.append(["Found", self.stats['mail_found']]) table.append(["Skipped", self.stats['mail_skipped']]) table.append(["Rejected", self.stats['mail_rejected']]) table.append(["Kept", self.stats['mail_kept']]) table.append(["Unique", self.stats['mail_unique']]) table.append(["Duplicates", self.stats['mail_duplicates']]) table.append(["Deleted", self.stats['mail_deleted']]) logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow')) table = [["Duplicate sets", "Metric"]] table.append(["Total", self.stats['set_total']]) table.append(["Ignored", self.stats['set_ignored']]) table.append(["Skipped", self.stats['set_skipped']]) table.append([ "Rejected (bad encoding)", self.stats['set_rejected_encoding']]) table.append([ "Rejected (too dissimilar in size)", self.stats['set_rejected_size']]) table.append([ "Rejected (too dissimilar in content)", self.stats['set_rejected_content']]) table.append(["Deduplicated", self.stats['set_deduplicated']]) logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow')) # Perform some high-level consistency checks on metrics. assert self.stats['mail_found'] == ( self.stats['mail_skipped'] + self.stats['mail_rejected'] + self.stats['mail_kept']) assert self.stats['mail_kept'] >= self.stats['mail_unique'] assert self.stats['mail_kept'] >= self.stats['mail_duplicates'] assert self.stats['mail_kept'] >= self.stats['mail_deleted'] assert self.stats['mail_kept'] == ( self.stats['mail_unique'] + self.stats['mail_duplicates']) assert self.stats['mail_duplicates'] > self.stats['mail_deleted'] assert self.stats['set_ignored'] == self.stats['mail_unique'] assert self.stats['set_total'] == ( self.stats['set_ignored'] + self.stats['set_skipped'] + self.stats['set_rejected_encoding'] + self.stats['set_rejected_size'] + self.stats['set_rejected_content'] + self.stats['set_deduplicated'])
[ "def", "report", "(", "self", ")", ":", "table", "=", "[", "[", "\"Mails\"", ",", "\"Metric\"", "]", "]", "table", ".", "append", "(", "[", "\"Found\"", ",", "self", ".", "stats", "[", "'mail_found'", "]", "]", ")", "table", ".", "append", "(", "["...
Print user-friendly statistics and metrics.
[ "Print", "user", "-", "friendly", "statistics", "and", "metrics", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L559-L608
26,604
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
cli
def cli(ctx): """ CLI for maildirs content analysis and deletion. """ level = logger.level try: level_to_name = logging._levelToName # Fallback to pre-Python 3.4 internals. except AttributeError: level_to_name = logging._levelNames level_name = level_to_name.get(level, level) logger.debug('Verbosity set to {}.'.format(level_name)) # Print help screen and exit if no sub-commands provided. if ctx.invoked_subcommand is None: click.echo(ctx.get_help()) ctx.exit() # Load up global options to the context. ctx.obj = {}
python
def cli(ctx): level = logger.level try: level_to_name = logging._levelToName # Fallback to pre-Python 3.4 internals. except AttributeError: level_to_name = logging._levelNames level_name = level_to_name.get(level, level) logger.debug('Verbosity set to {}.'.format(level_name)) # Print help screen and exit if no sub-commands provided. if ctx.invoked_subcommand is None: click.echo(ctx.get_help()) ctx.exit() # Load up global options to the context. ctx.obj = {}
[ "def", "cli", "(", "ctx", ")", ":", "level", "=", "logger", ".", "level", "try", ":", "level_to_name", "=", "logging", ".", "_levelToName", "# Fallback to pre-Python 3.4 internals.", "except", "AttributeError", ":", "level_to_name", "=", "logging", ".", "_levelNam...
CLI for maildirs content analysis and deletion.
[ "CLI", "for", "maildirs", "content", "analysis", "and", "deletion", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L59-L76
26,605
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
validate_regexp
def validate_regexp(ctx, param, value): """ Validate and compile regular expression. """ if value: try: value = re.compile(value) except ValueError: raise click.BadParameter('invalid regular expression.') return value
python
def validate_regexp(ctx, param, value): if value: try: value = re.compile(value) except ValueError: raise click.BadParameter('invalid regular expression.') return value
[ "def", "validate_regexp", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "value", ":", "try", ":", "value", "=", "re", ".", "compile", "(", "value", ")", "except", "ValueError", ":", "raise", "click", ".", "BadParameter", "(", "'invalid regular ...
Validate and compile regular expression.
[ "Validate", "and", "compile", "regular", "expression", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L79-L86
26,606
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
validate_maildirs
def validate_maildirs(ctx, param, value): """ Check that folders are maildirs. """ for path in value: for subdir in MD_SUBDIRS: if not os.path.isdir(os.path.join(path, subdir)): raise click.BadParameter( '{} is not a maildir (missing {!r} sub-directory).'.format( path, subdir)) return value
python
def validate_maildirs(ctx, param, value): for path in value: for subdir in MD_SUBDIRS: if not os.path.isdir(os.path.join(path, subdir)): raise click.BadParameter( '{} is not a maildir (missing {!r} sub-directory).'.format( path, subdir)) return value
[ "def", "validate_maildirs", "(", "ctx", ",", "param", ",", "value", ")", ":", "for", "path", "in", "value", ":", "for", "subdir", "in", "MD_SUBDIRS", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "path...
Check that folders are maildirs.
[ "Check", "that", "folders", "are", "maildirs", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L89-L97
26,607
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
deduplicate
def deduplicate( ctx, strategy, time_source, regexp, dry_run, message_id, size_threshold, content_threshold, show_diff, maildirs): """ Deduplicate mails from a set of maildir folders. Run a first pass computing the canonical hash of each encountered mail from their headers, then a second pass to apply the deletion strategy on each subset of duplicate mails. \b Removal strategies for each subsets of duplicate mails: - delete-older: Deletes the olders, keeps the newests. - delete-oldest: Deletes the oldests, keeps the newers. - delete-newer: Deletes the newers, keeps the oldests. - delete-newest: Deletes the newests, keeps the olders. - delete-smaller: Deletes the smallers, keeps the biggests. - delete-smallest: Deletes the smallests, keeps the biggers. - delete-bigger: Deletes the biggers, keeps the smallests. - delete-biggest: Deletes the biggests, keeps the smallers. - delete-matching-path: Deletes all duplicates whose file path match the regular expression provided via the --regexp parameter. - delete-non-matching-path: Deletes all duplicates whose file path doesn't match the regular expression provided via the --regexp parameter. Deletion strategy on a duplicate set only applies if no major differences between mails are uncovered during a fine-grained check differences during the second pass. Limits can be set via the threshold options. """ # Print help screen and exit if no maildir folder provided. if not maildirs: click.echo(ctx.get_help()) ctx.exit() # Validate exclusive options requirement depending on strategy. requirements = [ (time_source, '-t/--time-source', [ DELETE_OLDER, DELETE_OLDEST, DELETE_NEWER, DELETE_NEWEST]), (regexp, '-r/--regexp', [ DELETE_MATCHING_PATH, DELETE_NON_MATCHING_PATH])] for param_value, param_name, required_strategies in requirements: if strategy in required_strategies: if not param_value: raise click.BadParameter( '{} strategy requires the {} parameter.'.format( strategy, param_name)) elif param_value: raise click.BadParameter( '{} parameter not allowed in {} strategy.'.format( param_name, strategy)) conf = Config( strategy=strategy, time_source=time_source, regexp=regexp, dry_run=dry_run, show_diff=show_diff, message_id=message_id, size_threshold=size_threshold, content_threshold=content_threshold, # progress=progress, ) dedup = Deduplicate(conf) logger.info('=== Start phase #1: load mails and compute hashes.') for maildir in maildirs: dedup.add_maildir(maildir) logger.info('=== Start phase #2: deduplicate mails.') dedup.run() dedup.report()
python
def deduplicate( ctx, strategy, time_source, regexp, dry_run, message_id, size_threshold, content_threshold, show_diff, maildirs): # Print help screen and exit if no maildir folder provided. if not maildirs: click.echo(ctx.get_help()) ctx.exit() # Validate exclusive options requirement depending on strategy. requirements = [ (time_source, '-t/--time-source', [ DELETE_OLDER, DELETE_OLDEST, DELETE_NEWER, DELETE_NEWEST]), (regexp, '-r/--regexp', [ DELETE_MATCHING_PATH, DELETE_NON_MATCHING_PATH])] for param_value, param_name, required_strategies in requirements: if strategy in required_strategies: if not param_value: raise click.BadParameter( '{} strategy requires the {} parameter.'.format( strategy, param_name)) elif param_value: raise click.BadParameter( '{} parameter not allowed in {} strategy.'.format( param_name, strategy)) conf = Config( strategy=strategy, time_source=time_source, regexp=regexp, dry_run=dry_run, show_diff=show_diff, message_id=message_id, size_threshold=size_threshold, content_threshold=content_threshold, # progress=progress, ) dedup = Deduplicate(conf) logger.info('=== Start phase #1: load mails and compute hashes.') for maildir in maildirs: dedup.add_maildir(maildir) logger.info('=== Start phase #2: deduplicate mails.') dedup.run() dedup.report()
[ "def", "deduplicate", "(", "ctx", ",", "strategy", ",", "time_source", ",", "regexp", ",", "dry_run", ",", "message_id", ",", "size_threshold", ",", "content_threshold", ",", "show_diff", ",", "maildirs", ")", ":", "# Print help screen and exit if no maildir folder pr...
Deduplicate mails from a set of maildir folders. Run a first pass computing the canonical hash of each encountered mail from their headers, then a second pass to apply the deletion strategy on each subset of duplicate mails. \b Removal strategies for each subsets of duplicate mails: - delete-older: Deletes the olders, keeps the newests. - delete-oldest: Deletes the oldests, keeps the newers. - delete-newer: Deletes the newers, keeps the oldests. - delete-newest: Deletes the newests, keeps the olders. - delete-smaller: Deletes the smallers, keeps the biggests. - delete-smallest: Deletes the smallests, keeps the biggers. - delete-bigger: Deletes the biggers, keeps the smallests. - delete-biggest: Deletes the biggests, keeps the smallers. - delete-matching-path: Deletes all duplicates whose file path match the regular expression provided via the --regexp parameter. - delete-non-matching-path: Deletes all duplicates whose file path doesn't match the regular expression provided via the --regexp parameter. Deletion strategy on a duplicate set only applies if no major differences between mails are uncovered during a fine-grained check differences during the second pass. Limits can be set via the threshold options.
[ "Deduplicate", "mails", "from", "a", "set", "of", "maildir", "folders", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L140-L211
26,608
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
hash
def hash(ctx, message_id, message): """ Take a single mail message and show its canonicalised form and hash. Mainly used to debug message hashing. """ conf = Config(message_id=message_id) mail = Mail(message, conf) logger.info(mail.header_text) logger.info('-' * 70) logger.info('Hash: {}'.format(mail.hash_key))
python
def hash(ctx, message_id, message): conf = Config(message_id=message_id) mail = Mail(message, conf) logger.info(mail.header_text) logger.info('-' * 70) logger.info('Hash: {}'.format(mail.hash_key))
[ "def", "hash", "(", "ctx", ",", "message_id", ",", "message", ")", ":", "conf", "=", "Config", "(", "message_id", "=", "message_id", ")", "mail", "=", "Mail", "(", "message", ",", "conf", ")", "logger", ".", "info", "(", "mail", ".", "header_text", "...
Take a single mail message and show its canonicalised form and hash. Mainly used to debug message hashing.
[ "Take", "a", "single", "mail", "message", "and", "show", "its", "canonicalised", "form", "and", "hash", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L224-L235
26,609
kdeldycke/maildir-deduplicate
setup.py
read_file
def read_file(*relative_path_elements): """ Return content of a file relative to this ``setup.py``. """ file_path = path.join(path.dirname(__file__), *relative_path_elements) return io.open(file_path, encoding='utf8').read().strip()
python
def read_file(*relative_path_elements): file_path = path.join(path.dirname(__file__), *relative_path_elements) return io.open(file_path, encoding='utf8').read().strip()
[ "def", "read_file", "(", "*", "relative_path_elements", ")", ":", "file_path", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "*", "relative_path_elements", ")", "return", "io", ".", "open", "(", "file_path", ",", "encodi...
Return content of a file relative to this ``setup.py``.
[ "Return", "content", "of", "a", "file", "relative", "to", "this", "setup", ".", "py", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/setup.py#L68-L71
26,610
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.message
def message(self): """ Read mail, parse it and return a Message instance. """ logger.debug("Parsing mail at {} ...".format(self.path)) with open(self.path, 'rb') as mail_file: if PY2: message = email.message_from_file(mail_file) else: message = email.message_from_binary_file(mail_file) return message
python
def message(self): logger.debug("Parsing mail at {} ...".format(self.path)) with open(self.path, 'rb') as mail_file: if PY2: message = email.message_from_file(mail_file) else: message = email.message_from_binary_file(mail_file) return message
[ "def", "message", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Parsing mail at {} ...\"", ".", "format", "(", "self", ".", "path", ")", ")", "with", "open", "(", "self", ".", "path", ",", "'rb'", ")", "as", "mail_file", ":", "if", "PY2", ":...
Read mail, parse it and return a Message instance.
[ "Read", "mail", "parse", "it", "and", "return", "a", "Message", "instance", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L60-L68
26,611
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.timestamp
def timestamp(self): """ Compute the normalized canonical timestamp of the mail. """ # XXX ctime does not refer to creation time on POSIX systems, but # rather the last time the inode data changed. Source: # https://userprimary.net/posts/2007/11/18 # /ctime-in-unix-means-last-change-time-not-create-time/ if self.conf.time_source == CTIME: return os.path.getctime(self.path) # Fetch from the date header. return email.utils.mktime_tz(email.utils.parsedate_tz( self.message.get('Date')))
python
def timestamp(self): # XXX ctime does not refer to creation time on POSIX systems, but # rather the last time the inode data changed. Source: # https://userprimary.net/posts/2007/11/18 # /ctime-in-unix-means-last-change-time-not-create-time/ if self.conf.time_source == CTIME: return os.path.getctime(self.path) # Fetch from the date header. return email.utils.mktime_tz(email.utils.parsedate_tz( self.message.get('Date')))
[ "def", "timestamp", "(", "self", ")", ":", "# XXX ctime does not refer to creation time on POSIX systems, but", "# rather the last time the inode data changed. Source:", "# https://userprimary.net/posts/2007/11/18", "# /ctime-in-unix-means-last-change-time-not-create-time/", "if", "self", "....
Compute the normalized canonical timestamp of the mail.
[ "Compute", "the", "normalized", "canonical", "timestamp", "of", "the", "mail", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L71-L82
26,612
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.body_lines
def body_lines(self): """ Return a normalized list of lines from message's body. """ if not self.message.is_multipart(): body = self.message.get_payload(None, decode=True) else: _, _, body = self.message.as_string().partition("\n\n") if isinstance(body, bytes): for enc in ['ascii', 'utf-8']: try: body = body.decode(enc) break except UnicodeDecodeError: continue else: body = self.message.get_payload(None, decode=False) return body.splitlines(True)
python
def body_lines(self): if not self.message.is_multipart(): body = self.message.get_payload(None, decode=True) else: _, _, body = self.message.as_string().partition("\n\n") if isinstance(body, bytes): for enc in ['ascii', 'utf-8']: try: body = body.decode(enc) break except UnicodeDecodeError: continue else: body = self.message.get_payload(None, decode=False) return body.splitlines(True)
[ "def", "body_lines", "(", "self", ")", ":", "if", "not", "self", ".", "message", ".", "is_multipart", "(", ")", ":", "body", "=", "self", ".", "message", ".", "get_payload", "(", "None", ",", "decode", "=", "True", ")", "else", ":", "_", ",", "_", ...
Return a normalized list of lines from message's body.
[ "Return", "a", "normalized", "list", "of", "lines", "from", "message", "s", "body", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L99-L114
26,613
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.subject
def subject(self): """ Normalized subject. Only used for debugging and human-friendly logging. """ # Fetch subject from first message. subject = self.message.get('Subject', '') subject, _ = re.subn(r'\s+', ' ', subject) return subject
python
def subject(self): # Fetch subject from first message. subject = self.message.get('Subject', '') subject, _ = re.subn(r'\s+', ' ', subject) return subject
[ "def", "subject", "(", "self", ")", ":", "# Fetch subject from first message.", "subject", "=", "self", ".", "message", ".", "get", "(", "'Subject'", ",", "''", ")", "subject", ",", "_", "=", "re", ".", "subn", "(", "r'\\s+'", ",", "' '", ",", "subject",...
Normalized subject. Only used for debugging and human-friendly logging.
[ "Normalized", "subject", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L117-L125
26,614
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.hash_key
def hash_key(self): """ Returns the canonical hash of a mail. """ if self.conf.message_id: message_id = self.message.get('Message-Id') if message_id: return message_id.strip() logger.error( "No Message-ID in {}: {}".format(self.path, self.header_text)) raise MissingMessageID return hashlib.sha224(self.canonical_headers).hexdigest()
python
def hash_key(self): if self.conf.message_id: message_id = self.message.get('Message-Id') if message_id: return message_id.strip() logger.error( "No Message-ID in {}: {}".format(self.path, self.header_text)) raise MissingMessageID return hashlib.sha224(self.canonical_headers).hexdigest()
[ "def", "hash_key", "(", "self", ")", ":", "if", "self", ".", "conf", ".", "message_id", ":", "message_id", "=", "self", ".", "message", ".", "get", "(", "'Message-Id'", ")", "if", "message_id", ":", "return", "message_id", ".", "strip", "(", ")", "logg...
Returns the canonical hash of a mail.
[ "Returns", "the", "canonical", "hash", "of", "a", "mail", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L128-L138
26,615
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.canonical_headers
def canonical_headers(self): """ Copy selected headers into a new string. """ canonical_headers = '' for header in HEADERS: if header not in self.message: continue for value in self.message.get_all(header): canonical_value = self.canonical_header_value(header, value) if re.search(r'\S', canonical_value): canonical_headers += '{}: {}\n'.format( header, canonical_value) canonical_headers = canonical_headers.encode('utf-8') if len(canonical_headers) > 50: return canonical_headers # At this point we should have at absolute minimum 3 or 4 headers, e.g. # From/To/Date/Subject; if not, something went badly wrong. if len(canonical_headers) == 0: raise InsufficientHeadersError("No canonical headers found") err = textwrap.dedent("""\ Not enough data from canonical headers to compute reliable hash! Headers: --------- 8< --------- 8< --------- 8< --------- 8< --------- {} --------- 8< --------- 8< --------- 8< --------- 8< ---------""") raise InsufficientHeadersError(err.format(canonical_headers))
python
def canonical_headers(self): canonical_headers = '' for header in HEADERS: if header not in self.message: continue for value in self.message.get_all(header): canonical_value = self.canonical_header_value(header, value) if re.search(r'\S', canonical_value): canonical_headers += '{}: {}\n'.format( header, canonical_value) canonical_headers = canonical_headers.encode('utf-8') if len(canonical_headers) > 50: return canonical_headers # At this point we should have at absolute minimum 3 or 4 headers, e.g. # From/To/Date/Subject; if not, something went badly wrong. if len(canonical_headers) == 0: raise InsufficientHeadersError("No canonical headers found") err = textwrap.dedent("""\ Not enough data from canonical headers to compute reliable hash! Headers: --------- 8< --------- 8< --------- 8< --------- 8< --------- {} --------- 8< --------- 8< --------- 8< --------- 8< ---------""") raise InsufficientHeadersError(err.format(canonical_headers))
[ "def", "canonical_headers", "(", "self", ")", ":", "canonical_headers", "=", "''", "for", "header", "in", "HEADERS", ":", "if", "header", "not", "in", "self", ".", "message", ":", "continue", "for", "value", "in", "self", ".", "message", ".", "get_all", ...
Copy selected headers into a new string.
[ "Copy", "selected", "headers", "into", "a", "new", "string", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L148-L178
26,616
keepkey/python-keepkey
keepkeylib/transport_hid.py
HidTransport.enumerate
def enumerate(cls): """ Return a list of available KeepKey devices. """ devices = {} for d in hid.enumerate(0, 0): vendor_id = d['vendor_id'] product_id = d['product_id'] serial_number = d['serial_number'] interface_number = d['interface_number'] path = d['path'] # HIDAPI on Mac cannot detect correct HID interfaces, so device with # DebugLink doesn't work on Mac... if devices.get(serial_number) != None and devices[serial_number][0] == path: raise Exception("Two devices with the same path and S/N found. This is Mac, right? :-/") if (vendor_id, product_id) in DEVICE_IDS: devices.setdefault(serial_number, [None, None, None]) if is_normal_link(d): devices[serial_number][0] = path elif is_debug_link(d): devices[serial_number][1] = path else: raise Exception("Unknown USB interface number: %d" % interface_number) # List of two-tuples (path_normal, path_debuglink) return list(devices.values())
python
def enumerate(cls): devices = {} for d in hid.enumerate(0, 0): vendor_id = d['vendor_id'] product_id = d['product_id'] serial_number = d['serial_number'] interface_number = d['interface_number'] path = d['path'] # HIDAPI on Mac cannot detect correct HID interfaces, so device with # DebugLink doesn't work on Mac... if devices.get(serial_number) != None and devices[serial_number][0] == path: raise Exception("Two devices with the same path and S/N found. This is Mac, right? :-/") if (vendor_id, product_id) in DEVICE_IDS: devices.setdefault(serial_number, [None, None, None]) if is_normal_link(d): devices[serial_number][0] = path elif is_debug_link(d): devices[serial_number][1] = path else: raise Exception("Unknown USB interface number: %d" % interface_number) # List of two-tuples (path_normal, path_debuglink) return list(devices.values())
[ "def", "enumerate", "(", "cls", ")", ":", "devices", "=", "{", "}", "for", "d", "in", "hid", ".", "enumerate", "(", "0", ",", "0", ")", ":", "vendor_id", "=", "d", "[", "'vendor_id'", "]", "product_id", "=", "d", "[", "'product_id'", "]", "serial_n...
Return a list of available KeepKey devices.
[ "Return", "a", "list", "of", "available", "KeepKey", "devices", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport_hid.py#L75-L102
26,617
keepkey/python-keepkey
keepkeylib/transport_hid.py
HidTransport.is_connected
def is_connected(self): """ Check if the device is still connected. """ for d in hid.enumerate(0, 0): if d['path'] == self.device: return True return False
python
def is_connected(self): for d in hid.enumerate(0, 0): if d['path'] == self.device: return True return False
[ "def", "is_connected", "(", "self", ")", ":", "for", "d", "in", "hid", ".", "enumerate", "(", "0", ",", "0", ")", ":", "if", "d", "[", "'path'", "]", "==", "self", ".", "device", ":", "return", "True", "return", "False" ]
Check if the device is still connected.
[ "Check", "if", "the", "device", "is", "still", "connected", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport_hid.py#L104-L111
26,618
keepkey/python-keepkey
keepkeylib/transport.py
Transport.session_end
def session_end(self): """ End a session. Se session_begin for an in depth description of TREZOR sessions. """ self.session_depth -= 1 self.session_depth = max(0, self.session_depth) if self.session_depth == 0: self._session_end()
python
def session_end(self): self.session_depth -= 1 self.session_depth = max(0, self.session_depth) if self.session_depth == 0: self._session_end()
[ "def", "session_end", "(", "self", ")", ":", "self", ".", "session_depth", "-=", "1", "self", ".", "session_depth", "=", "max", "(", "0", ",", "self", ".", "session_depth", ")", "if", "self", ".", "session_depth", "==", "0", ":", "self", ".", "_session...
End a session. Se session_begin for an in depth description of TREZOR sessions.
[ "End", "a", "session", ".", "Se", "session_begin", "for", "an", "in", "depth", "description", "of", "TREZOR", "sessions", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport.py#L48-L55
26,619
keepkey/python-keepkey
keepkeylib/transport.py
Transport.read
def read(self): """ If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. Otherwise, returns None. """ if not self.ready_to_read(): return None data = self._read() if data is None: return None return self._parse_message(data)
python
def read(self): if not self.ready_to_read(): return None data = self._read() if data is None: return None return self._parse_message(data)
[ "def", "read", "(", "self", ")", ":", "if", "not", "self", ".", "ready_to_read", "(", ")", ":", "return", "None", "data", "=", "self", ".", "_read", "(", ")", "if", "data", "is", "None", ":", "return", "None", "return", "self", ".", "_parse_message",...
If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. Otherwise, returns None.
[ "If", "there", "is", "data", "available", "to", "be", "read", "from", "the", "transport", "reads", "the", "data", "and", "tries", "to", "parse", "it", "as", "a", "protobuf", "message", ".", "If", "the", "parsing", "succeeds", "return", "a", "protobuf", "...
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport.py#L71-L83
26,620
keepkey/python-keepkey
keepkeylib/transport.py
Transport.read_blocking
def read_blocking(self): """ Same as read, except blocks untill data is available to be read. """ while True: data = self._read() if data != None: break return self._parse_message(data)
python
def read_blocking(self): while True: data = self._read() if data != None: break return self._parse_message(data)
[ "def", "read_blocking", "(", "self", ")", ":", "while", "True", ":", "data", "=", "self", ".", "_read", "(", ")", "if", "data", "!=", "None", ":", "break", "return", "self", ".", "_parse_message", "(", "data", ")" ]
Same as read, except blocks untill data is available to be read.
[ "Same", "as", "read", "except", "blocks", "untill", "data", "is", "available", "to", "be", "read", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport.py#L85-L94
26,621
keepkey/python-keepkey
keepkeylib/filecache.py
_get_cache_name
def _get_cache_name(function): """ returns a name for the module's cache db. """ module_name = _inspect.getfile(function) module_name = _os.path.abspath(module_name) cache_name = module_name # fix for '<string>' or '<stdin>' in exec or interpreter usage. cache_name = cache_name.replace('<', '_lt_') cache_name = cache_name.replace('>', '_gt_') tmpdir = _os.getenv('TMPDIR') or _os.getenv('TEMP') or _os.getenv('TMP') if tmpdir: cache_name = tmpdir + '/filecache_' + cache_name.replace(_os.sep, '@') cache_name += '.cache' return cache_name
python
def _get_cache_name(function): module_name = _inspect.getfile(function) module_name = _os.path.abspath(module_name) cache_name = module_name # fix for '<string>' or '<stdin>' in exec or interpreter usage. cache_name = cache_name.replace('<', '_lt_') cache_name = cache_name.replace('>', '_gt_') tmpdir = _os.getenv('TMPDIR') or _os.getenv('TEMP') or _os.getenv('TMP') if tmpdir: cache_name = tmpdir + '/filecache_' + cache_name.replace(_os.sep, '@') cache_name += '.cache' return cache_name
[ "def", "_get_cache_name", "(", "function", ")", ":", "module_name", "=", "_inspect", ".", "getfile", "(", "function", ")", "module_name", "=", "_os", ".", "path", ".", "abspath", "(", "module_name", ")", "cache_name", "=", "module_name", "# fix for '<string>' or...
returns a name for the module's cache db.
[ "returns", "a", "name", "for", "the", "module", "s", "cache", "db", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/filecache.py#L81-L98
26,622
keepkey/python-keepkey
keepkeylib/filecache.py
filecache
def filecache(seconds_of_validity=None, fail_silently=False): ''' filecache is called and the decorator should be returned. ''' def filecache_decorator(function): @_functools.wraps(function) def function_with_cache(*args, **kwargs): try: key = _args_key(function, args, kwargs) if key in function._db: rv = function._db[key] if seconds_of_validity is None or _time.time() - rv.timesig < seconds_of_validity: return rv.data except Exception: # in any case of failure, don't let filecache break the program error_str = _traceback.format_exc() _log_error(error_str) if not fail_silently: raise retval = function(*args, **kwargs) # store in cache # NOTE: no need to _db.sync() because there was no mutation # NOTE: it's importatnt to do _db.sync() because otherwise the cache doesn't survive Ctrl-Break! try: function._db[key] = _retval(_time.time(), retval) function._db.sync() except Exception: # in any case of failure, don't let filecache break the program error_str = _traceback.format_exc() _log_error(error_str) if not fail_silently: raise return retval # make sure cache is loaded if not hasattr(function, '_db'): cache_name = _get_cache_name(function) if cache_name in OPEN_DBS: function._db = OPEN_DBS[cache_name] else: function._db = _shelve.open(cache_name) OPEN_DBS[cache_name] = function._db atexit.register(function._db.close) function_with_cache._db = function._db return function_with_cache if type(seconds_of_validity) == types.FunctionType: # support for when people use '@filecache.filecache' instead of '@filecache.filecache()' func = seconds_of_validity seconds_of_validity = None return filecache_decorator(func) return filecache_decorator
python
def filecache(seconds_of_validity=None, fail_silently=False): ''' filecache is called and the decorator should be returned. ''' def filecache_decorator(function): @_functools.wraps(function) def function_with_cache(*args, **kwargs): try: key = _args_key(function, args, kwargs) if key in function._db: rv = function._db[key] if seconds_of_validity is None or _time.time() - rv.timesig < seconds_of_validity: return rv.data except Exception: # in any case of failure, don't let filecache break the program error_str = _traceback.format_exc() _log_error(error_str) if not fail_silently: raise retval = function(*args, **kwargs) # store in cache # NOTE: no need to _db.sync() because there was no mutation # NOTE: it's importatnt to do _db.sync() because otherwise the cache doesn't survive Ctrl-Break! try: function._db[key] = _retval(_time.time(), retval) function._db.sync() except Exception: # in any case of failure, don't let filecache break the program error_str = _traceback.format_exc() _log_error(error_str) if not fail_silently: raise return retval # make sure cache is loaded if not hasattr(function, '_db'): cache_name = _get_cache_name(function) if cache_name in OPEN_DBS: function._db = OPEN_DBS[cache_name] else: function._db = _shelve.open(cache_name) OPEN_DBS[cache_name] = function._db atexit.register(function._db.close) function_with_cache._db = function._db return function_with_cache if type(seconds_of_validity) == types.FunctionType: # support for when people use '@filecache.filecache' instead of '@filecache.filecache()' func = seconds_of_validity seconds_of_validity = None return filecache_decorator(func) return filecache_decorator
[ "def", "filecache", "(", "seconds_of_validity", "=", "None", ",", "fail_silently", "=", "False", ")", ":", "def", "filecache_decorator", "(", "function", ")", ":", "@", "_functools", ".", "wraps", "(", "function", ")", "def", "function_with_cache", "(", "*", ...
filecache is called and the decorator should be returned.
[ "filecache", "is", "called", "and", "the", "decorator", "should", "be", "returned", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/filecache.py#L129-L187
26,623
juju/python-libjuju
juju/model.py
ModelState.entity_data
def entity_data(self, entity_type, entity_id, history_index): """Return the data dict for an entity at a specific index of its history. """ return self.entity_history(entity_type, entity_id)[history_index]
python
def entity_data(self, entity_type, entity_id, history_index): return self.entity_history(entity_type, entity_id)[history_index]
[ "def", "entity_data", "(", "self", ",", "entity_type", ",", "entity_id", ",", "history_index", ")", ":", "return", "self", ".", "entity_history", "(", "entity_type", ",", "entity_id", ")", "[", "history_index", "]" ]
Return the data dict for an entity at a specific index of its history.
[ "Return", "the", "data", "dict", "for", "an", "entity", "at", "a", "specific", "index", "of", "its", "history", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L164-L169
26,624
juju/python-libjuju
juju/model.py
ModelState.get_entity
def get_entity( self, entity_type, entity_id, history_index=-1, connected=True): """Return an object instance for the given entity_type and id. By default the object state matches the most recent state from Juju. To get an instance of the object in an older state, pass history_index, an index into the history deque for the entity. """ if history_index < 0 and history_index != -1: history_index += len(self.entity_history(entity_type, entity_id)) if history_index < 0: return None try: self.entity_data(entity_type, entity_id, history_index) except IndexError: return None entity_class = get_entity_class(entity_type) return entity_class( entity_id, self.model, history_index=history_index, connected=connected)
python
def get_entity( self, entity_type, entity_id, history_index=-1, connected=True): if history_index < 0 and history_index != -1: history_index += len(self.entity_history(entity_type, entity_id)) if history_index < 0: return None try: self.entity_data(entity_type, entity_id, history_index) except IndexError: return None entity_class = get_entity_class(entity_type) return entity_class( entity_id, self.model, history_index=history_index, connected=connected)
[ "def", "get_entity", "(", "self", ",", "entity_type", ",", "entity_id", ",", "history_index", "=", "-", "1", ",", "connected", "=", "True", ")", ":", "if", "history_index", "<", "0", "and", "history_index", "!=", "-", "1", ":", "history_index", "+=", "le...
Return an object instance for the given entity_type and id. By default the object state matches the most recent state from Juju. To get an instance of the object in an older state, pass history_index, an index into the history deque for the entity.
[ "Return", "an", "object", "instance", "for", "the", "given", "entity_type", "and", "id", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L197-L220
26,625
juju/python-libjuju
juju/model.py
ModelEntity.on_change
def on_change(self, callable_): """Add a change observer to this entity. """ self.model.add_observer( callable_, self.entity_type, 'change', self.entity_id)
python
def on_change(self, callable_): self.model.add_observer( callable_, self.entity_type, 'change', self.entity_id)
[ "def", "on_change", "(", "self", ",", "callable_", ")", ":", "self", ".", "model", ".", "add_observer", "(", "callable_", ",", "self", ".", "entity_type", ",", "'change'", ",", "self", ".", "entity_id", ")" ]
Add a change observer to this entity.
[ "Add", "a", "change", "observer", "to", "this", "entity", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L265-L270
26,626
juju/python-libjuju
juju/model.py
ModelEntity.on_remove
def on_remove(self, callable_): """Add a remove observer to this entity. """ self.model.add_observer( callable_, self.entity_type, 'remove', self.entity_id)
python
def on_remove(self, callable_): self.model.add_observer( callable_, self.entity_type, 'remove', self.entity_id)
[ "def", "on_remove", "(", "self", ",", "callable_", ")", ":", "self", ".", "model", ".", "add_observer", "(", "callable_", ",", "self", ".", "entity_type", ",", "'remove'", ",", "self", ".", "entity_id", ")" ]
Add a remove observer to this entity.
[ "Add", "a", "remove", "observer", "to", "this", "entity", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L272-L277
26,627
juju/python-libjuju
juju/model.py
ModelEntity.dead
def dead(self): """Returns True if this entity no longer exists in the underlying model. """ return ( self.data is None or self.model.state.entity_data( self.entity_type, self.entity_id, -1) is None )
python
def dead(self): return ( self.data is None or self.model.state.entity_data( self.entity_type, self.entity_id, -1) is None )
[ "def", "dead", "(", "self", ")", ":", "return", "(", "self", ".", "data", "is", "None", "or", "self", ".", "model", ".", "state", ".", "entity_data", "(", "self", ".", "entity_type", ",", "self", ".", "entity_id", ",", "-", "1", ")", "is", "None", ...
Returns True if this entity no longer exists in the underlying model.
[ "Returns", "True", "if", "this", "entity", "no", "longer", "exists", "in", "the", "underlying", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L300-L309
26,628
juju/python-libjuju
juju/model.py
ModelEntity.previous
def previous(self): """Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates. """ return self.model.state.get_entity( self.entity_type, self.entity_id, self._history_index - 1, connected=False)
python
def previous(self): return self.model.state.get_entity( self.entity_type, self.entity_id, self._history_index - 1, connected=False)
[ "def", "previous", "(", "self", ")", ":", "return", "self", ".", "model", ".", "state", ".", "get_entity", "(", "self", ".", "entity_type", ",", "self", ".", "entity_id", ",", "self", ".", "_history_index", "-", "1", ",", "connected", "=", "False", ")"...
Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates.
[ "Return", "a", "copy", "of", "this", "object", "as", "was", "at", "its", "previous", "state", "in", "history", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L343-L355
26,629
juju/python-libjuju
juju/model.py
ModelEntity.next
def next(self): """Return a copy of this object at its next state in history. Returns None if this object is already the latest. The returned object is "disconnected", i.e. does not receive live updates, unless it is current (latest). """ if self._history_index == -1: return None new_index = self._history_index + 1 connected = ( new_index == len(self.model.state.entity_history( self.entity_type, self.entity_id)) - 1 ) return self.model.state.get_entity( self.entity_type, self.entity_id, self._history_index - 1, connected=connected)
python
def next(self): if self._history_index == -1: return None new_index = self._history_index + 1 connected = ( new_index == len(self.model.state.entity_history( self.entity_type, self.entity_id)) - 1 ) return self.model.state.get_entity( self.entity_type, self.entity_id, self._history_index - 1, connected=connected)
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_history_index", "==", "-", "1", ":", "return", "None", "new_index", "=", "self", ".", "_history_index", "+", "1", "connected", "=", "(", "new_index", "==", "len", "(", "self", ".", "model", "...
Return a copy of this object at its next state in history. Returns None if this object is already the latest. The returned object is "disconnected", i.e. does not receive live updates, unless it is current (latest).
[ "Return", "a", "copy", "of", "this", "object", "at", "its", "next", "state", "in", "history", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L357-L377
26,630
juju/python-libjuju
juju/model.py
Model.connect
async def connect(self, *args, **kwargs): """Connect to a juju model. This supports two calling conventions: The model and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``model_name`` is specified, or if the ``endpoint`` and ``uuid`` are not. Otherwise, all of the ``endpoint``, ``uuid``, and authentication information (``username`` and ``password``, or ``bakery_client`` and/or ``macaroons``) are required. If a single positional argument is given, it will be assumed to be the ``model_name``. Otherwise, the first positional argument, if any, must be the ``endpoint``. Available parameters are: :param model_name: Format [controller:][user/]model :param str endpoint: The hostname:port of the controller to connect to. :param str uuid: The model UUID to connect to. :param str username: The username for controller-local users (or None to use macaroon-based login.) :param str password: The password for controller-local users. :param str cacert: The CA certificate of the controller (PEM formatted). :param httpbakery.Client bakery_client: The macaroon bakery client to to use when performing macaroon-based login. Macaroon tokens acquired when logging will be saved to bakery_client.cookies. If this is None, a default bakery_client will be used. :param list macaroons: List of macaroons to load into the ``bakery_client``. :param asyncio.BaseEventLoop loop: The event loop to use for async operations. :param int max_frame_size: The maximum websocket frame size to allow. """ await self.disconnect() if 'endpoint' not in kwargs and len(args) < 2: if args and 'model_name' in kwargs: raise TypeError('connect() got multiple values for model_name') elif args: model_name = args[0] else: model_name = kwargs.pop('model_name', None) await self._connector.connect_model(model_name, **kwargs) else: if 'model_name' in kwargs: raise TypeError('connect() got values for both ' 'model_name and endpoint') if args and 'endpoint' in kwargs: raise TypeError('connect() got multiple values for endpoint') if len(args) < 2 and 'uuid' not in kwargs: raise TypeError('connect() missing value for uuid') has_userpass = (len(args) >= 4 or {'username', 'password'}.issubset(kwargs)) has_macaroons = (len(args) >= 6 or not {'bakery_client', 'macaroons'}.isdisjoint(kwargs)) if not (has_userpass or has_macaroons): raise TypeError('connect() missing auth params') arg_names = [ 'endpoint', 'uuid', 'username', 'password', 'cacert', 'bakery_client', 'macaroons', 'loop', 'max_frame_size', ] for i, arg in enumerate(args): kwargs[arg_names[i]] = arg if not {'endpoint', 'uuid'}.issubset(kwargs): raise ValueError('endpoint and uuid are required ' 'if model_name not given') if not ({'username', 'password'}.issubset(kwargs) or {'bakery_client', 'macaroons'}.intersection(kwargs)): raise ValueError('Authentication parameters are required ' 'if model_name not given') await self._connector.connect(**kwargs) await self._after_connect()
python
async def connect(self, *args, **kwargs): await self.disconnect() if 'endpoint' not in kwargs and len(args) < 2: if args and 'model_name' in kwargs: raise TypeError('connect() got multiple values for model_name') elif args: model_name = args[0] else: model_name = kwargs.pop('model_name', None) await self._connector.connect_model(model_name, **kwargs) else: if 'model_name' in kwargs: raise TypeError('connect() got values for both ' 'model_name and endpoint') if args and 'endpoint' in kwargs: raise TypeError('connect() got multiple values for endpoint') if len(args) < 2 and 'uuid' not in kwargs: raise TypeError('connect() missing value for uuid') has_userpass = (len(args) >= 4 or {'username', 'password'}.issubset(kwargs)) has_macaroons = (len(args) >= 6 or not {'bakery_client', 'macaroons'}.isdisjoint(kwargs)) if not (has_userpass or has_macaroons): raise TypeError('connect() missing auth params') arg_names = [ 'endpoint', 'uuid', 'username', 'password', 'cacert', 'bakery_client', 'macaroons', 'loop', 'max_frame_size', ] for i, arg in enumerate(args): kwargs[arg_names[i]] = arg if not {'endpoint', 'uuid'}.issubset(kwargs): raise ValueError('endpoint and uuid are required ' 'if model_name not given') if not ({'username', 'password'}.issubset(kwargs) or {'bakery_client', 'macaroons'}.intersection(kwargs)): raise ValueError('Authentication parameters are required ' 'if model_name not given') await self._connector.connect(**kwargs) await self._after_connect()
[ "async", "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "disconnect", "(", ")", "if", "'endpoint'", "not", "in", "kwargs", "and", "len", "(", "args", ")", "<", "2", ":", "if", "args", "an...
Connect to a juju model. This supports two calling conventions: The model and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``model_name`` is specified, or if the ``endpoint`` and ``uuid`` are not. Otherwise, all of the ``endpoint``, ``uuid``, and authentication information (``username`` and ``password``, or ``bakery_client`` and/or ``macaroons``) are required. If a single positional argument is given, it will be assumed to be the ``model_name``. Otherwise, the first positional argument, if any, must be the ``endpoint``. Available parameters are: :param model_name: Format [controller:][user/]model :param str endpoint: The hostname:port of the controller to connect to. :param str uuid: The model UUID to connect to. :param str username: The username for controller-local users (or None to use macaroon-based login.) :param str password: The password for controller-local users. :param str cacert: The CA certificate of the controller (PEM formatted). :param httpbakery.Client bakery_client: The macaroon bakery client to to use when performing macaroon-based login. Macaroon tokens acquired when logging will be saved to bakery_client.cookies. If this is None, a default bakery_client will be used. :param list macaroons: List of macaroons to load into the ``bakery_client``. :param asyncio.BaseEventLoop loop: The event loop to use for async operations. :param int max_frame_size: The maximum websocket frame size to allow.
[ "Connect", "to", "a", "juju", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L465-L547
26,631
juju/python-libjuju
juju/model.py
Model.add_local_charm_dir
async def add_local_charm_dir(self, charm_dir, series): """Upload a local charm to the model. This will automatically generate an archive from the charm dir. :param charm_dir: Path to the charm directory :param series: Charm series """ fh = tempfile.NamedTemporaryFile() CharmArchiveGenerator(charm_dir).make_archive(fh.name) with fh: func = partial( self.add_local_charm, fh, series, os.stat(fh.name).st_size) charm_url = await self._connector.loop.run_in_executor(None, func) log.debug('Uploaded local charm: %s -> %s', charm_dir, charm_url) return charm_url
python
async def add_local_charm_dir(self, charm_dir, series): fh = tempfile.NamedTemporaryFile() CharmArchiveGenerator(charm_dir).make_archive(fh.name) with fh: func = partial( self.add_local_charm, fh, series, os.stat(fh.name).st_size) charm_url = await self._connector.loop.run_in_executor(None, func) log.debug('Uploaded local charm: %s -> %s', charm_dir, charm_url) return charm_url
[ "async", "def", "add_local_charm_dir", "(", "self", ",", "charm_dir", ",", "series", ")", ":", "fh", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "CharmArchiveGenerator", "(", "charm_dir", ")", ".", "make_archive", "(", "fh", ".", "name", ")", "with...
Upload a local charm to the model. This will automatically generate an archive from the charm dir. :param charm_dir: Path to the charm directory :param series: Charm series
[ "Upload", "a", "local", "charm", "to", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L597-L615
26,632
juju/python-libjuju
juju/model.py
Model.add_local_charm
def add_local_charm(self, charm_file, series, size=None): """Upload a local charm archive to the model. Returns the 'local:...' url that should be used to deploy the charm. :param charm_file: Path to charm zip archive :param series: Charm series :param size: Size of the archive, in bytes :return str: 'local:...' url for deploying the charm :raises: :class:`JujuError` if the upload fails Uses an https endpoint at the same host:port as the wss. Supports large file uploads. .. warning:: This method will block. Consider using :meth:`add_local_charm_dir` instead. """ conn, headers, path_prefix = self.connection().https_connection() path = "%s/charms?series=%s" % (path_prefix, series) headers['Content-Type'] = 'application/zip' if size: headers['Content-Length'] = size conn.request("POST", path, charm_file, headers) response = conn.getresponse() result = response.read().decode() if not response.status == 200: raise JujuError(result) result = json.loads(result) return result['charm-url']
python
def add_local_charm(self, charm_file, series, size=None): conn, headers, path_prefix = self.connection().https_connection() path = "%s/charms?series=%s" % (path_prefix, series) headers['Content-Type'] = 'application/zip' if size: headers['Content-Length'] = size conn.request("POST", path, charm_file, headers) response = conn.getresponse() result = response.read().decode() if not response.status == 200: raise JujuError(result) result = json.loads(result) return result['charm-url']
[ "def", "add_local_charm", "(", "self", ",", "charm_file", ",", "series", ",", "size", "=", "None", ")", ":", "conn", ",", "headers", ",", "path_prefix", "=", "self", ".", "connection", "(", ")", ".", "https_connection", "(", ")", "path", "=", "\"%s/charm...
Upload a local charm archive to the model. Returns the 'local:...' url that should be used to deploy the charm. :param charm_file: Path to charm zip archive :param series: Charm series :param size: Size of the archive, in bytes :return str: 'local:...' url for deploying the charm :raises: :class:`JujuError` if the upload fails Uses an https endpoint at the same host:port as the wss. Supports large file uploads. .. warning:: This method will block. Consider using :meth:`add_local_charm_dir` instead.
[ "Upload", "a", "local", "charm", "archive", "to", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L617-L648
26,633
juju/python-libjuju
juju/model.py
Model.all_units_idle
def all_units_idle(self): """Return True if all units are idle. """ for unit in self.units.values(): unit_status = unit.data['agent-status']['current'] if unit_status != 'idle': return False return True
python
def all_units_idle(self): for unit in self.units.values(): unit_status = unit.data['agent-status']['current'] if unit_status != 'idle': return False return True
[ "def", "all_units_idle", "(", "self", ")", ":", "for", "unit", "in", "self", ".", "units", ".", "values", "(", ")", ":", "unit_status", "=", "unit", ".", "data", "[", "'agent-status'", "]", "[", "'current'", "]", "if", "unit_status", "!=", "'idle'", ":...
Return True if all units are idle.
[ "Return", "True", "if", "all", "units", "are", "idle", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L650-L658
26,634
juju/python-libjuju
juju/model.py
Model.reset
async def reset(self, force=False): """Reset the model to a clean state. :param bool force: Force-terminate machines. This returns only after the model has reached a clean state. "Clean" means no applications or machines exist in the model. """ log.debug('Resetting model') for app in self.applications.values(): await app.destroy() for machine in self.machines.values(): await machine.destroy(force=force) await self.block_until( lambda: len(self.machines) == 0 )
python
async def reset(self, force=False): log.debug('Resetting model') for app in self.applications.values(): await app.destroy() for machine in self.machines.values(): await machine.destroy(force=force) await self.block_until( lambda: len(self.machines) == 0 )
[ "async", "def", "reset", "(", "self", ",", "force", "=", "False", ")", ":", "log", ".", "debug", "(", "'Resetting model'", ")", "for", "app", "in", "self", ".", "applications", ".", "values", "(", ")", ":", "await", "app", ".", "destroy", "(", ")", ...
Reset the model to a clean state. :param bool force: Force-terminate machines. This returns only after the model has reached a clean state. "Clean" means no applications or machines exist in the model.
[ "Reset", "the", "model", "to", "a", "clean", "state", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L660-L676
26,635
juju/python-libjuju
juju/model.py
Model.get_info
async def get_info(self): """Return a client.ModelInfo object for this Model. Retrieves latest info for this Model from the api server. The return value is cached on the Model.info attribute so that the valued may be accessed again without another api call, if desired. This method is called automatically when the Model is connected, resulting in Model.info being initialized without requiring an explicit call to this method. """ facade = client.ClientFacade.from_connection(self.connection()) self._info = await facade.ModelInfo() log.debug('Got ModelInfo: %s', vars(self.info)) return self.info
python
async def get_info(self): facade = client.ClientFacade.from_connection(self.connection()) self._info = await facade.ModelInfo() log.debug('Got ModelInfo: %s', vars(self.info)) return self.info
[ "async", "def", "get_info", "(", "self", ")", ":", "facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "self", ".", "_info", "=", "await", "facade", ".", "ModelInfo", "(", ")", "log", "."...
Return a client.ModelInfo object for this Model. Retrieves latest info for this Model from the api server. The return value is cached on the Model.info attribute so that the valued may be accessed again without another api call, if desired. This method is called automatically when the Model is connected, resulting in Model.info being initialized without requiring an explicit call to this method.
[ "Return", "a", "client", ".", "ModelInfo", "object", "for", "this", "Model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L731-L749
26,636
juju/python-libjuju
juju/model.py
Model.add_observer
def add_observer( self, callable_, entity_type=None, action=None, entity_id=None, predicate=None): """Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable and accept the following positional arguments: delta - An instance of :class:`juju.delta.EntityDelta` containing the raw delta data recv'd from the Juju websocket. old_obj - If the delta modifies an existing object in the model, old_obj will be a copy of that object, as it was before the delta was applied. Will be None if the delta creates a new entity in the model. new_obj - A copy of the new or updated object, after the delta is applied. Will be None if the delta removes an entity from the model. model - The :class:`Model` itself. Events for which ``callable_`` is called can be specified by passing entity_type, action, and/or entitiy_id filter criteria, e.g.:: add_observer( myfunc, entity_type='application', action='add', entity_id='ubuntu') For more complex filtering conditions, pass a predicate function. It will be called with a delta as its only argument. If the predicate function returns True, the ``callable_`` will be called. """ observer = _Observer( callable_, entity_type, action, entity_id, predicate) self._observers[observer] = callable_
python
def add_observer( self, callable_, entity_type=None, action=None, entity_id=None, predicate=None): observer = _Observer( callable_, entity_type, action, entity_id, predicate) self._observers[observer] = callable_
[ "def", "add_observer", "(", "self", ",", "callable_", ",", "entity_type", "=", "None", ",", "action", "=", "None", ",", "entity_id", "=", "None", ",", "predicate", "=", "None", ")", ":", "observer", "=", "_Observer", "(", "callable_", ",", "entity_type", ...
Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable and accept the following positional arguments: delta - An instance of :class:`juju.delta.EntityDelta` containing the raw delta data recv'd from the Juju websocket. old_obj - If the delta modifies an existing object in the model, old_obj will be a copy of that object, as it was before the delta was applied. Will be None if the delta creates a new entity in the model. new_obj - A copy of the new or updated object, after the delta is applied. Will be None if the delta removes an entity from the model. model - The :class:`Model` itself. Events for which ``callable_`` is called can be specified by passing entity_type, action, and/or entitiy_id filter criteria, e.g.:: add_observer( myfunc, entity_type='application', action='add', entity_id='ubuntu') For more complex filtering conditions, pass a predicate function. It will be called with a delta as its only argument. If the predicate function returns True, the ``callable_`` will be called.
[ "Register", "an", "on", "-", "model", "-", "change", "callback" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L759-L797
26,637
juju/python-libjuju
juju/model.py
Model._watch
def _watch(self): """Start an asynchronous watch against this model. See :meth:`add_observer` to register an onchange callback. """ async def _all_watcher(): try: allwatcher = client.AllWatcherFacade.from_connection( self.connection()) while not self._watch_stopping.is_set(): try: results = await utils.run_with_interrupt( allwatcher.Next(), self._watch_stopping, loop=self._connector.loop) except JujuAPIError as e: if 'watcher was stopped' not in str(e): raise if self._watch_stopping.is_set(): # this shouldn't ever actually happen, because # the event should trigger before the controller # has a chance to tell us the watcher is stopped # but handle it gracefully, just in case break # controller stopped our watcher for some reason # but we're not actually stopping, so just restart it log.warning( 'Watcher: watcher stopped, restarting') del allwatcher.Id continue except websockets.ConnectionClosed: monitor = self.connection().monitor if monitor.status == monitor.ERROR: # closed unexpectedly, try to reopen log.warning( 'Watcher: connection closed, reopening') await self.connection().reconnect() if monitor.status != monitor.CONNECTED: # reconnect failed; abort and shutdown log.error('Watcher: automatic reconnect ' 'failed; stopping watcher') break del allwatcher.Id continue else: # closed on request, go ahead and shutdown break if self._watch_stopping.is_set(): try: await allwatcher.Stop() except websockets.ConnectionClosed: pass # can't stop on a closed conn break for delta in results.deltas: try: delta = get_entity_delta(delta) old_obj, new_obj = self.state.apply_delta(delta) await self._notify_observers(delta, old_obj, new_obj) except KeyError as e: log.debug("unknown delta type: %s", e.args[0]) self._watch_received.set() except CancelledError: pass except Exception: log.exception('Error in watcher') raise finally: self._watch_stopped.set() log.debug('Starting watcher task') self._watch_received.clear() self._watch_stopping.clear() self._watch_stopped.clear() self._connector.loop.create_task(_all_watcher())
python
def _watch(self): async def _all_watcher(): try: allwatcher = client.AllWatcherFacade.from_connection( self.connection()) while not self._watch_stopping.is_set(): try: results = await utils.run_with_interrupt( allwatcher.Next(), self._watch_stopping, loop=self._connector.loop) except JujuAPIError as e: if 'watcher was stopped' not in str(e): raise if self._watch_stopping.is_set(): # this shouldn't ever actually happen, because # the event should trigger before the controller # has a chance to tell us the watcher is stopped # but handle it gracefully, just in case break # controller stopped our watcher for some reason # but we're not actually stopping, so just restart it log.warning( 'Watcher: watcher stopped, restarting') del allwatcher.Id continue except websockets.ConnectionClosed: monitor = self.connection().monitor if monitor.status == monitor.ERROR: # closed unexpectedly, try to reopen log.warning( 'Watcher: connection closed, reopening') await self.connection().reconnect() if monitor.status != monitor.CONNECTED: # reconnect failed; abort and shutdown log.error('Watcher: automatic reconnect ' 'failed; stopping watcher') break del allwatcher.Id continue else: # closed on request, go ahead and shutdown break if self._watch_stopping.is_set(): try: await allwatcher.Stop() except websockets.ConnectionClosed: pass # can't stop on a closed conn break for delta in results.deltas: try: delta = get_entity_delta(delta) old_obj, new_obj = self.state.apply_delta(delta) await self._notify_observers(delta, old_obj, new_obj) except KeyError as e: log.debug("unknown delta type: %s", e.args[0]) self._watch_received.set() except CancelledError: pass except Exception: log.exception('Error in watcher') raise finally: self._watch_stopped.set() log.debug('Starting watcher task') self._watch_received.clear() self._watch_stopping.clear() self._watch_stopped.clear() self._connector.loop.create_task(_all_watcher())
[ "def", "_watch", "(", "self", ")", ":", "async", "def", "_all_watcher", "(", ")", ":", "try", ":", "allwatcher", "=", "client", ".", "AllWatcherFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "while", "not", "self", ".", ...
Start an asynchronous watch against this model. See :meth:`add_observer` to register an onchange callback.
[ "Start", "an", "asynchronous", "watch", "against", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L799-L873
26,638
juju/python-libjuju
juju/model.py
Model._notify_observers
async def _notify_observers(self, delta, old_obj, new_obj): """Call observing callbacks, notifying them of a change in model state :param delta: The raw change from the watcher (:class:`juju.client.overrides.Delta`) :param old_obj: The object in the model that this delta updates. May be None. :param new_obj: The object in the model that is created or updated by applying this delta. """ if new_obj and not old_obj: delta.type = 'add' log.debug( 'Model changed: %s %s %s', delta.entity, delta.type, delta.get_id()) for o in self._observers: if o.cares_about(delta): asyncio.ensure_future(o(delta, old_obj, new_obj, self), loop=self._connector.loop)
python
async def _notify_observers(self, delta, old_obj, new_obj): if new_obj and not old_obj: delta.type = 'add' log.debug( 'Model changed: %s %s %s', delta.entity, delta.type, delta.get_id()) for o in self._observers: if o.cares_about(delta): asyncio.ensure_future(o(delta, old_obj, new_obj, self), loop=self._connector.loop)
[ "async", "def", "_notify_observers", "(", "self", ",", "delta", ",", "old_obj", ",", "new_obj", ")", ":", "if", "new_obj", "and", "not", "old_obj", ":", "delta", ".", "type", "=", "'add'", "log", ".", "debug", "(", "'Model changed: %s %s %s'", ",", "delta"...
Call observing callbacks, notifying them of a change in model state :param delta: The raw change from the watcher (:class:`juju.client.overrides.Delta`) :param old_obj: The object in the model that this delta updates. May be None. :param new_obj: The object in the model that is created or updated by applying this delta.
[ "Call", "observing", "callbacks", "notifying", "them", "of", "a", "change", "in", "model", "state" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L875-L896
26,639
juju/python-libjuju
juju/model.py
Model._wait
async def _wait(self, entity_type, entity_id, action, predicate=None): """ Block the calling routine until a given action has happened to the given entity :param entity_type: The entity's type. :param entity_id: The entity's id. :param action: the type of action (e.g., 'add', 'change', or 'remove') :param predicate: optional callable that must take as an argument a delta, and must return a boolean, indicating whether the delta contains the specific action we're looking for. For example, you might check to see whether a 'change' has a 'completed' status. See the _Observer class for details. """ q = asyncio.Queue(loop=self._connector.loop) async def callback(delta, old, new, model): await q.put(delta.get_id()) self.add_observer(callback, entity_type, action, entity_id, predicate) entity_id = await q.get() # object might not be in the entity_map if we were waiting for a # 'remove' action return self.state._live_entity_map(entity_type).get(entity_id)
python
async def _wait(self, entity_type, entity_id, action, predicate=None): q = asyncio.Queue(loop=self._connector.loop) async def callback(delta, old, new, model): await q.put(delta.get_id()) self.add_observer(callback, entity_type, action, entity_id, predicate) entity_id = await q.get() # object might not be in the entity_map if we were waiting for a # 'remove' action return self.state._live_entity_map(entity_type).get(entity_id)
[ "async", "def", "_wait", "(", "self", ",", "entity_type", ",", "entity_id", ",", "action", ",", "predicate", "=", "None", ")", ":", "q", "=", "asyncio", ".", "Queue", "(", "loop", "=", "self", ".", "_connector", ".", "loop", ")", "async", "def", "cal...
Block the calling routine until a given action has happened to the given entity :param entity_type: The entity's type. :param entity_id: The entity's id. :param action: the type of action (e.g., 'add', 'change', or 'remove') :param predicate: optional callable that must take as an argument a delta, and must return a boolean, indicating whether the delta contains the specific action we're looking for. For example, you might check to see whether a 'change' has a 'completed' status. See the _Observer class for details.
[ "Block", "the", "calling", "routine", "until", "a", "given", "action", "has", "happened", "to", "the", "given", "entity" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L898-L922
26,640
juju/python-libjuju
juju/model.py
Model._wait_for_new
async def _wait_for_new(self, entity_type, entity_id): """Wait for a new object to appear in the Model and return it. Waits for an object of type ``entity_type`` with id ``entity_id`` to appear in the model. This is similar to watching for the object using ``block_until``, but uses the watcher rather than polling. """ # if the entity is already in the model, just return it if entity_id in self.state._live_entity_map(entity_type): return self.state._live_entity_map(entity_type)[entity_id] return await self._wait(entity_type, entity_id, None)
python
async def _wait_for_new(self, entity_type, entity_id): # if the entity is already in the model, just return it if entity_id in self.state._live_entity_map(entity_type): return self.state._live_entity_map(entity_type)[entity_id] return await self._wait(entity_type, entity_id, None)
[ "async", "def", "_wait_for_new", "(", "self", ",", "entity_type", ",", "entity_id", ")", ":", "# if the entity is already in the model, just return it", "if", "entity_id", "in", "self", ".", "state", ".", "_live_entity_map", "(", "entity_type", ")", ":", "return", "...
Wait for a new object to appear in the Model and return it. Waits for an object of type ``entity_type`` with id ``entity_id`` to appear in the model. This is similar to watching for the object using ``block_until``, but uses the watcher rather than polling.
[ "Wait", "for", "a", "new", "object", "to", "appear", "in", "the", "Model", "and", "return", "it", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L924-L936
26,641
juju/python-libjuju
juju/model.py
Model.wait_for_action
async def wait_for_action(self, action_id): """Given an action, wait for it to complete.""" if action_id.startswith("action-"): # if we've been passed action.tag, transform it into the # id that the api deltas will use. action_id = action_id[7:] def predicate(delta): return delta.data['status'] in ('completed', 'failed') return await self._wait('action', action_id, None, predicate)
python
async def wait_for_action(self, action_id): if action_id.startswith("action-"): # if we've been passed action.tag, transform it into the # id that the api deltas will use. action_id = action_id[7:] def predicate(delta): return delta.data['status'] in ('completed', 'failed') return await self._wait('action', action_id, None, predicate)
[ "async", "def", "wait_for_action", "(", "self", ",", "action_id", ")", ":", "if", "action_id", ".", "startswith", "(", "\"action-\"", ")", ":", "# if we've been passed action.tag, transform it into the", "# id that the api deltas will use.", "action_id", "=", "action_id", ...
Given an action, wait for it to complete.
[ "Given", "an", "action", "wait", "for", "it", "to", "complete", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L938-L949
26,642
juju/python-libjuju
juju/model.py
Model.add_machine
async def add_machine( self, spec=None, constraints=None, disks=None, series=None): """Start a new, empty machine and optionally a container, or add a container to a machine. :param str spec: Machine specification Examples:: (None) - starts a new machine 'lxd' - starts a new machine with one lxd container 'lxd:4' - starts a new lxd container on machine 4 'ssh:user@10.10.0.3:/path/to/private/key' - manually provision a machine with ssh and the private key used for authentication 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS 'maas2.name' - acquire machine maas2.name on MAAS :param dict constraints: Machine constraints, which can contain the the following keys:: arch : str container : str cores : int cpu_power : int instance_type : str mem : int root_disk : int spaces : list(str) tags : list(str) virt_type : str Example:: constraints={ 'mem': 256 * MB, 'tags': ['virtual'], } :param list disks: List of disk constraint dictionaries, which can contain the following keys:: count : int pool : str size : int Example:: disks=[{ 'pool': 'rootfs', 'size': 10 * GB, 'count': 1, }] :param str series: Series, e.g. 'xenial' Supported container types are: lxd, kvm When deploying a container to an existing machine, constraints cannot be used. """ params = client.AddMachineParams() if spec: if spec.startswith("ssh:"): placement, target, private_key_path = spec.split(":") user, host = target.split("@") sshProvisioner = provisioner.SSHProvisioner( host=host, user=user, private_key_path=private_key_path, ) params = sshProvisioner.provision_machine() else: placement = parse_placement(spec) if placement: params.placement = placement[0] params.jobs = ['JobHostUnits'] if constraints: params.constraints = client.Value.from_json(constraints) if disks: params.disks = [ client.Constraints.from_json(o) for o in disks] if series: params.series = series # Submit the request. client_facade = client.ClientFacade.from_connection(self.connection()) results = await client_facade.AddMachines([params]) error = results.machines[0].error if error: raise ValueError("Error adding machine: %s" % error.message) machine_id = results.machines[0].machine if spec: if spec.startswith("ssh:"): # Need to run this after AddMachines has been called, # as we need the machine_id await sshProvisioner.install_agent( self.connection(), params.nonce, machine_id, ) log.debug('Added new machine %s', machine_id) return await self._wait_for_new('machine', machine_id)
python
async def add_machine( self, spec=None, constraints=None, disks=None, series=None): params = client.AddMachineParams() if spec: if spec.startswith("ssh:"): placement, target, private_key_path = spec.split(":") user, host = target.split("@") sshProvisioner = provisioner.SSHProvisioner( host=host, user=user, private_key_path=private_key_path, ) params = sshProvisioner.provision_machine() else: placement = parse_placement(spec) if placement: params.placement = placement[0] params.jobs = ['JobHostUnits'] if constraints: params.constraints = client.Value.from_json(constraints) if disks: params.disks = [ client.Constraints.from_json(o) for o in disks] if series: params.series = series # Submit the request. client_facade = client.ClientFacade.from_connection(self.connection()) results = await client_facade.AddMachines([params]) error = results.machines[0].error if error: raise ValueError("Error adding machine: %s" % error.message) machine_id = results.machines[0].machine if spec: if spec.startswith("ssh:"): # Need to run this after AddMachines has been called, # as we need the machine_id await sshProvisioner.install_agent( self.connection(), params.nonce, machine_id, ) log.debug('Added new machine %s', machine_id) return await self._wait_for_new('machine', machine_id)
[ "async", "def", "add_machine", "(", "self", ",", "spec", "=", "None", ",", "constraints", "=", "None", ",", "disks", "=", "None", ",", "series", "=", "None", ")", ":", "params", "=", "client", ".", "AddMachineParams", "(", ")", "if", "spec", ":", "if...
Start a new, empty machine and optionally a container, or add a container to a machine. :param str spec: Machine specification Examples:: (None) - starts a new machine 'lxd' - starts a new machine with one lxd container 'lxd:4' - starts a new lxd container on machine 4 'ssh:user@10.10.0.3:/path/to/private/key' - manually provision a machine with ssh and the private key used for authentication 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS 'maas2.name' - acquire machine maas2.name on MAAS :param dict constraints: Machine constraints, which can contain the the following keys:: arch : str container : str cores : int cpu_power : int instance_type : str mem : int root_disk : int spaces : list(str) tags : list(str) virt_type : str Example:: constraints={ 'mem': 256 * MB, 'tags': ['virtual'], } :param list disks: List of disk constraint dictionaries, which can contain the following keys:: count : int pool : str size : int Example:: disks=[{ 'pool': 'rootfs', 'size': 10 * GB, 'count': 1, }] :param str series: Series, e.g. 'xenial' Supported container types are: lxd, kvm When deploying a container to an existing machine, constraints cannot be used.
[ "Start", "a", "new", "empty", "machine", "and", "optionally", "a", "container", "or", "add", "a", "container", "to", "a", "machine", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L967-L1077
26,643
juju/python-libjuju
juju/model.py
Model.add_relation
async def add_relation(self, relation1, relation2): """Add a relation between two applications. :param str relation1: '<application>[:<relation_name>]' :param str relation2: '<application>[:<relation_name>]' """ connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Adding relation %s <-> %s', relation1, relation2) def _find_relation(*specs): for rel in self.relations: if rel.matches(*specs): return rel return None try: result = await app_facade.AddRelation([relation1, relation2]) except JujuAPIError as e: if 'relation already exists' not in e.message: raise rel = _find_relation(relation1, relation2) if rel: return rel raise JujuError('Relation {} {} exists but not in model'.format( relation1, relation2)) specs = ['{}:{}'.format(app, data['name']) for app, data in result.endpoints.items()] await self.block_until(lambda: _find_relation(*specs) is not None) return _find_relation(*specs)
python
async def add_relation(self, relation1, relation2): connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Adding relation %s <-> %s', relation1, relation2) def _find_relation(*specs): for rel in self.relations: if rel.matches(*specs): return rel return None try: result = await app_facade.AddRelation([relation1, relation2]) except JujuAPIError as e: if 'relation already exists' not in e.message: raise rel = _find_relation(relation1, relation2) if rel: return rel raise JujuError('Relation {} {} exists but not in model'.format( relation1, relation2)) specs = ['{}:{}'.format(app, data['name']) for app, data in result.endpoints.items()] await self.block_until(lambda: _find_relation(*specs) is not None) return _find_relation(*specs)
[ "async", "def", "add_relation", "(", "self", ",", "relation1", ",", "relation2", ")", ":", "connection", "=", "self", ".", "connection", "(", ")", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "connection", ")", "log", "...
Add a relation between two applications. :param str relation1: '<application>[:<relation_name>]' :param str relation2: '<application>[:<relation_name>]'
[ "Add", "a", "relation", "between", "two", "applications", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1079-L1113
26,644
juju/python-libjuju
juju/model.py
Model.add_ssh_key
async def add_ssh_key(self, user, key): """Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key """ key_facade = client.KeyManagerFacade.from_connection(self.connection()) return await key_facade.AddKeys([key], user)
python
async def add_ssh_key(self, user, key): key_facade = client.KeyManagerFacade.from_connection(self.connection()) return await key_facade.AddKeys([key], user)
[ "async", "def", "add_ssh_key", "(", "self", ",", "user", ",", "key", ")", ":", "key_facade", "=", "client", ".", "KeyManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "return", "await", "key_facade", ".", "AddKeys", "("...
Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key
[ "Add", "a", "public", "SSH", "key", "to", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1127-L1135
26,645
juju/python-libjuju
juju/model.py
Model.debug_log
def debug_log( self, no_tail=False, exclude_module=None, include_module=None, include=None, level=None, limit=0, lines=10, replay=False, exclude=None): """Get log messages for this model. :param bool no_tail: Stop after returning existing log messages :param list exclude_module: Do not show log messages for these logging modules :param list include_module: Only show log messages for these logging modules :param list include: Only show log messages for these entities :param str level: Log level to show, valid options are 'TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR, :param int limit: Return this many of the most recent (possibly filtered) lines are shown :param int lines: Yield this many of the most recent lines, and keep yielding :param bool replay: Yield the entire log, and keep yielding :param list exclude: Do not show log messages for these entities """ raise NotImplementedError()
python
def debug_log( self, no_tail=False, exclude_module=None, include_module=None, include=None, level=None, limit=0, lines=10, replay=False, exclude=None): raise NotImplementedError()
[ "def", "debug_log", "(", "self", ",", "no_tail", "=", "False", ",", "exclude_module", "=", "None", ",", "include_module", "=", "None", ",", "include", "=", "None", ",", "level", "=", "None", ",", "limit", "=", "0", ",", "lines", "=", "10", ",", "repl...
Get log messages for this model. :param bool no_tail: Stop after returning existing log messages :param list exclude_module: Do not show log messages for these logging modules :param list include_module: Only show log messages for these logging modules :param list include: Only show log messages for these entities :param str level: Log level to show, valid options are 'TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR, :param int limit: Return this many of the most recent (possibly filtered) lines are shown :param int lines: Yield this many of the most recent lines, and keep yielding :param bool replay: Yield the entire log, and keep yielding :param list exclude: Do not show log messages for these entities
[ "Get", "log", "messages", "for", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1199-L1221
26,646
juju/python-libjuju
juju/model.py
Model._deploy
async def _deploy(self, charm_url, application, series, config, constraints, endpoint_bindings, resources, storage, channel=None, num_units=None, placement=None, devices=None): """Logic shared between `Model.deploy` and `BundleHandler.deploy`. """ log.info('Deploying %s', charm_url) # stringify all config values for API, and convert to YAML config = {k: str(v) for k, v in config.items()} config = yaml.dump({application: config}, default_flow_style=False) app_facade = client.ApplicationFacade.from_connection( self.connection()) app = client.ApplicationDeploy( charm_url=charm_url, application=application, series=series, channel=channel, config_yaml=config, constraints=parse_constraints(constraints), endpoint_bindings=endpoint_bindings, num_units=num_units, resources=resources, storage=storage, placement=placement, devices=devices, ) result = await app_facade.Deploy([app]) errors = [r.error.message for r in result.results if r.error] if errors: raise JujuError('\n'.join(errors)) return await self._wait_for_new('application', application)
python
async def _deploy(self, charm_url, application, series, config, constraints, endpoint_bindings, resources, storage, channel=None, num_units=None, placement=None, devices=None): log.info('Deploying %s', charm_url) # stringify all config values for API, and convert to YAML config = {k: str(v) for k, v in config.items()} config = yaml.dump({application: config}, default_flow_style=False) app_facade = client.ApplicationFacade.from_connection( self.connection()) app = client.ApplicationDeploy( charm_url=charm_url, application=application, series=series, channel=channel, config_yaml=config, constraints=parse_constraints(constraints), endpoint_bindings=endpoint_bindings, num_units=num_units, resources=resources, storage=storage, placement=placement, devices=devices, ) result = await app_facade.Deploy([app]) errors = [r.error.message for r in result.results if r.error] if errors: raise JujuError('\n'.join(errors)) return await self._wait_for_new('application', application)
[ "async", "def", "_deploy", "(", "self", ",", "charm_url", ",", "application", ",", "series", ",", "config", ",", "constraints", ",", "endpoint_bindings", ",", "resources", ",", "storage", ",", "channel", "=", "None", ",", "num_units", "=", "None", ",", "pl...
Logic shared between `Model.deploy` and `BundleHandler.deploy`.
[ "Logic", "shared", "between", "Model", ".", "deploy", "and", "BundleHandler", ".", "deploy", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1407-L1441
26,647
juju/python-libjuju
juju/model.py
Model.destroy_unit
async def destroy_unit(self, *unit_names): """Destroy units by name. """ connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Destroying unit%s %s', 's' if len(unit_names) == 1 else '', ' '.join(unit_names)) return await app_facade.DestroyUnits(list(unit_names))
python
async def destroy_unit(self, *unit_names): connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Destroying unit%s %s', 's' if len(unit_names) == 1 else '', ' '.join(unit_names)) return await app_facade.DestroyUnits(list(unit_names))
[ "async", "def", "destroy_unit", "(", "self", ",", "*", "unit_names", ")", ":", "connection", "=", "self", ".", "connection", "(", ")", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "connection", ")", "log", ".", "debug",...
Destroy units by name.
[ "Destroy", "units", "by", "name", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1449-L1461
26,648
juju/python-libjuju
juju/model.py
Model.get_config
async def get_config(self): """Return the configuration settings for this model. :returns: A ``dict`` mapping keys to `ConfigValue` instances, which have `source` and `value` attributes. """ config_facade = client.ModelConfigFacade.from_connection( self.connection() ) result = await config_facade.ModelGet() config = result.config for key, value in config.items(): config[key] = ConfigValue.from_json(value) return config
python
async def get_config(self): config_facade = client.ModelConfigFacade.from_connection( self.connection() ) result = await config_facade.ModelGet() config = result.config for key, value in config.items(): config[key] = ConfigValue.from_json(value) return config
[ "async", "def", "get_config", "(", "self", ")", ":", "config_facade", "=", "client", ".", "ModelConfigFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "result", "=", "await", "config_facade", ".", "ModelGet", "(", ")", "config"...
Return the configuration settings for this model. :returns: A ``dict`` mapping keys to `ConfigValue` instances, which have `source` and `value` attributes.
[ "Return", "the", "configuration", "settings", "for", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1492-L1505
26,649
juju/python-libjuju
juju/model.py
Model.get_constraints
async def get_constraints(self): """Return the machine constraints for this model. :returns: A ``dict`` of constraints. """ constraints = {} client_facade = client.ClientFacade.from_connection(self.connection()) result = await client_facade.GetModelConstraints() # GetModelConstraints returns GetConstraintsResults which has a # 'constraints' attribute. If no constraints have been set # GetConstraintsResults.constraints is None. Otherwise # GetConstraintsResults.constraints has an attribute for each possible # constraint, each of these in turn will be None if they have not been # set. if result.constraints: constraint_types = [a for a in dir(result.constraints) if a in Value._toSchema.keys()] for constraint in constraint_types: value = getattr(result.constraints, constraint) if value is not None: constraints[constraint] = getattr(result.constraints, constraint) return constraints
python
async def get_constraints(self): constraints = {} client_facade = client.ClientFacade.from_connection(self.connection()) result = await client_facade.GetModelConstraints() # GetModelConstraints returns GetConstraintsResults which has a # 'constraints' attribute. If no constraints have been set # GetConstraintsResults.constraints is None. Otherwise # GetConstraintsResults.constraints has an attribute for each possible # constraint, each of these in turn will be None if they have not been # set. if result.constraints: constraint_types = [a for a in dir(result.constraints) if a in Value._toSchema.keys()] for constraint in constraint_types: value = getattr(result.constraints, constraint) if value is not None: constraints[constraint] = getattr(result.constraints, constraint) return constraints
[ "async", "def", "get_constraints", "(", "self", ")", ":", "constraints", "=", "{", "}", "client_facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "result", "=", "await", "client_facade", ".", ...
Return the machine constraints for this model. :returns: A ``dict`` of constraints.
[ "Return", "the", "machine", "constraints", "for", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1507-L1530
26,650
juju/python-libjuju
juju/model.py
Model.restore_backup
def restore_backup( self, bootstrap=False, constraints=None, archive=None, backup_id=None, upload_tools=False): """Restore a backup archive to a new controller. :param bool bootstrap: Bootstrap a new state machine :param constraints: Model constraints :type constraints: :class:`juju.Constraints` :param str archive: Path to backup archive to restore :param str backup_id: Id of backup to restore :param bool upload_tools: Upload tools if bootstrapping a new machine """ raise NotImplementedError()
python
def restore_backup( self, bootstrap=False, constraints=None, archive=None, backup_id=None, upload_tools=False): raise NotImplementedError()
[ "def", "restore_backup", "(", "self", ",", "bootstrap", "=", "False", ",", "constraints", "=", "None", ",", "archive", "=", "None", ",", "backup_id", "=", "None", ",", "upload_tools", "=", "False", ")", ":", "raise", "NotImplementedError", "(", ")" ]
Restore a backup archive to a new controller. :param bool bootstrap: Bootstrap a new state machine :param constraints: Model constraints :type constraints: :class:`juju.Constraints` :param str archive: Path to backup archive to restore :param str backup_id: Id of backup to restore :param bool upload_tools: Upload tools if bootstrapping a new machine
[ "Restore", "a", "backup", "archive", "to", "a", "new", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1645-L1658
26,651
juju/python-libjuju
juju/model.py
Model.set_config
async def set_config(self, config): """Set configuration keys on this model. :param dict config: Mapping of config keys to either string values or `ConfigValue` instances, as returned by `get_config`. """ config_facade = client.ModelConfigFacade.from_connection( self.connection() ) for key, value in config.items(): if isinstance(value, ConfigValue): config[key] = value.value await config_facade.ModelSet(config)
python
async def set_config(self, config): config_facade = client.ModelConfigFacade.from_connection( self.connection() ) for key, value in config.items(): if isinstance(value, ConfigValue): config[key] = value.value await config_facade.ModelSet(config)
[ "async", "def", "set_config", "(", "self", ",", "config", ")", ":", "config_facade", "=", "client", ".", "ModelConfigFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "for", "key", ",", "value", "in", "config", ".", "items", ...
Set configuration keys on this model. :param dict config: Mapping of config keys to either string values or `ConfigValue` instances, as returned by `get_config`.
[ "Set", "configuration", "keys", "on", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1675-L1687
26,652
juju/python-libjuju
juju/model.py
Model.set_constraints
async def set_constraints(self, constraints): """Set machine constraints on this model. :param dict config: Mapping of model constraints """ client_facade = client.ClientFacade.from_connection(self.connection()) await client_facade.SetModelConstraints( application='', constraints=constraints)
python
async def set_constraints(self, constraints): client_facade = client.ClientFacade.from_connection(self.connection()) await client_facade.SetModelConstraints( application='', constraints=constraints)
[ "async", "def", "set_constraints", "(", "self", ",", "constraints", ")", ":", "client_facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "await", "client_facade", ".", "SetModelConstraints", "(", ...
Set machine constraints on this model. :param dict config: Mapping of model constraints
[ "Set", "machine", "constraints", "on", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1689-L1697
26,653
juju/python-libjuju
juju/model.py
Model.get_action_output
async def get_action_output(self, action_uuid, wait=None): """Get the results of an action by ID. :param str action_uuid: Id of the action :param int wait: Time in seconds to wait for action to complete. :return dict: Output from action :raises: :class:`JujuError` if invalid action_uuid """ action_facade = client.ActionFacade.from_connection( self.connection() ) entity = [{'tag': tag.action(action_uuid)}] # Cannot use self.wait_for_action as the action event has probably # already happened and self.wait_for_action works by processing # model deltas and checking if they match our type. If the action # has already occured then the delta has gone. async def _wait_for_action_status(): while True: action_output = await action_facade.Actions(entity) if action_output.results[0].status in ('completed', 'failed'): return else: await asyncio.sleep(1) await asyncio.wait_for( _wait_for_action_status(), timeout=wait) action_output = await action_facade.Actions(entity) # ActionResult.output is None if the action produced no output if action_output.results[0].output is None: output = {} else: output = action_output.results[0].output return output
python
async def get_action_output(self, action_uuid, wait=None): action_facade = client.ActionFacade.from_connection( self.connection() ) entity = [{'tag': tag.action(action_uuid)}] # Cannot use self.wait_for_action as the action event has probably # already happened and self.wait_for_action works by processing # model deltas and checking if they match our type. If the action # has already occured then the delta has gone. async def _wait_for_action_status(): while True: action_output = await action_facade.Actions(entity) if action_output.results[0].status in ('completed', 'failed'): return else: await asyncio.sleep(1) await asyncio.wait_for( _wait_for_action_status(), timeout=wait) action_output = await action_facade.Actions(entity) # ActionResult.output is None if the action produced no output if action_output.results[0].output is None: output = {} else: output = action_output.results[0].output return output
[ "async", "def", "get_action_output", "(", "self", ",", "action_uuid", ",", "wait", "=", "None", ")", ":", "action_facade", "=", "client", ".", "ActionFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "entity", "=", "[", "{", ...
Get the results of an action by ID. :param str action_uuid: Id of the action :param int wait: Time in seconds to wait for action to complete. :return dict: Output from action :raises: :class:`JujuError` if invalid action_uuid
[ "Get", "the", "results", "of", "an", "action", "by", "ID", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1699-L1732
26,654
juju/python-libjuju
juju/model.py
Model.get_action_status
async def get_action_status(self, uuid_or_prefix=None, name=None): """Get the status of all actions, filtered by ID, ID prefix, or name. :param str uuid_or_prefix: Filter by action uuid or prefix :param str name: Filter by action name """ results = {} action_results = [] action_facade = client.ActionFacade.from_connection( self.connection() ) if name: name_results = await action_facade.FindActionsByNames([name]) action_results.extend(name_results.actions[0].actions) if uuid_or_prefix: # Collect list of actions matching uuid or prefix matching_actions = await action_facade.FindActionTagsByPrefix( [uuid_or_prefix]) entities = [] for actions in matching_actions.matches.values(): entities = [{'tag': a.tag} for a in actions] # Get action results matching action tags uuid_results = await action_facade.Actions(entities) action_results.extend(uuid_results.results) for a in action_results: results[tag.untag('action-', a.action.tag)] = a.status return results
python
async def get_action_status(self, uuid_or_prefix=None, name=None): results = {} action_results = [] action_facade = client.ActionFacade.from_connection( self.connection() ) if name: name_results = await action_facade.FindActionsByNames([name]) action_results.extend(name_results.actions[0].actions) if uuid_or_prefix: # Collect list of actions matching uuid or prefix matching_actions = await action_facade.FindActionTagsByPrefix( [uuid_or_prefix]) entities = [] for actions in matching_actions.matches.values(): entities = [{'tag': a.tag} for a in actions] # Get action results matching action tags uuid_results = await action_facade.Actions(entities) action_results.extend(uuid_results.results) for a in action_results: results[tag.untag('action-', a.action.tag)] = a.status return results
[ "async", "def", "get_action_status", "(", "self", ",", "uuid_or_prefix", "=", "None", ",", "name", "=", "None", ")", ":", "results", "=", "{", "}", "action_results", "=", "[", "]", "action_facade", "=", "client", ".", "ActionFacade", ".", "from_connection", ...
Get the status of all actions, filtered by ID, ID prefix, or name. :param str uuid_or_prefix: Filter by action uuid or prefix :param str name: Filter by action name
[ "Get", "the", "status", "of", "all", "actions", "filtered", "by", "ID", "ID", "prefix", "or", "name", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1734-L1761
26,655
juju/python-libjuju
juju/model.py
Model.get_status
async def get_status(self, filters=None, utc=False): """Return the status of the model. :param str filters: Optional list of applications, units, or machines to include, which can use wildcards ('*'). :param bool utc: Display time as UTC in RFC3339 format """ client_facade = client.ClientFacade.from_connection(self.connection()) return await client_facade.FullStatus(filters)
python
async def get_status(self, filters=None, utc=False): client_facade = client.ClientFacade.from_connection(self.connection()) return await client_facade.FullStatus(filters)
[ "async", "def", "get_status", "(", "self", ",", "filters", "=", "None", ",", "utc", "=", "False", ")", ":", "client_facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "return", "await", "cl...
Return the status of the model. :param str filters: Optional list of applications, units, or machines to include, which can use wildcards ('*'). :param bool utc: Display time as UTC in RFC3339 format
[ "Return", "the", "status", "of", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1771-L1780
26,656
juju/python-libjuju
juju/model.py
Model.sync_tools
def sync_tools( self, all_=False, destination=None, dry_run=False, public=False, source=None, stream=None, version=None): """Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination directory :param bool dry_run: Don't do the actual copy :param bool public: Tools are for a public cloud, so generate mirrors information :param str source: Path to local source directory :param str stream: Simplestreams stream for which to sync metadata :param str version: Copy a specific major.minor version """ raise NotImplementedError()
python
def sync_tools( self, all_=False, destination=None, dry_run=False, public=False, source=None, stream=None, version=None): raise NotImplementedError()
[ "def", "sync_tools", "(", "self", ",", "all_", "=", "False", ",", "destination", "=", "None", ",", "dry_run", "=", "False", ",", "public", "=", "False", ",", "source", "=", "None", ",", "stream", "=", "None", ",", "version", "=", "None", ")", ":", ...
Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination directory :param bool dry_run: Don't do the actual copy :param bool public: Tools are for a public cloud, so generate mirrors information :param str source: Path to local source directory :param str stream: Simplestreams stream for which to sync metadata :param str version: Copy a specific major.minor version
[ "Copy", "Juju", "tools", "into", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1782-L1797
26,657
juju/python-libjuju
juju/model.py
Model.upgrade_juju
def upgrade_juju( self, dry_run=False, reset_previous_upgrade=False, upload_tools=False, version=None): """Upgrade Juju on all machines in a model. :param bool dry_run: Don't do the actual upgrade :param bool reset_previous_upgrade: Clear the previous (incomplete) upgrade status :param bool upload_tools: Upload local version of tools :param str version: Upgrade to a specific version """ raise NotImplementedError()
python
def upgrade_juju( self, dry_run=False, reset_previous_upgrade=False, upload_tools=False, version=None): raise NotImplementedError()
[ "def", "upgrade_juju", "(", "self", ",", "dry_run", "=", "False", ",", "reset_previous_upgrade", "=", "False", ",", "upload_tools", "=", "False", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", ")" ]
Upgrade Juju on all machines in a model. :param bool dry_run: Don't do the actual upgrade :param bool reset_previous_upgrade: Clear the previous (incomplete) upgrade status :param bool upload_tools: Upload local version of tools :param str version: Upgrade to a specific version
[ "Upgrade", "Juju", "on", "all", "machines", "in", "a", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1822-L1834
26,658
juju/python-libjuju
juju/model.py
Model.get_metrics
async def get_metrics(self, *tags): """Retrieve metrics. :param str *tags: Tags of entities from which to retrieve metrics. No tags retrieves the metrics of all units in the model. :return: Dictionary of unit_name:metrics """ log.debug("Retrieving metrics for %s", ', '.join(tags) if tags else "all units") metrics_facade = client.MetricsDebugFacade.from_connection( self.connection()) entities = [client.Entity(tag) for tag in tags] metrics_result = await metrics_facade.GetMetrics(entities) metrics = collections.defaultdict(list) for entity_metrics in metrics_result.results: error = entity_metrics.error if error: if "is not a valid tag" in error: raise ValueError(error.message) else: raise Exception(error.message) for metric in entity_metrics.metrics: metrics[metric.unit].append(vars(metric)) return metrics
python
async def get_metrics(self, *tags): log.debug("Retrieving metrics for %s", ', '.join(tags) if tags else "all units") metrics_facade = client.MetricsDebugFacade.from_connection( self.connection()) entities = [client.Entity(tag) for tag in tags] metrics_result = await metrics_facade.GetMetrics(entities) metrics = collections.defaultdict(list) for entity_metrics in metrics_result.results: error = entity_metrics.error if error: if "is not a valid tag" in error: raise ValueError(error.message) else: raise Exception(error.message) for metric in entity_metrics.metrics: metrics[metric.unit].append(vars(metric)) return metrics
[ "async", "def", "get_metrics", "(", "self", ",", "*", "tags", ")", ":", "log", ".", "debug", "(", "\"Retrieving metrics for %s\"", ",", "', '", ".", "join", "(", "tags", ")", "if", "tags", "else", "\"all units\"", ")", "metrics_facade", "=", "client", ".",...
Retrieve metrics. :param str *tags: Tags of entities from which to retrieve metrics. No tags retrieves the metrics of all units in the model. :return: Dictionary of unit_name:metrics
[ "Retrieve", "metrics", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1848-L1878
26,659
juju/python-libjuju
juju/model.py
BundleHandler.scale
async def scale(self, application, scale): """ Handle a change of scale to a k8s application. :param string application: Application holds the application placeholder name for which a unit is added. :param int scale: New scale value to use. """ application = self.resolve(application) return await self.model.applications[application].scale(scale=scale)
python
async def scale(self, application, scale): application = self.resolve(application) return await self.model.applications[application].scale(scale=scale)
[ "async", "def", "scale", "(", "self", ",", "application", ",", "scale", ")", ":", "application", "=", "self", ".", "resolve", "(", "application", ")", "return", "await", "self", ".", "model", ".", "applications", "[", "application", "]", ".", "scale", "(...
Handle a change of scale to a k8s application. :param string application: Application holds the application placeholder name for which a unit is added. :param int scale: New scale value to use.
[ "Handle", "a", "change", "of", "scale", "to", "a", "k8s", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L2194-L2206
26,660
juju/python-libjuju
juju/model.py
CharmArchiveGenerator.make_archive
def make_archive(self, path): """Create archive of directory and write to ``path``. :param path: Path to archive Ignored:: * build/* - This is used for packing the charm itself and any similar tasks. * */.* - Hidden files are all ignored for now. This will most likely be changed into a specific ignore list (.bzr, etc) """ zf = zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(self.path): relative_path = dirpath[len(self.path) + 1:] if relative_path and not self._ignore(relative_path): zf.write(dirpath, relative_path) for name in filenames: archive_name = os.path.join(relative_path, name) if not self._ignore(archive_name): real_path = os.path.join(dirpath, name) self._check_type(real_path) if os.path.islink(real_path): self._check_link(real_path) self._write_symlink( zf, os.readlink(real_path), archive_name) else: zf.write(real_path, archive_name) zf.close() return path
python
def make_archive(self, path): zf = zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(self.path): relative_path = dirpath[len(self.path) + 1:] if relative_path and not self._ignore(relative_path): zf.write(dirpath, relative_path) for name in filenames: archive_name = os.path.join(relative_path, name) if not self._ignore(archive_name): real_path = os.path.join(dirpath, name) self._check_type(real_path) if os.path.islink(real_path): self._check_link(real_path) self._write_symlink( zf, os.readlink(real_path), archive_name) else: zf.write(real_path, archive_name) zf.close() return path
[ "def", "make_archive", "(", "self", ",", "path", ")", ":", "zf", "=", "zipfile", ".", "ZipFile", "(", "path", ",", "'w'", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "se...
Create archive of directory and write to ``path``. :param path: Path to archive Ignored:: * build/* - This is used for packing the charm itself and any similar tasks. * */.* - Hidden files are all ignored for now. This will most likely be changed into a specific ignore list (.bzr, etc)
[ "Create", "archive", "of", "directory", "and", "write", "to", "path", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L2281-L2312
26,661
juju/python-libjuju
juju/model.py
CharmArchiveGenerator._check_type
def _check_type(self, path): """Check the path """ s = os.stat(path) if stat.S_ISDIR(s.st_mode) or stat.S_ISREG(s.st_mode): return path raise ValueError("Invalid Charm at % %s" % ( path, "Invalid file type for a charm"))
python
def _check_type(self, path): s = os.stat(path) if stat.S_ISDIR(s.st_mode) or stat.S_ISREG(s.st_mode): return path raise ValueError("Invalid Charm at % %s" % ( path, "Invalid file type for a charm"))
[ "def", "_check_type", "(", "self", ",", "path", ")", ":", "s", "=", "os", ".", "stat", "(", "path", ")", "if", "stat", ".", "S_ISDIR", "(", "s", ".", "st_mode", ")", "or", "stat", ".", "S_ISREG", "(", "s", ".", "st_mode", ")", ":", "return", "p...
Check the path
[ "Check", "the", "path" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L2314-L2321
26,662
juju/python-libjuju
juju/model.py
CharmArchiveGenerator._write_symlink
def _write_symlink(self, zf, link_target, link_path): """Package symlinks with appropriate zipfile metadata.""" info = zipfile.ZipInfo() info.filename = link_path info.create_system = 3 # Magic code for symlinks / py2/3 compat # 27166663808 = (stat.S_IFLNK | 0755) << 16 info.external_attr = 2716663808 zf.writestr(info, link_target)
python
def _write_symlink(self, zf, link_target, link_path): info = zipfile.ZipInfo() info.filename = link_path info.create_system = 3 # Magic code for symlinks / py2/3 compat # 27166663808 = (stat.S_IFLNK | 0755) << 16 info.external_attr = 2716663808 zf.writestr(info, link_target)
[ "def", "_write_symlink", "(", "self", ",", "zf", ",", "link_target", ",", "link_path", ")", ":", "info", "=", "zipfile", ".", "ZipInfo", "(", ")", "info", ".", "filename", "=", "link_path", "info", ".", "create_system", "=", "3", "# Magic code for symlinks /...
Package symlinks with appropriate zipfile metadata.
[ "Package", "symlinks", "with", "appropriate", "zipfile", "metadata", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L2336-L2344
26,663
juju/python-libjuju
juju/user.py
User.set_password
async def set_password(self, password): """Update this user's password. """ await self.controller.change_user_password(self.username, password) self._user_info.password = password
python
async def set_password(self, password): await self.controller.change_user_password(self.username, password) self._user_info.password = password
[ "async", "def", "set_password", "(", "self", ",", "password", ")", ":", "await", "self", ".", "controller", ".", "change_user_password", "(", "self", ".", "username", ",", "password", ")", "self", ".", "_user_info", ".", "password", "=", "password" ]
Update this user's password.
[ "Update", "this", "user", "s", "password", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/user.py#L56-L60
26,664
juju/python-libjuju
juju/user.py
User.grant
async def grant(self, acl='login'): """Set access level of this user on the controller. :param str acl: Access control ('login', 'add-model', or 'superuser') """ if await self.controller.grant(self.username, acl): self._user_info.access = acl
python
async def grant(self, acl='login'): if await self.controller.grant(self.username, acl): self._user_info.access = acl
[ "async", "def", "grant", "(", "self", ",", "acl", "=", "'login'", ")", ":", "if", "await", "self", ".", "controller", ".", "grant", "(", "self", ".", "username", ",", "acl", ")", ":", "self", ".", "_user_info", ".", "access", "=", "acl" ]
Set access level of this user on the controller. :param str acl: Access control ('login', 'add-model', or 'superuser')
[ "Set", "access", "level", "of", "this", "user", "on", "the", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/user.py#L62-L68
26,665
juju/python-libjuju
juju/user.py
User.revoke
async def revoke(self): """Removes all access rights for this user from the controller. """ await self.controller.revoke(self.username) self._user_info.access = ''
python
async def revoke(self): await self.controller.revoke(self.username) self._user_info.access = ''
[ "async", "def", "revoke", "(", "self", ")", ":", "await", "self", ".", "controller", ".", "revoke", "(", "self", ".", "username", ")", "self", ".", "_user_info", ".", "access", "=", "''" ]
Removes all access rights for this user from the controller.
[ "Removes", "all", "access", "rights", "for", "this", "user", "from", "the", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/user.py#L70-L74
26,666
juju/python-libjuju
juju/user.py
User.disable
async def disable(self): """Disable this user. """ await self.controller.disable_user(self.username) self._user_info.disabled = True
python
async def disable(self): await self.controller.disable_user(self.username) self._user_info.disabled = True
[ "async", "def", "disable", "(", "self", ")", ":", "await", "self", ".", "controller", ".", "disable_user", "(", "self", ".", "username", ")", "self", ".", "_user_info", ".", "disabled", "=", "True" ]
Disable this user.
[ "Disable", "this", "user", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/user.py#L76-L80
26,667
juju/python-libjuju
juju/user.py
User.enable
async def enable(self): """Re-enable this user. """ await self.controller.enable_user(self.username) self._user_info.disabled = False
python
async def enable(self): await self.controller.enable_user(self.username) self._user_info.disabled = False
[ "async", "def", "enable", "(", "self", ")", ":", "await", "self", ".", "controller", ".", "enable_user", "(", "self", ".", "username", ")", "self", ".", "_user_info", ".", "disabled", "=", "False" ]
Re-enable this user.
[ "Re", "-", "enable", "this", "user", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/user.py#L82-L86
26,668
juju/python-libjuju
juju/machine.py
Machine.destroy
async def destroy(self, force=False): """Remove this machine from the model. Blocks until the machine is actually removed. """ facade = client.ClientFacade.from_connection(self.connection) log.debug( 'Destroying machine %s', self.id) await facade.DestroyMachines(force, [self.id]) return await self.model._wait( 'machine', self.id, 'remove')
python
async def destroy(self, force=False): facade = client.ClientFacade.from_connection(self.connection) log.debug( 'Destroying machine %s', self.id) await facade.DestroyMachines(force, [self.id]) return await self.model._wait( 'machine', self.id, 'remove')
[ "async", "def", "destroy", "(", "self", ",", "force", "=", "False", ")", ":", "facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Destroying machine %s'", ",", "self", ".", ...
Remove this machine from the model. Blocks until the machine is actually removed.
[ "Remove", "this", "machine", "from", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/machine.py#L99-L112
26,669
juju/python-libjuju
juju/machine.py
Machine.scp_to
async def scp_to(self, source, destination, user='ubuntu', proxy=False, scp_opts=''): """Transfer files to this machine. :param str source: Local path of file(s) to transfer :param str destination: Remote destination of transferred files :param str user: Remote username :param bool proxy: Proxy through the Juju API server :param scp_opts: Additional options to the `scp` command :type scp_opts: str or list """ if proxy: raise NotImplementedError('proxy option is not implemented') address = self.dns_name destination = '%s@%s:%s' % (user, address, destination) await self._scp(source, destination, scp_opts)
python
async def scp_to(self, source, destination, user='ubuntu', proxy=False, scp_opts=''): if proxy: raise NotImplementedError('proxy option is not implemented') address = self.dns_name destination = '%s@%s:%s' % (user, address, destination) await self._scp(source, destination, scp_opts)
[ "async", "def", "scp_to", "(", "self", ",", "source", ",", "destination", ",", "user", "=", "'ubuntu'", ",", "proxy", "=", "False", ",", "scp_opts", "=", "''", ")", ":", "if", "proxy", ":", "raise", "NotImplementedError", "(", "'proxy option is not implement...
Transfer files to this machine. :param str source: Local path of file(s) to transfer :param str destination: Remote destination of transferred files :param str user: Remote username :param bool proxy: Proxy through the Juju API server :param scp_opts: Additional options to the `scp` command :type scp_opts: str or list
[ "Transfer", "files", "to", "this", "machine", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/machine.py#L140-L156
26,670
juju/python-libjuju
juju/machine.py
Machine._scp
async def _scp(self, source, destination, scp_opts): """ Execute an scp command. Requires a fully qualified source and destination. """ cmd = [ 'scp', '-i', os.path.expanduser('~/.local/share/juju/ssh/juju_id_rsa'), '-o', 'StrictHostKeyChecking=no', '-q', '-B' ] cmd.extend(scp_opts.split() if isinstance(scp_opts, str) else scp_opts) cmd.extend([source, destination]) loop = self.model.loop process = await asyncio.create_subprocess_exec(*cmd, loop=loop) await process.wait() if process.returncode != 0: raise JujuError("command failed: %s" % cmd)
python
async def _scp(self, source, destination, scp_opts): cmd = [ 'scp', '-i', os.path.expanduser('~/.local/share/juju/ssh/juju_id_rsa'), '-o', 'StrictHostKeyChecking=no', '-q', '-B' ] cmd.extend(scp_opts.split() if isinstance(scp_opts, str) else scp_opts) cmd.extend([source, destination]) loop = self.model.loop process = await asyncio.create_subprocess_exec(*cmd, loop=loop) await process.wait() if process.returncode != 0: raise JujuError("command failed: %s" % cmd)
[ "async", "def", "_scp", "(", "self", ",", "source", ",", "destination", ",", "scp_opts", ")", ":", "cmd", "=", "[", "'scp'", ",", "'-i'", ",", "os", ".", "path", ".", "expanduser", "(", "'~/.local/share/juju/ssh/juju_id_rsa'", ")", ",", "'-o'", ",", "'St...
Execute an scp command. Requires a fully qualified source and destination.
[ "Execute", "an", "scp", "command", ".", "Requires", "a", "fully", "qualified", "source", "and", "destination", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/machine.py#L176-L193
26,671
juju/python-libjuju
juju/machine.py
Machine.agent_version
def agent_version(self): """Get the version of the Juju machine agent. May return None if the agent is not yet available. """ version = self.safe_data['agent-status']['version'] if version: return client.Number.from_json(version) else: return None
python
def agent_version(self): version = self.safe_data['agent-status']['version'] if version: return client.Number.from_json(version) else: return None
[ "def", "agent_version", "(", "self", ")", ":", "version", "=", "self", ".", "safe_data", "[", "'agent-status'", "]", "[", "'version'", "]", "if", "version", ":", "return", "client", ".", "Number", ".", "from_json", "(", "version", ")", "else", ":", "retu...
Get the version of the Juju machine agent. May return None if the agent is not yet available.
[ "Get", "the", "version", "of", "the", "Juju", "machine", "agent", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/machine.py#L231-L240
26,672
juju/python-libjuju
juju/machine.py
Machine.dns_name
def dns_name(self): """Get the DNS name for this machine. This is a best guess based on the addresses available in current data. May return None if no suitable address is found. """ for scope in ['public', 'local-cloud']: addresses = self.safe_data['addresses'] or [] addresses = [address for address in addresses if address['scope'] == scope] if addresses: return addresses[0]['value'] return None
python
def dns_name(self): for scope in ['public', 'local-cloud']: addresses = self.safe_data['addresses'] or [] addresses = [address for address in addresses if address['scope'] == scope] if addresses: return addresses[0]['value'] return None
[ "def", "dns_name", "(", "self", ")", ":", "for", "scope", "in", "[", "'public'", ",", "'local-cloud'", "]", ":", "addresses", "=", "self", ".", "safe_data", "[", "'addresses'", "]", "or", "[", "]", "addresses", "=", "[", "address", "for", "address", "i...
Get the DNS name for this machine. This is a best guess based on the addresses available in current data. May return None if no suitable address is found.
[ "Get", "the", "DNS", "name", "for", "this", "machine", ".", "This", "is", "a", "best", "guess", "based", "on", "the", "addresses", "available", "in", "current", "data", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/machine.py#L264-L276
26,673
juju/python-libjuju
juju/client/_client.py
TypeFactory.from_connection
def from_connection(cls, connection): """ Given a connected Connection object, return an initialized and connected instance of an API Interface matching the name of this class. @param connection: initialized Connection object. """ facade_name = cls.__name__ if not facade_name.endswith('Facade'): raise TypeError('Unexpected class name: {}'.format(facade_name)) facade_name = facade_name[:-len('Facade')] version = connection.facades.get(facade_name) if version is None: raise Exception('No facade {} in facades {}'.format(facade_name, connection.facades)) c = lookup_facade(cls.__name__, version) c = c() c.connect(connection) return c
python
def from_connection(cls, connection): facade_name = cls.__name__ if not facade_name.endswith('Facade'): raise TypeError('Unexpected class name: {}'.format(facade_name)) facade_name = facade_name[:-len('Facade')] version = connection.facades.get(facade_name) if version is None: raise Exception('No facade {} in facades {}'.format(facade_name, connection.facades)) c = lookup_facade(cls.__name__, version) c = c() c.connect(connection) return c
[ "def", "from_connection", "(", "cls", ",", "connection", ")", ":", "facade_name", "=", "cls", ".", "__name__", "if", "not", "facade_name", ".", "endswith", "(", "'Facade'", ")", ":", "raise", "TypeError", "(", "'Unexpected class name: {}'", ".", "format", "(",...
Given a connected Connection object, return an initialized and connected instance of an API Interface matching the name of this class. @param connection: initialized Connection object.
[ "Given", "a", "connected", "Connection", "object", "return", "an", "initialized", "and", "connected", "instance", "of", "an", "API", "Interface", "matching", "the", "name", "of", "this", "class", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client.py#L42-L64
26,674
juju/python-libjuju
juju/utils.py
execute_process
async def execute_process(*cmd, log=None, loop=None): ''' Wrapper around asyncio.create_subprocess_exec. ''' p = await asyncio.create_subprocess_exec( *cmd, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, loop=loop) stdout, stderr = await p.communicate() if log: log.debug("Exec %s -> %d", cmd, p.returncode) if stdout: log.debug(stdout.decode('utf-8')) if stderr: log.debug(stderr.decode('utf-8')) return p.returncode == 0
python
async def execute_process(*cmd, log=None, loop=None): ''' Wrapper around asyncio.create_subprocess_exec. ''' p = await asyncio.create_subprocess_exec( *cmd, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, loop=loop) stdout, stderr = await p.communicate() if log: log.debug("Exec %s -> %d", cmd, p.returncode) if stdout: log.debug(stdout.decode('utf-8')) if stderr: log.debug(stderr.decode('utf-8')) return p.returncode == 0
[ "async", "def", "execute_process", "(", "*", "cmd", ",", "log", "=", "None", ",", "loop", "=", "None", ")", ":", "p", "=", "await", "asyncio", ".", "create_subprocess_exec", "(", "*", "cmd", ",", "stdin", "=", "asyncio", ".", "subprocess", ".", "PIPE",...
Wrapper around asyncio.create_subprocess_exec.
[ "Wrapper", "around", "asyncio", ".", "create_subprocess_exec", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/utils.py#L11-L29
26,675
juju/python-libjuju
juju/utils.py
_read_ssh_key
def _read_ssh_key(): ''' Inner function for read_ssh_key, suitable for passing to our Executor. ''' default_data_dir = Path(Path.home(), ".local", "share", "juju") juju_data = os.environ.get("JUJU_DATA", default_data_dir) ssh_key_path = Path(juju_data, 'ssh', 'juju_id_rsa.pub') with ssh_key_path.open('r') as ssh_key_file: ssh_key = ssh_key_file.readlines()[0].strip() return ssh_key
python
def _read_ssh_key(): ''' Inner function for read_ssh_key, suitable for passing to our Executor. ''' default_data_dir = Path(Path.home(), ".local", "share", "juju") juju_data = os.environ.get("JUJU_DATA", default_data_dir) ssh_key_path = Path(juju_data, 'ssh', 'juju_id_rsa.pub') with ssh_key_path.open('r') as ssh_key_file: ssh_key = ssh_key_file.readlines()[0].strip() return ssh_key
[ "def", "_read_ssh_key", "(", ")", ":", "default_data_dir", "=", "Path", "(", "Path", ".", "home", "(", ")", ",", "\".local\"", ",", "\"share\"", ",", "\"juju\"", ")", "juju_data", "=", "os", ".", "environ", ".", "get", "(", "\"JUJU_DATA\"", ",", "default...
Inner function for read_ssh_key, suitable for passing to our Executor.
[ "Inner", "function", "for", "read_ssh_key", "suitable", "for", "passing", "to", "our", "Executor", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/utils.py#L32-L43
26,676
juju/python-libjuju
juju/utils.py
run_with_interrupt
async def run_with_interrupt(task, *events, loop=None): """ Awaits a task while allowing it to be interrupted by one or more `asyncio.Event`s. If the task finishes without the events becoming set, the results of the task will be returned. If the event become set, the task will be cancelled ``None`` will be returned. :param task: Task to run :param events: One or more `asyncio.Event`s which, if set, will interrupt `task` and cause it to be cancelled. :param loop: Optional event loop to use other than the default. """ loop = loop or asyncio.get_event_loop() task = asyncio.ensure_future(task, loop=loop) event_tasks = [loop.create_task(event.wait()) for event in events] done, pending = await asyncio.wait([task] + event_tasks, loop=loop, return_when=asyncio.FIRST_COMPLETED) for f in pending: f.cancel() # cancel unfinished tasks for f in done: f.exception() # prevent "exception was not retrieved" errors if task in done: return task.result() # may raise exception else: return None
python
async def run_with_interrupt(task, *events, loop=None): loop = loop or asyncio.get_event_loop() task = asyncio.ensure_future(task, loop=loop) event_tasks = [loop.create_task(event.wait()) for event in events] done, pending = await asyncio.wait([task] + event_tasks, loop=loop, return_when=asyncio.FIRST_COMPLETED) for f in pending: f.cancel() # cancel unfinished tasks for f in done: f.exception() # prevent "exception was not retrieved" errors if task in done: return task.result() # may raise exception else: return None
[ "async", "def", "run_with_interrupt", "(", "task", ",", "*", "events", ",", "loop", "=", "None", ")", ":", "loop", "=", "loop", "or", "asyncio", ".", "get_event_loop", "(", ")", "task", "=", "asyncio", ".", "ensure_future", "(", "task", ",", "loop", "=...
Awaits a task while allowing it to be interrupted by one or more `asyncio.Event`s. If the task finishes without the events becoming set, the results of the task will be returned. If the event become set, the task will be cancelled ``None`` will be returned. :param task: Task to run :param events: One or more `asyncio.Event`s which, if set, will interrupt `task` and cause it to be cancelled. :param loop: Optional event loop to use other than the default.
[ "Awaits", "a", "task", "while", "allowing", "it", "to", "be", "interrupted", "by", "one", "or", "more", "asyncio", ".", "Event", "s", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/utils.py#L88-L115
26,677
juju/python-libjuju
juju/client/gocookies.py
go_to_py_cookie
def go_to_py_cookie(go_cookie): '''Convert a Go-style JSON-unmarshaled cookie into a Python cookie''' expires = None if go_cookie.get('Expires') is not None: t = pyrfc3339.parse(go_cookie['Expires']) expires = t.timestamp() return cookiejar.Cookie( version=0, name=go_cookie['Name'], value=go_cookie['Value'], port=None, port_specified=False, # Unfortunately Python cookies don't record the original # host that the cookie came from, so we'll just use Domain # for that purpose, and record that the domain was specified, # even though it probably was not. This means that # we won't correctly record the CanonicalHost entry # when writing the cookie file after reading it. domain=go_cookie['Domain'], domain_specified=not go_cookie['HostOnly'], domain_initial_dot=False, path=go_cookie['Path'], path_specified=True, secure=go_cookie['Secure'], expires=expires, discard=False, comment=None, comment_url=None, rest=None, rfc2109=False, )
python
def go_to_py_cookie(go_cookie): '''Convert a Go-style JSON-unmarshaled cookie into a Python cookie''' expires = None if go_cookie.get('Expires') is not None: t = pyrfc3339.parse(go_cookie['Expires']) expires = t.timestamp() return cookiejar.Cookie( version=0, name=go_cookie['Name'], value=go_cookie['Value'], port=None, port_specified=False, # Unfortunately Python cookies don't record the original # host that the cookie came from, so we'll just use Domain # for that purpose, and record that the domain was specified, # even though it probably was not. This means that # we won't correctly record the CanonicalHost entry # when writing the cookie file after reading it. domain=go_cookie['Domain'], domain_specified=not go_cookie['HostOnly'], domain_initial_dot=False, path=go_cookie['Path'], path_specified=True, secure=go_cookie['Secure'], expires=expires, discard=False, comment=None, comment_url=None, rest=None, rfc2109=False, )
[ "def", "go_to_py_cookie", "(", "go_cookie", ")", ":", "expires", "=", "None", "if", "go_cookie", ".", "get", "(", "'Expires'", ")", "is", "not", "None", ":", "t", "=", "pyrfc3339", ".", "parse", "(", "go_cookie", "[", "'Expires'", "]", ")", "expires", ...
Convert a Go-style JSON-unmarshaled cookie into a Python cookie
[ "Convert", "a", "Go", "-", "style", "JSON", "-", "unmarshaled", "cookie", "into", "a", "Python", "cookie" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/gocookies.py#L45-L75
26,678
juju/python-libjuju
juju/client/gocookies.py
py_to_go_cookie
def py_to_go_cookie(py_cookie): '''Convert a python cookie to the JSON-marshalable Go-style cookie form.''' # TODO (perhaps): # HttpOnly # Creation # LastAccess # Updated # not done properly: CanonicalHost. go_cookie = { 'Name': py_cookie.name, 'Value': py_cookie.value, 'Domain': py_cookie.domain, 'HostOnly': not py_cookie.domain_specified, 'Persistent': not py_cookie.discard, 'Secure': py_cookie.secure, 'CanonicalHost': py_cookie.domain, } if py_cookie.path_specified: go_cookie['Path'] = py_cookie.path if py_cookie.expires is not None: unix_time = datetime.datetime.fromtimestamp(py_cookie.expires) # Note: fromtimestamp bizarrely produces a time without # a time zone, so we need to use accept_naive. go_cookie['Expires'] = pyrfc3339.generate(unix_time, accept_naive=True) return go_cookie
python
def py_to_go_cookie(py_cookie): '''Convert a python cookie to the JSON-marshalable Go-style cookie form.''' # TODO (perhaps): # HttpOnly # Creation # LastAccess # Updated # not done properly: CanonicalHost. go_cookie = { 'Name': py_cookie.name, 'Value': py_cookie.value, 'Domain': py_cookie.domain, 'HostOnly': not py_cookie.domain_specified, 'Persistent': not py_cookie.discard, 'Secure': py_cookie.secure, 'CanonicalHost': py_cookie.domain, } if py_cookie.path_specified: go_cookie['Path'] = py_cookie.path if py_cookie.expires is not None: unix_time = datetime.datetime.fromtimestamp(py_cookie.expires) # Note: fromtimestamp bizarrely produces a time without # a time zone, so we need to use accept_naive. go_cookie['Expires'] = pyrfc3339.generate(unix_time, accept_naive=True) return go_cookie
[ "def", "py_to_go_cookie", "(", "py_cookie", ")", ":", "# TODO (perhaps):", "# HttpOnly", "# Creation", "# LastAccess", "# Updated", "# not done properly: CanonicalHost.", "go_cookie", "=", "{", "'Name'", ":", "py_cookie", ".", "name", ",", "'Value'", ":", "py_co...
Convert a python cookie to the JSON-marshalable Go-style cookie form.
[ "Convert", "a", "python", "cookie", "to", "the", "JSON", "-", "marshalable", "Go", "-", "style", "cookie", "form", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/gocookies.py#L78-L102
26,679
juju/python-libjuju
juju/client/gocookies.py
GoCookieJar._really_load
def _really_load(self, f, filename, ignore_discard, ignore_expires): '''Implement the _really_load method called by FileCookieJar to implement the actual cookie loading''' data = json.load(f) or [] now = time.time() for cookie in map(go_to_py_cookie, data): if not ignore_expires and cookie.is_expired(now): continue self.set_cookie(cookie)
python
def _really_load(self, f, filename, ignore_discard, ignore_expires): '''Implement the _really_load method called by FileCookieJar to implement the actual cookie loading''' data = json.load(f) or [] now = time.time() for cookie in map(go_to_py_cookie, data): if not ignore_expires and cookie.is_expired(now): continue self.set_cookie(cookie)
[ "def", "_really_load", "(", "self", ",", "f", ",", "filename", ",", "ignore_discard", ",", "ignore_expires", ")", ":", "data", "=", "json", ".", "load", "(", "f", ")", "or", "[", "]", "now", "=", "time", ".", "time", "(", ")", "for", "cookie", "in"...
Implement the _really_load method called by FileCookieJar to implement the actual cookie loading
[ "Implement", "the", "_really_load", "method", "called", "by", "FileCookieJar", "to", "implement", "the", "actual", "cookie", "loading" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/gocookies.py#L13-L21
26,680
juju/python-libjuju
juju/client/gocookies.py
GoCookieJar.save
def save(self, filename=None, ignore_discard=False, ignore_expires=False): '''Implement the FileCookieJar abstract method.''' if filename is None: if self.filename is not None: filename = self.filename else: raise ValueError(cookiejar.MISSING_FILENAME_TEXT) # TODO: obtain file lock, read contents of file, and merge with # current content. go_cookies = [] now = time.time() for cookie in self: if not ignore_discard and cookie.discard: continue if not ignore_expires and cookie.is_expired(now): continue go_cookies.append(py_to_go_cookie(cookie)) with open(filename, "w") as f: f.write(json.dumps(go_cookies))
python
def save(self, filename=None, ignore_discard=False, ignore_expires=False): '''Implement the FileCookieJar abstract method.''' if filename is None: if self.filename is not None: filename = self.filename else: raise ValueError(cookiejar.MISSING_FILENAME_TEXT) # TODO: obtain file lock, read contents of file, and merge with # current content. go_cookies = [] now = time.time() for cookie in self: if not ignore_discard and cookie.discard: continue if not ignore_expires and cookie.is_expired(now): continue go_cookies.append(py_to_go_cookie(cookie)) with open(filename, "w") as f: f.write(json.dumps(go_cookies))
[ "def", "save", "(", "self", ",", "filename", "=", "None", ",", "ignore_discard", "=", "False", ",", "ignore_expires", "=", "False", ")", ":", "if", "filename", "is", "None", ":", "if", "self", ".", "filename", "is", "not", "None", ":", "filename", "=",...
Implement the FileCookieJar abstract method.
[ "Implement", "the", "FileCookieJar", "abstract", "method", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/gocookies.py#L23-L42
26,681
juju/python-libjuju
juju/controller.py
Controller.connect
async def connect(self, *args, **kwargs): """Connect to a Juju controller. This supports two calling conventions: The controller and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``controller_name`` is specified, or if the ``endpoint`` is not. Otherwise, both the ``endpoint`` and authentication information (``username`` and ``password``, or ``bakery_client`` and/or ``macaroons``) are required. If a single positional argument is given, it will be assumed to be the ``controller_name``. Otherwise, the first positional argument, if any, must be the ``endpoint``. Available parameters are: :param str controller_name: Name of controller registered with the Juju CLI. :param str endpoint: The hostname:port of the controller to connect to. :param str username: The username for controller-local users (or None to use macaroon-based login.) :param str password: The password for controller-local users. :param str cacert: The CA certificate of the controller (PEM formatted). :param httpbakery.Client bakery_client: The macaroon bakery client to to use when performing macaroon-based login. Macaroon tokens acquired when logging will be saved to bakery_client.cookies. If this is None, a default bakery_client will be used. :param list macaroons: List of macaroons to load into the ``bakery_client``. :param asyncio.BaseEventLoop loop: The event loop to use for async operations. :param int max_frame_size: The maximum websocket frame size to allow. """ await self.disconnect() if 'endpoint' not in kwargs and len(args) < 2: if args and 'model_name' in kwargs: raise TypeError('connect() got multiple values for ' 'controller_name') elif args: controller_name = args[0] else: controller_name = kwargs.pop('controller_name', None) await self._connector.connect_controller(controller_name, **kwargs) else: if 'controller_name' in kwargs: raise TypeError('connect() got values for both ' 'controller_name and endpoint') if args and 'endpoint' in kwargs: raise TypeError('connect() got multiple values for endpoint') has_userpass = (len(args) >= 3 or {'username', 'password'}.issubset(kwargs)) has_macaroons = (len(args) >= 5 or not {'bakery_client', 'macaroons'}.isdisjoint(kwargs)) if not (has_userpass or has_macaroons): raise TypeError('connect() missing auth params') arg_names = [ 'endpoint', 'username', 'password', 'cacert', 'bakery_client', 'macaroons', 'loop', 'max_frame_size', ] for i, arg in enumerate(args): kwargs[arg_names[i]] = arg if 'endpoint' not in kwargs: raise ValueError('endpoint is required ' 'if controller_name not given') if not ({'username', 'password'}.issubset(kwargs) or {'bakery_client', 'macaroons'}.intersection(kwargs)): raise ValueError('Authentication parameters are required ' 'if controller_name not given') await self._connector.connect(**kwargs)
python
async def connect(self, *args, **kwargs): await self.disconnect() if 'endpoint' not in kwargs and len(args) < 2: if args and 'model_name' in kwargs: raise TypeError('connect() got multiple values for ' 'controller_name') elif args: controller_name = args[0] else: controller_name = kwargs.pop('controller_name', None) await self._connector.connect_controller(controller_name, **kwargs) else: if 'controller_name' in kwargs: raise TypeError('connect() got values for both ' 'controller_name and endpoint') if args and 'endpoint' in kwargs: raise TypeError('connect() got multiple values for endpoint') has_userpass = (len(args) >= 3 or {'username', 'password'}.issubset(kwargs)) has_macaroons = (len(args) >= 5 or not {'bakery_client', 'macaroons'}.isdisjoint(kwargs)) if not (has_userpass or has_macaroons): raise TypeError('connect() missing auth params') arg_names = [ 'endpoint', 'username', 'password', 'cacert', 'bakery_client', 'macaroons', 'loop', 'max_frame_size', ] for i, arg in enumerate(args): kwargs[arg_names[i]] = arg if 'endpoint' not in kwargs: raise ValueError('endpoint is required ' 'if controller_name not given') if not ({'username', 'password'}.issubset(kwargs) or {'bakery_client', 'macaroons'}.intersection(kwargs)): raise ValueError('Authentication parameters are required ' 'if controller_name not given') await self._connector.connect(**kwargs)
[ "async", "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "disconnect", "(", ")", "if", "'endpoint'", "not", "in", "kwargs", "and", "len", "(", "args", ")", "<", "2", ":", "if", "args", "an...
Connect to a Juju controller. This supports two calling conventions: The controller and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``controller_name`` is specified, or if the ``endpoint`` is not. Otherwise, both the ``endpoint`` and authentication information (``username`` and ``password``, or ``bakery_client`` and/or ``macaroons``) are required. If a single positional argument is given, it will be assumed to be the ``controller_name``. Otherwise, the first positional argument, if any, must be the ``endpoint``. Available parameters are: :param str controller_name: Name of controller registered with the Juju CLI. :param str endpoint: The hostname:port of the controller to connect to. :param str username: The username for controller-local users (or None to use macaroon-based login.) :param str password: The password for controller-local users. :param str cacert: The CA certificate of the controller (PEM formatted). :param httpbakery.Client bakery_client: The macaroon bakery client to to use when performing macaroon-based login. Macaroon tokens acquired when logging will be saved to bakery_client.cookies. If this is None, a default bakery_client will be used. :param list macaroons: List of macaroons to load into the ``bakery_client``. :param asyncio.BaseEventLoop loop: The event loop to use for async operations. :param int max_frame_size: The maximum websocket frame size to allow.
[ "Connect", "to", "a", "Juju", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L54-L133
26,682
juju/python-libjuju
juju/controller.py
Controller.add_credential
async def add_credential(self, name=None, credential=None, cloud=None, owner=None, force=False): """Add or update a credential to the controller. :param str name: Name of new credential. If None, the default local credential is used. Name must be provided if a credential is given. :param CloudCredential credential: Credential to add. If not given, it will attempt to read from local data, if available. :param str cloud: Name of cloud to associate the credential with. Defaults to the same cloud as the controller. :param str owner: Username that will own the credential. Defaults to the current user. :param bool force: Force indicates whether the update should be forced. It's only supported for facade v3 or later. Defaults to false. :returns: Name of credential that was uploaded. """ if not cloud: cloud = await self.get_cloud() if not owner: owner = self.connection().info['user-info']['identity'] if credential and not name: raise errors.JujuError('Name must be provided for credential') if not credential: name, credential = self._connector.jujudata.load_credential(cloud, name) if credential is None: raise errors.JujuError( 'Unable to find credential: {}'.format(name)) if credential.auth_type == 'jsonfile' and 'file' in credential.attrs: # file creds have to be loaded before being sent to the controller try: # it might already be JSON json.loads(credential.attrs['file']) except json.JSONDecodeError: # not valid JSON, so maybe it's a file cred_path = Path(credential.attrs['file']) if cred_path.exists(): # make a copy cred_json = credential.to_json() credential = client.CloudCredential.from_json(cred_json) # inline the cred credential.attrs['file'] = cred_path.read_text() log.debug('Uploading credential %s', name) cloud_facade = client.CloudFacade.from_connection(self.connection()) tagged_credentials = [ client.UpdateCloudCredential( tag=tag.credential(cloud, tag.untag('user-', owner), name), credential=credential, )] if cloud_facade.version >= 3: # UpdateCredentials was renamed to UpdateCredentialsCheckModels # in facade version 3. await cloud_facade.UpdateCredentialsCheckModels( credentials=tagged_credentials, force=force, ) else: await cloud_facade.UpdateCredentials(tagged_credentials) return name
python
async def add_credential(self, name=None, credential=None, cloud=None, owner=None, force=False): if not cloud: cloud = await self.get_cloud() if not owner: owner = self.connection().info['user-info']['identity'] if credential and not name: raise errors.JujuError('Name must be provided for credential') if not credential: name, credential = self._connector.jujudata.load_credential(cloud, name) if credential is None: raise errors.JujuError( 'Unable to find credential: {}'.format(name)) if credential.auth_type == 'jsonfile' and 'file' in credential.attrs: # file creds have to be loaded before being sent to the controller try: # it might already be JSON json.loads(credential.attrs['file']) except json.JSONDecodeError: # not valid JSON, so maybe it's a file cred_path = Path(credential.attrs['file']) if cred_path.exists(): # make a copy cred_json = credential.to_json() credential = client.CloudCredential.from_json(cred_json) # inline the cred credential.attrs['file'] = cred_path.read_text() log.debug('Uploading credential %s', name) cloud_facade = client.CloudFacade.from_connection(self.connection()) tagged_credentials = [ client.UpdateCloudCredential( tag=tag.credential(cloud, tag.untag('user-', owner), name), credential=credential, )] if cloud_facade.version >= 3: # UpdateCredentials was renamed to UpdateCredentialsCheckModels # in facade version 3. await cloud_facade.UpdateCredentialsCheckModels( credentials=tagged_credentials, force=force, ) else: await cloud_facade.UpdateCredentials(tagged_credentials) return name
[ "async", "def", "add_credential", "(", "self", ",", "name", "=", "None", ",", "credential", "=", "None", ",", "cloud", "=", "None", ",", "owner", "=", "None", ",", "force", "=", "False", ")", ":", "if", "not", "cloud", ":", "cloud", "=", "await", "...
Add or update a credential to the controller. :param str name: Name of new credential. If None, the default local credential is used. Name must be provided if a credential is given. :param CloudCredential credential: Credential to add. If not given, it will attempt to read from local data, if available. :param str cloud: Name of cloud to associate the credential with. Defaults to the same cloud as the controller. :param str owner: Username that will own the credential. Defaults to the current user. :param bool force: Force indicates whether the update should be forced. It's only supported for facade v3 or later. Defaults to false. :returns: Name of credential that was uploaded.
[ "Add", "or", "update", "a", "credential", "to", "the", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L172-L236
26,683
juju/python-libjuju
juju/controller.py
Controller.add_model
async def add_model( self, model_name, cloud_name=None, credential_name=None, owner=None, config=None, region=None): """Add a model to this controller. :param str model_name: Name to give the new model. :param str cloud_name: Name of the cloud in which to create the model, e.g. 'aws'. Defaults to same cloud as controller. :param str credential_name: Name of the credential to use when creating the model. If not given, it will attempt to find a default credential. :param str owner: Username that will own the model. Defaults to the current user. :param dict config: Model configuration. :param str region: Region in which to create the model. :return Model: A connection to the newly created model. """ model_facade = client.ModelManagerFacade.from_connection( self.connection()) owner = owner or self.connection().info['user-info']['identity'] cloud_name = cloud_name or await self.get_cloud() try: # attempt to add/update the credential from local data if available credential_name = await self.add_credential( name=credential_name, cloud=cloud_name, owner=owner) except errors.JujuError: # if it's not available locally, assume it's on the controller pass if credential_name: credential = tag.credential( cloud_name, tag.untag('user-', owner), credential_name ) else: credential = None log.debug('Creating model %s', model_name) if not config or 'authorized-keys' not in config: config = config or {} config['authorized-keys'] = await utils.read_ssh_key( loop=self._connector.loop) model_info = await model_facade.CreateModel( tag.cloud(cloud_name), config, credential, model_name, owner, region ) from juju.model import Model model = Model(jujudata=self._connector.jujudata) kwargs = self.connection().connect_params() kwargs['uuid'] = model_info.uuid await model._connect_direct(**kwargs) return model
python
async def add_model( self, model_name, cloud_name=None, credential_name=None, owner=None, config=None, region=None): model_facade = client.ModelManagerFacade.from_connection( self.connection()) owner = owner or self.connection().info['user-info']['identity'] cloud_name = cloud_name or await self.get_cloud() try: # attempt to add/update the credential from local data if available credential_name = await self.add_credential( name=credential_name, cloud=cloud_name, owner=owner) except errors.JujuError: # if it's not available locally, assume it's on the controller pass if credential_name: credential = tag.credential( cloud_name, tag.untag('user-', owner), credential_name ) else: credential = None log.debug('Creating model %s', model_name) if not config or 'authorized-keys' not in config: config = config or {} config['authorized-keys'] = await utils.read_ssh_key( loop=self._connector.loop) model_info = await model_facade.CreateModel( tag.cloud(cloud_name), config, credential, model_name, owner, region ) from juju.model import Model model = Model(jujudata=self._connector.jujudata) kwargs = self.connection().connect_params() kwargs['uuid'] = model_info.uuid await model._connect_direct(**kwargs) return model
[ "async", "def", "add_model", "(", "self", ",", "model_name", ",", "cloud_name", "=", "None", ",", "credential_name", "=", "None", ",", "owner", "=", "None", ",", "config", "=", "None", ",", "region", "=", "None", ")", ":", "model_facade", "=", "client", ...
Add a model to this controller. :param str model_name: Name to give the new model. :param str cloud_name: Name of the cloud in which to create the model, e.g. 'aws'. Defaults to same cloud as controller. :param str credential_name: Name of the credential to use when creating the model. If not given, it will attempt to find a default credential. :param str owner: Username that will own the model. Defaults to the current user. :param dict config: Model configuration. :param str region: Region in which to create the model. :return Model: A connection to the newly created model.
[ "Add", "a", "model", "to", "this", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L238-L301
26,684
juju/python-libjuju
juju/controller.py
Controller.destroy_models
async def destroy_models(self, *models, destroy_storage=False): """Destroy one or more models. :param str *models: Names or UUIDs of models to destroy :param bool destroy_storage: Whether or not to destroy storage when destroying the models. Defaults to false. """ uuids = await self.model_uuids() models = [uuids[model] if model in uuids else model for model in models] model_facade = client.ModelManagerFacade.from_connection( self.connection()) log.debug( 'Destroying model%s %s', '' if len(models) == 1 else 's', ', '.join(models) ) if model_facade.version >= 5: params = [ client.DestroyModelParams(model_tag=tag.model(model), destroy_storage=destroy_storage) for model in models] else: params = [client.Entity(tag.model(model)) for model in models] await model_facade.DestroyModels(params)
python
async def destroy_models(self, *models, destroy_storage=False): uuids = await self.model_uuids() models = [uuids[model] if model in uuids else model for model in models] model_facade = client.ModelManagerFacade.from_connection( self.connection()) log.debug( 'Destroying model%s %s', '' if len(models) == 1 else 's', ', '.join(models) ) if model_facade.version >= 5: params = [ client.DestroyModelParams(model_tag=tag.model(model), destroy_storage=destroy_storage) for model in models] else: params = [client.Entity(tag.model(model)) for model in models] await model_facade.DestroyModels(params)
[ "async", "def", "destroy_models", "(", "self", ",", "*", "models", ",", "destroy_storage", "=", "False", ")", ":", "uuids", "=", "await", "self", ".", "model_uuids", "(", ")", "models", "=", "[", "uuids", "[", "model", "]", "if", "model", "in", "uuids"...
Destroy one or more models. :param str *models: Names or UUIDs of models to destroy :param bool destroy_storage: Whether or not to destroy storage when destroying the models. Defaults to false.
[ "Destroy", "one", "or", "more", "models", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L303-L332
26,685
juju/python-libjuju
juju/controller.py
Controller.add_user
async def add_user(self, username, password=None, display_name=None): """Add a user to this controller. :param str username: Username :param str password: Password :param str display_name: Display name :returns: A :class:`~juju.user.User` instance """ if not display_name: display_name = username user_facade = client.UserManagerFacade.from_connection( self.connection()) users = [client.AddUser(display_name=display_name, username=username, password=password)] results = await user_facade.AddUser(users) secret_key = results.results[0].secret_key return await self.get_user(username, secret_key=secret_key)
python
async def add_user(self, username, password=None, display_name=None): if not display_name: display_name = username user_facade = client.UserManagerFacade.from_connection( self.connection()) users = [client.AddUser(display_name=display_name, username=username, password=password)] results = await user_facade.AddUser(users) secret_key = results.results[0].secret_key return await self.get_user(username, secret_key=secret_key)
[ "async", "def", "add_user", "(", "self", ",", "username", ",", "password", "=", "None", ",", "display_name", "=", "None", ")", ":", "if", "not", "display_name", ":", "display_name", "=", "username", "user_facade", "=", "client", ".", "UserManagerFacade", "."...
Add a user to this controller. :param str username: Username :param str password: Password :param str display_name: Display name :returns: A :class:`~juju.user.User` instance
[ "Add", "a", "user", "to", "this", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L335-L352
26,686
juju/python-libjuju
juju/controller.py
Controller.remove_user
async def remove_user(self, username): """Remove a user from this controller. """ client_facade = client.UserManagerFacade.from_connection( self.connection()) user = tag.user(username) await client_facade.RemoveUser([client.Entity(user)])
python
async def remove_user(self, username): client_facade = client.UserManagerFacade.from_connection( self.connection()) user = tag.user(username) await client_facade.RemoveUser([client.Entity(user)])
[ "async", "def", "remove_user", "(", "self", ",", "username", ")", ":", "client_facade", "=", "client", ".", "UserManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "user", "=", "tag", ".", "user", "(", "username", ")", ...
Remove a user from this controller.
[ "Remove", "a", "user", "from", "this", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L354-L360
26,687
juju/python-libjuju
juju/controller.py
Controller.change_user_password
async def change_user_password(self, username, password): """Change the password for a user in this controller. :param str username: Username :param str password: New password """ user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.EntityPassword(password, tag.user(username)) return await user_facade.SetPassword([entity])
python
async def change_user_password(self, username, password): user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.EntityPassword(password, tag.user(username)) return await user_facade.SetPassword([entity])
[ "async", "def", "change_user_password", "(", "self", ",", "username", ",", "password", ")", ":", "user_facade", "=", "client", ".", "UserManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "entity", "=", "client", ".", "Ent...
Change the password for a user in this controller. :param str username: Username :param str password: New password
[ "Change", "the", "password", "for", "a", "user", "in", "this", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L362-L372
26,688
juju/python-libjuju
juju/controller.py
Controller.reset_user_password
async def reset_user_password(self, username): """Reset user password. :param str username: Username :returns: A :class:`~juju.user.User` instance """ user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) results = await user_facade.ResetPassword([entity]) secret_key = results.results[0].secret_key return await self.get_user(username, secret_key=secret_key)
python
async def reset_user_password(self, username): user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) results = await user_facade.ResetPassword([entity]) secret_key = results.results[0].secret_key return await self.get_user(username, secret_key=secret_key)
[ "async", "def", "reset_user_password", "(", "self", ",", "username", ")", ":", "user_facade", "=", "client", ".", "UserManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "entity", "=", "client", ".", "Entity", "(", "tag", ...
Reset user password. :param str username: Username :returns: A :class:`~juju.user.User` instance
[ "Reset", "user", "password", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L374-L385
26,689
juju/python-libjuju
juju/controller.py
Controller.destroy
async def destroy(self, destroy_all_models=False): """Destroy this controller. :param bool destroy_all_models: Destroy all hosted models in the controller. """ controller_facade = client.ControllerFacade.from_connection( self.connection()) return await controller_facade.DestroyController(destroy_all_models)
python
async def destroy(self, destroy_all_models=False): controller_facade = client.ControllerFacade.from_connection( self.connection()) return await controller_facade.DestroyController(destroy_all_models)
[ "async", "def", "destroy", "(", "self", ",", "destroy_all_models", "=", "False", ")", ":", "controller_facade", "=", "client", ".", "ControllerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "return", "await", "controller_facade",...
Destroy this controller. :param bool destroy_all_models: Destroy all hosted models in the controller.
[ "Destroy", "this", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L387-L396
26,690
juju/python-libjuju
juju/controller.py
Controller.disable_user
async def disable_user(self, username): """Disable a user. :param str username: Username """ user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) return await user_facade.DisableUser([entity])
python
async def disable_user(self, username): user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) return await user_facade.DisableUser([entity])
[ "async", "def", "disable_user", "(", "self", ",", "username", ")", ":", "user_facade", "=", "client", ".", "UserManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "entity", "=", "client", ".", "Entity", "(", "tag", ".", ...
Disable a user. :param str username: Username
[ "Disable", "a", "user", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L398-L407
26,691
juju/python-libjuju
juju/controller.py
Controller.enable_user
async def enable_user(self, username): """Re-enable a previously disabled user. """ user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) return await user_facade.EnableUser([entity])
python
async def enable_user(self, username): user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) return await user_facade.EnableUser([entity])
[ "async", "def", "enable_user", "(", "self", ",", "username", ")", ":", "user_facade", "=", "client", ".", "UserManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "entity", "=", "client", ".", "Entity", "(", "tag", ".", ...
Re-enable a previously disabled user.
[ "Re", "-", "enable", "a", "previously", "disabled", "user", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L409-L416
26,692
juju/python-libjuju
juju/controller.py
Controller.get_cloud
async def get_cloud(self): """ Get the name of the cloud that this controller lives on. """ cloud_facade = client.CloudFacade.from_connection(self.connection()) result = await cloud_facade.Clouds() cloud = list(result.clouds.keys())[0] # only lives on one cloud return tag.untag('cloud-', cloud)
python
async def get_cloud(self): cloud_facade = client.CloudFacade.from_connection(self.connection()) result = await cloud_facade.Clouds() cloud = list(result.clouds.keys())[0] # only lives on one cloud return tag.untag('cloud-', cloud)
[ "async", "def", "get_cloud", "(", "self", ")", ":", "cloud_facade", "=", "client", ".", "CloudFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "result", "=", "await", "cloud_facade", ".", "Clouds", "(", ")", "cloud", "=", "...
Get the name of the cloud that this controller lives on.
[ "Get", "the", "name", "of", "the", "cloud", "that", "this", "controller", "lives", "on", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L425-L433
26,693
juju/python-libjuju
juju/controller.py
Controller.model_uuids
async def model_uuids(self): """Return a mapping of model names to UUIDs. """ controller_facade = client.ControllerFacade.from_connection( self.connection()) for attempt in (1, 2, 3): try: response = await controller_facade.AllModels() return {um.model.name: um.model.uuid for um in response.user_models} except errors.JujuAPIError as e: # retry concurrency error until resolved in Juju # see: https://bugs.launchpad.net/juju/+bug/1721786 if 'has been removed' not in e.message or attempt == 3: raise await asyncio.sleep(attempt, loop=self._connector.loop)
python
async def model_uuids(self): controller_facade = client.ControllerFacade.from_connection( self.connection()) for attempt in (1, 2, 3): try: response = await controller_facade.AllModels() return {um.model.name: um.model.uuid for um in response.user_models} except errors.JujuAPIError as e: # retry concurrency error until resolved in Juju # see: https://bugs.launchpad.net/juju/+bug/1721786 if 'has been removed' not in e.message or attempt == 3: raise await asyncio.sleep(attempt, loop=self._connector.loop)
[ "async", "def", "model_uuids", "(", "self", ")", ":", "controller_facade", "=", "client", ".", "ControllerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "for", "attempt", "in", "(", "1", ",", "2", ",", "3", ")", ":", "t...
Return a mapping of model names to UUIDs.
[ "Return", "a", "mapping", "of", "model", "names", "to", "UUIDs", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L451-L466
26,694
juju/python-libjuju
juju/controller.py
Controller.get_model
async def get_model(self, model): """Get a model by name or UUID. :param str model: Model name or UUID :returns Model: Connected Model instance. """ uuids = await self.model_uuids() if model in uuids: uuid = uuids[model] else: uuid = model from juju.model import Model model = Model() kwargs = self.connection().connect_params() kwargs['uuid'] = uuid await model._connect_direct(**kwargs) return model
python
async def get_model(self, model): uuids = await self.model_uuids() if model in uuids: uuid = uuids[model] else: uuid = model from juju.model import Model model = Model() kwargs = self.connection().connect_params() kwargs['uuid'] = uuid await model._connect_direct(**kwargs) return model
[ "async", "def", "get_model", "(", "self", ",", "model", ")", ":", "uuids", "=", "await", "self", ".", "model_uuids", "(", ")", "if", "model", "in", "uuids", ":", "uuid", "=", "uuids", "[", "model", "]", "else", ":", "uuid", "=", "model", "from", "j...
Get a model by name or UUID. :param str model: Model name or UUID :returns Model: Connected Model instance.
[ "Get", "a", "model", "by", "name", "or", "UUID", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L509-L526
26,695
juju/python-libjuju
juju/controller.py
Controller.get_user
async def get_user(self, username, secret_key=None): """Get a user by name. :param str username: Username :param str secret_key: Issued by juju when add or reset user password :returns: A :class:`~juju.user.User` instance """ client_facade = client.UserManagerFacade.from_connection( self.connection()) user = tag.user(username) args = [client.Entity(user)] try: response = await client_facade.UserInfo(args, True) except errors.JujuError as e: if 'permission denied' in e.errors: # apparently, trying to get info for a nonexistent user returns # a "permission denied" error rather than an empty result set return None raise if response.results and response.results[0].result: return User(self, response.results[0].result, secret_key=secret_key) return None
python
async def get_user(self, username, secret_key=None): client_facade = client.UserManagerFacade.from_connection( self.connection()) user = tag.user(username) args = [client.Entity(user)] try: response = await client_facade.UserInfo(args, True) except errors.JujuError as e: if 'permission denied' in e.errors: # apparently, trying to get info for a nonexistent user returns # a "permission denied" error rather than an empty result set return None raise if response.results and response.results[0].result: return User(self, response.results[0].result, secret_key=secret_key) return None
[ "async", "def", "get_user", "(", "self", ",", "username", ",", "secret_key", "=", "None", ")", ":", "client_facade", "=", "client", ".", "UserManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "user", "=", "tag", ".", ...
Get a user by name. :param str username: Username :param str secret_key: Issued by juju when add or reset user password :returns: A :class:`~juju.user.User` instance
[ "Get", "a", "user", "by", "name", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L528-L550
26,696
juju/python-libjuju
juju/controller.py
Controller.get_users
async def get_users(self, include_disabled=False): """Return list of users that can connect to this controller. :param bool include_disabled: Include disabled users :returns: A list of :class:`~juju.user.User` instances """ client_facade = client.UserManagerFacade.from_connection( self.connection()) response = await client_facade.UserInfo(None, include_disabled) return [User(self, r.result) for r in response.results]
python
async def get_users(self, include_disabled=False): client_facade = client.UserManagerFacade.from_connection( self.connection()) response = await client_facade.UserInfo(None, include_disabled) return [User(self, r.result) for r in response.results]
[ "async", "def", "get_users", "(", "self", ",", "include_disabled", "=", "False", ")", ":", "client_facade", "=", "client", ".", "UserManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "response", "=", "await", "client_facade...
Return list of users that can connect to this controller. :param bool include_disabled: Include disabled users :returns: A list of :class:`~juju.user.User` instances
[ "Return", "list", "of", "users", "that", "can", "connect", "to", "this", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L552-L561
26,697
juju/python-libjuju
juju/controller.py
Controller.revoke
async def revoke(self, username, acl='login'): """Removes some or all access of a user to from a controller If 'login' access is revoked, the user will no longer have any permissions on the controller. Revoking a higher privilege from a user without that privilege will have no effect. :param str username: username :param str acl: Access to remove ('login', 'add-model' or 'superuser') """ controller_facade = client.ControllerFacade.from_connection( self.connection()) user = tag.user(username) changes = client.ModifyControllerAccess('login', 'revoke', user) return await controller_facade.ModifyControllerAccess([changes])
python
async def revoke(self, username, acl='login'): controller_facade = client.ControllerFacade.from_connection( self.connection()) user = tag.user(username) changes = client.ModifyControllerAccess('login', 'revoke', user) return await controller_facade.ModifyControllerAccess([changes])
[ "async", "def", "revoke", "(", "self", ",", "username", ",", "acl", "=", "'login'", ")", ":", "controller_facade", "=", "client", ".", "ControllerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "user", "=", "tag", ".", "us...
Removes some or all access of a user to from a controller If 'login' access is revoked, the user will no longer have any permissions on the controller. Revoking a higher privilege from a user without that privilege will have no effect. :param str username: username :param str acl: Access to remove ('login', 'add-model' or 'superuser')
[ "Removes", "some", "or", "all", "access", "of", "a", "user", "to", "from", "a", "controller", "If", "login", "access", "is", "revoked", "the", "user", "will", "no", "longer", "have", "any", "permissions", "on", "the", "controller", ".", "Revoking", "a", ...
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/controller.py#L586-L599
26,698
juju/python-libjuju
juju/client/jujudata.py
FileJujuData.current_model
def current_model(self, controller_name=None, model_only=False): '''Return the current model, qualified by its controller name. If controller_name is specified, the current model for that controller will be returned. If model_only is true, only the model name, not qualified by its controller name, will be returned. ''' # TODO respect JUJU_MODEL environment variable. if not controller_name: controller_name = self.current_controller() if not controller_name: raise JujuError('No current controller') models = self.models()[controller_name] if 'current-model' not in models: return None if model_only: return models['current-model'] return controller_name + ':' + models['current-model']
python
def current_model(self, controller_name=None, model_only=False): '''Return the current model, qualified by its controller name. If controller_name is specified, the current model for that controller will be returned. If model_only is true, only the model name, not qualified by its controller name, will be returned. ''' # TODO respect JUJU_MODEL environment variable. if not controller_name: controller_name = self.current_controller() if not controller_name: raise JujuError('No current controller') models = self.models()[controller_name] if 'current-model' not in models: return None if model_only: return models['current-model'] return controller_name + ':' + models['current-model']
[ "def", "current_model", "(", "self", ",", "controller_name", "=", "None", ",", "model_only", "=", "False", ")", ":", "# TODO respect JUJU_MODEL environment variable.", "if", "not", "controller_name", ":", "controller_name", "=", "self", ".", "current_controller", "(",...
Return the current model, qualified by its controller name. If controller_name is specified, the current model for that controller will be returned. If model_only is true, only the model name, not qualified by its controller name, will be returned.
[ "Return", "the", "current", "model", "qualified", "by", "its", "controller", "name", ".", "If", "controller_name", "is", "specified", "the", "current", "model", "for", "that", "controller", "will", "be", "returned", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/jujudata.py#L139-L157
26,699
juju/python-libjuju
juju/client/jujudata.py
FileJujuData.load_credential
def load_credential(self, cloud, name=None): """Load a local credential. :param str cloud: Name of cloud to load credentials from. :param str name: Name of credential. If None, the default credential will be used, if available. :return: A CloudCredential instance, or None. """ try: cloud = tag.untag('cloud-', cloud) creds_data = self.credentials()[cloud] if not name: default_credential = creds_data.pop('default-credential', None) default_region = creds_data.pop('default-region', None) # noqa if default_credential: name = creds_data['default-credential'] elif len(creds_data) == 1: name = list(creds_data)[0] else: return None, None cred_data = creds_data[name] auth_type = cred_data.pop('auth-type') return name, jujuclient.CloudCredential( auth_type=auth_type, attrs=cred_data, ) except (KeyError, FileNotFoundError): return None, None
python
def load_credential(self, cloud, name=None): try: cloud = tag.untag('cloud-', cloud) creds_data = self.credentials()[cloud] if not name: default_credential = creds_data.pop('default-credential', None) default_region = creds_data.pop('default-region', None) # noqa if default_credential: name = creds_data['default-credential'] elif len(creds_data) == 1: name = list(creds_data)[0] else: return None, None cred_data = creds_data[name] auth_type = cred_data.pop('auth-type') return name, jujuclient.CloudCredential( auth_type=auth_type, attrs=cred_data, ) except (KeyError, FileNotFoundError): return None, None
[ "def", "load_credential", "(", "self", ",", "cloud", ",", "name", "=", "None", ")", ":", "try", ":", "cloud", "=", "tag", ".", "untag", "(", "'cloud-'", ",", "cloud", ")", "creds_data", "=", "self", ".", "credentials", "(", ")", "[", "cloud", "]", ...
Load a local credential. :param str cloud: Name of cloud to load credentials from. :param str name: Name of credential. If None, the default credential will be used, if available. :return: A CloudCredential instance, or None.
[ "Load", "a", "local", "credential", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/jujudata.py#L159-L186