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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
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): """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()
[ "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
train
25,200
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): """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
[ "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
train
25,201
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): """ 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)
[ "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
train
25,202
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): """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
[ "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
train
25,203
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): """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"))
[ "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
train
25,204
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): """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)
[ "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
train
25,205
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): """Update this user's 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
train
25,206
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'): """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
[ "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
train
25,207
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): """Removes all access rights for this user from the controller. """ 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
train
25,208
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): """Disable this user. """ 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
train
25,209
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): """Re-enable this user. """ 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
train
25,210
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): """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')
[ "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
train
25,211
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=''): """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)
[ "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
train
25,212
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): """ 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)
[ "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
train
25,213
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): """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
[ "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
train
25,214
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): """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
[ "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
train
25,215
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): """ 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
[ "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
train
25,216
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
train
25,217
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
train
25,218
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): """ 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
[ "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
train
25,219
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
train
25,220
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
train
25,221
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
train
25,222
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
train
25,223
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): """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)
[ "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
train
25,224
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): """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
[ "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
train
25,225
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): """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
[ "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
train
25,226
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): """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)
[ "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
train
25,227
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): """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)
[ "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
train
25,228
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): """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)])
[ "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
train
25,229
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): """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])
[ "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
train
25,230
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): """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)
[ "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
train
25,231
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): """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)
[ "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
train
25,232
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): """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])
[ "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
train
25,233
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): """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])
[ "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
train
25,234
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): """ 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)
[ "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
train
25,235
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): """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)
[ "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
train
25,236
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): """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
[ "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
train
25,237
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): """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
[ "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
train
25,238
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): """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]
[ "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
train
25,239
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'): """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])
[ "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
train
25,240
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
train
25,241
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): """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
[ "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
train
25,242
juju/python-libjuju
juju/client/connection.py
_macaroons_for_domain
def _macaroons_for_domain(cookies, domain): '''Return any macaroons from the given cookie jar that apply to the given domain name.''' req = urllib.request.Request('https://' + domain + '/') cookies.add_cookie_header(req) return httpbakery.extract_macaroons(req)
python
def _macaroons_for_domain(cookies, domain): '''Return any macaroons from the given cookie jar that apply to the given domain name.''' req = urllib.request.Request('https://' + domain + '/') cookies.add_cookie_header(req) return httpbakery.extract_macaroons(req)
[ "def", "_macaroons_for_domain", "(", "cookies", ",", "domain", ")", ":", "req", "=", "urllib", ".", "request", ".", "Request", "(", "'https://'", "+", "domain", "+", "'/'", ")", "cookies", ".", "add_cookie_header", "(", "req", ")", "return", "httpbakery", ...
Return any macaroons from the given cookie jar that apply to the given domain name.
[ "Return", "any", "macaroons", "from", "the", "given", "cookie", "jar", "that", "apply", "to", "the", "given", "domain", "name", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L596-L601
train
25,243
juju/python-libjuju
juju/client/connection.py
Monitor.status
def status(self): """ Determine the status of the connection and receiver, and return ERROR, CONNECTED, or DISCONNECTED as appropriate. For simplicity, we only consider ourselves to be connected after the Connection class has setup a receiver task. This only happens after the websocket is open, and the connection isn't usable until that receiver has been started. """ connection = self.connection() # the connection instance was destroyed but someone kept # a separate reference to the monitor for some reason if not connection: return self.DISCONNECTED # connection cleanly disconnected or not yet opened if not connection.ws: return self.DISCONNECTED # close called but not yet complete if self.close_called.is_set(): return self.DISCONNECTING # connection closed uncleanly (we didn't call connection.close) stopped = connection._receiver_task.stopped.is_set() if stopped or not connection.ws.open: return self.ERROR # everything is fine! return self.CONNECTED
python
def status(self): """ Determine the status of the connection and receiver, and return ERROR, CONNECTED, or DISCONNECTED as appropriate. For simplicity, we only consider ourselves to be connected after the Connection class has setup a receiver task. This only happens after the websocket is open, and the connection isn't usable until that receiver has been started. """ connection = self.connection() # the connection instance was destroyed but someone kept # a separate reference to the monitor for some reason if not connection: return self.DISCONNECTED # connection cleanly disconnected or not yet opened if not connection.ws: return self.DISCONNECTED # close called but not yet complete if self.close_called.is_set(): return self.DISCONNECTING # connection closed uncleanly (we didn't call connection.close) stopped = connection._receiver_task.stopped.is_set() if stopped or not connection.ws.open: return self.ERROR # everything is fine! return self.CONNECTED
[ "def", "status", "(", "self", ")", ":", "connection", "=", "self", ".", "connection", "(", ")", "# the connection instance was destroyed but someone kept", "# a separate reference to the monitor for some reason", "if", "not", "connection", ":", "return", "self", ".", "DIS...
Determine the status of the connection and receiver, and return ERROR, CONNECTED, or DISCONNECTED as appropriate. For simplicity, we only consider ourselves to be connected after the Connection class has setup a receiver task. This only happens after the websocket is open, and the connection isn't usable until that receiver has been started.
[ "Determine", "the", "status", "of", "the", "connection", "and", "receiver", "and", "return", "ERROR", "CONNECTED", "or", "DISCONNECTED", "as", "appropriate", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L46-L78
train
25,244
juju/python-libjuju
juju/client/connection.py
Connection._pinger
async def _pinger(self): ''' A Controller can time us out if we are silent for too long. This is especially true in JaaS, which has a fairly strict timeout. To prevent timing out, we send a ping every ten seconds. ''' async def _do_ping(): try: await pinger_facade.Ping() await asyncio.sleep(10, loop=self.loop) except CancelledError: pass pinger_facade = client.PingerFacade.from_connection(self) try: while True: await utils.run_with_interrupt( _do_ping(), self.monitor.close_called, loop=self.loop) if self.monitor.close_called.is_set(): break except websockets.exceptions.ConnectionClosed: # The connection has closed - we can't do anything # more until the connection is restarted. log.debug('ping failed because of closed connection') pass
python
async def _pinger(self): ''' A Controller can time us out if we are silent for too long. This is especially true in JaaS, which has a fairly strict timeout. To prevent timing out, we send a ping every ten seconds. ''' async def _do_ping(): try: await pinger_facade.Ping() await asyncio.sleep(10, loop=self.loop) except CancelledError: pass pinger_facade = client.PingerFacade.from_connection(self) try: while True: await utils.run_with_interrupt( _do_ping(), self.monitor.close_called, loop=self.loop) if self.monitor.close_called.is_set(): break except websockets.exceptions.ConnectionClosed: # The connection has closed - we can't do anything # more until the connection is restarted. log.debug('ping failed because of closed connection') pass
[ "async", "def", "_pinger", "(", "self", ")", ":", "async", "def", "_do_ping", "(", ")", ":", "try", ":", "await", "pinger_facade", ".", "Ping", "(", ")", "await", "asyncio", ".", "sleep", "(", "10", ",", "loop", "=", "self", ".", "loop", ")", "exce...
A Controller can time us out if we are silent for too long. This is especially true in JaaS, which has a fairly strict timeout. To prevent timing out, we send a ping every ten seconds.
[ "A", "Controller", "can", "time", "us", "out", "if", "we", "are", "silent", "for", "too", "long", ".", "This", "is", "especially", "true", "in", "JaaS", "which", "has", "a", "fairly", "strict", "timeout", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L250-L278
train
25,245
juju/python-libjuju
juju/client/connection.py
Connection._http_headers
def _http_headers(self): """Return dictionary of http headers necessary for making an http connection to the endpoint of this Connection. :return: Dictionary of headers """ if not self.usertag: return {} creds = u'{}:{}'.format( self.usertag, self.password or '' ) token = base64.b64encode(creds.encode()) return { 'Authorization': 'Basic {}'.format(token.decode()) }
python
def _http_headers(self): """Return dictionary of http headers necessary for making an http connection to the endpoint of this Connection. :return: Dictionary of headers """ if not self.usertag: return {} creds = u'{}:{}'.format( self.usertag, self.password or '' ) token = base64.b64encode(creds.encode()) return { 'Authorization': 'Basic {}'.format(token.decode()) }
[ "def", "_http_headers", "(", "self", ")", ":", "if", "not", "self", ".", "usertag", ":", "return", "{", "}", "creds", "=", "u'{}:{}'", ".", "format", "(", "self", ".", "usertag", ",", "self", ".", "password", "or", "''", ")", "token", "=", "base64", ...
Return dictionary of http headers necessary for making an http connection to the endpoint of this Connection. :return: Dictionary of headers
[ "Return", "dictionary", "of", "http", "headers", "necessary", "for", "making", "an", "http", "connection", "to", "the", "endpoint", "of", "this", "Connection", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L350-L367
train
25,246
juju/python-libjuju
juju/client/connection.py
Connection.https_connection
def https_connection(self): """Return an https connection to this Connection's endpoint. Returns a 3-tuple containing:: 1. The :class:`HTTPSConnection` instance 2. Dictionary of auth headers to be used with the connection 3. The root url path (str) to be used for requests. """ endpoint = self.endpoint host, remainder = endpoint.split(':', 1) port = remainder if '/' in remainder: port, _ = remainder.split('/', 1) conn = HTTPSConnection( host, int(port), context=self._get_ssl(self.cacert), ) path = ( "/model/{}".format(self.uuid) if self.uuid else "" ) return conn, self._http_headers(), path
python
def https_connection(self): """Return an https connection to this Connection's endpoint. Returns a 3-tuple containing:: 1. The :class:`HTTPSConnection` instance 2. Dictionary of auth headers to be used with the connection 3. The root url path (str) to be used for requests. """ endpoint = self.endpoint host, remainder = endpoint.split(':', 1) port = remainder if '/' in remainder: port, _ = remainder.split('/', 1) conn = HTTPSConnection( host, int(port), context=self._get_ssl(self.cacert), ) path = ( "/model/{}".format(self.uuid) if self.uuid else "" ) return conn, self._http_headers(), path
[ "def", "https_connection", "(", "self", ")", ":", "endpoint", "=", "self", ".", "endpoint", "host", ",", "remainder", "=", "endpoint", ".", "split", "(", "':'", ",", "1", ")", "port", "=", "remainder", "if", "'/'", "in", "remainder", ":", "port", ",", ...
Return an https connection to this Connection's endpoint. Returns a 3-tuple containing:: 1. The :class:`HTTPSConnection` instance 2. Dictionary of auth headers to be used with the connection 3. The root url path (str) to be used for requests.
[ "Return", "an", "https", "connection", "to", "this", "Connection", "s", "endpoint", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L369-L394
train
25,247
juju/python-libjuju
juju/client/connection.py
Connection.connect_params
def connect_params(self): """Return a tuple of parameters suitable for passing to Connection.connect that can be used to make a new connection to the same controller (and model if specified. The first element in the returned tuple holds the endpoint argument; the other holds a dict of the keyword args. """ return { 'endpoint': self.endpoint, 'uuid': self.uuid, 'username': self.username, 'password': self.password, 'cacert': self.cacert, 'bakery_client': self.bakery_client, 'loop': self.loop, 'max_frame_size': self.max_frame_size, }
python
def connect_params(self): """Return a tuple of parameters suitable for passing to Connection.connect that can be used to make a new connection to the same controller (and model if specified. The first element in the returned tuple holds the endpoint argument; the other holds a dict of the keyword args. """ return { 'endpoint': self.endpoint, 'uuid': self.uuid, 'username': self.username, 'password': self.password, 'cacert': self.cacert, 'bakery_client': self.bakery_client, 'loop': self.loop, 'max_frame_size': self.max_frame_size, }
[ "def", "connect_params", "(", "self", ")", ":", "return", "{", "'endpoint'", ":", "self", ".", "endpoint", ",", "'uuid'", ":", "self", ".", "uuid", ",", "'username'", ":", "self", ".", "username", ",", "'password'", ":", "self", ".", "password", ",", "...
Return a tuple of parameters suitable for passing to Connection.connect that can be used to make a new connection to the same controller (and model if specified. The first element in the returned tuple holds the endpoint argument; the other holds a dict of the keyword args.
[ "Return", "a", "tuple", "of", "parameters", "suitable", "for", "passing", "to", "Connection", ".", "connect", "that", "can", "be", "used", "to", "make", "a", "new", "connection", "to", "the", "same", "controller", "(", "and", "model", "if", "specified", "....
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L403-L419
train
25,248
juju/python-libjuju
juju/client/connection.py
Connection.controller
async def controller(self): """Return a Connection to the controller at self.endpoint """ return await Connection.connect( self.endpoint, username=self.username, password=self.password, cacert=self.cacert, bakery_client=self.bakery_client, loop=self.loop, max_frame_size=self.max_frame_size, )
python
async def controller(self): """Return a Connection to the controller at self.endpoint """ return await Connection.connect( self.endpoint, username=self.username, password=self.password, cacert=self.cacert, bakery_client=self.bakery_client, loop=self.loop, max_frame_size=self.max_frame_size, )
[ "async", "def", "controller", "(", "self", ")", ":", "return", "await", "Connection", ".", "connect", "(", "self", ".", "endpoint", ",", "username", "=", "self", ".", "username", ",", "password", "=", "self", ".", "password", ",", "cacert", "=", "self", ...
Return a Connection to the controller at self.endpoint
[ "Return", "a", "Connection", "to", "the", "controller", "at", "self", ".", "endpoint" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L421-L432
train
25,249
juju/python-libjuju
juju/client/connection.py
Connection.reconnect
async def reconnect(self): """ Force a reconnection. """ monitor = self.monitor if monitor.reconnecting.locked() or monitor.close_called.is_set(): return async with monitor.reconnecting: await self.close() await self._connect_with_login([(self.endpoint, self.cacert)])
python
async def reconnect(self): """ Force a reconnection. """ monitor = self.monitor if monitor.reconnecting.locked() or monitor.close_called.is_set(): return async with monitor.reconnecting: await self.close() await self._connect_with_login([(self.endpoint, self.cacert)])
[ "async", "def", "reconnect", "(", "self", ")", ":", "monitor", "=", "self", ".", "monitor", "if", "monitor", ".", "reconnecting", ".", "locked", "(", ")", "or", "monitor", ".", "close_called", ".", "is_set", "(", ")", ":", "return", "async", "with", "m...
Force a reconnection.
[ "Force", "a", "reconnection", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L434-L442
train
25,250
juju/python-libjuju
juju/client/connector.py
Connector.connect
async def connect(self, **kwargs): """Connect to an arbitrary Juju model. kwargs are passed through to Connection.connect() """ kwargs.setdefault('loop', self.loop) kwargs.setdefault('max_frame_size', self.max_frame_size) kwargs.setdefault('bakery_client', self.bakery_client) if 'macaroons' in kwargs: if not kwargs['bakery_client']: kwargs['bakery_client'] = httpbakery.Client() if not kwargs['bakery_client'].cookies: kwargs['bakery_client'].cookies = GoCookieJar() jar = kwargs['bakery_client'].cookies for macaroon in kwargs.pop('macaroons'): jar.set_cookie(go_to_py_cookie(macaroon)) self._connection = await Connection.connect(**kwargs)
python
async def connect(self, **kwargs): """Connect to an arbitrary Juju model. kwargs are passed through to Connection.connect() """ kwargs.setdefault('loop', self.loop) kwargs.setdefault('max_frame_size', self.max_frame_size) kwargs.setdefault('bakery_client', self.bakery_client) if 'macaroons' in kwargs: if not kwargs['bakery_client']: kwargs['bakery_client'] = httpbakery.Client() if not kwargs['bakery_client'].cookies: kwargs['bakery_client'].cookies = GoCookieJar() jar = kwargs['bakery_client'].cookies for macaroon in kwargs.pop('macaroons'): jar.set_cookie(go_to_py_cookie(macaroon)) self._connection = await Connection.connect(**kwargs)
[ "async", "def", "connect", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'loop'", ",", "self", ".", "loop", ")", "kwargs", ".", "setdefault", "(", "'max_frame_size'", ",", "self", ".", "max_frame_size", ")", "kwargs",...
Connect to an arbitrary Juju model. kwargs are passed through to Connection.connect()
[ "Connect", "to", "an", "arbitrary", "Juju", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connector.py#L52-L68
train
25,251
juju/python-libjuju
juju/client/connector.py
Connector.connect_controller
async def connect_controller(self, controller_name=None): """Connect to a controller by name. If the name is empty, it connect to the current controller. """ if not controller_name: controller_name = self.jujudata.current_controller() if not controller_name: raise JujuConnectionError('No current controller') controller = self.jujudata.controllers()[controller_name] # TODO change Connection so we can pass all the endpoints # instead of just the first. endpoint = controller['api-endpoints'][0] accounts = self.jujudata.accounts().get(controller_name, {}) await self.connect( endpoint=endpoint, uuid=None, username=accounts.get('user'), password=accounts.get('password'), cacert=controller.get('ca-cert'), bakery_client=self.bakery_client_for_controller(controller_name), ) self.controller_name = controller_name
python
async def connect_controller(self, controller_name=None): """Connect to a controller by name. If the name is empty, it connect to the current controller. """ if not controller_name: controller_name = self.jujudata.current_controller() if not controller_name: raise JujuConnectionError('No current controller') controller = self.jujudata.controllers()[controller_name] # TODO change Connection so we can pass all the endpoints # instead of just the first. endpoint = controller['api-endpoints'][0] accounts = self.jujudata.accounts().get(controller_name, {}) await self.connect( endpoint=endpoint, uuid=None, username=accounts.get('user'), password=accounts.get('password'), cacert=controller.get('ca-cert'), bakery_client=self.bakery_client_for_controller(controller_name), ) self.controller_name = controller_name
[ "async", "def", "connect_controller", "(", "self", ",", "controller_name", "=", "None", ")", ":", "if", "not", "controller_name", ":", "controller_name", "=", "self", ".", "jujudata", ".", "current_controller", "(", ")", "if", "not", "controller_name", ":", "r...
Connect to a controller by name. If the name is empty, it connect to the current controller.
[ "Connect", "to", "a", "controller", "by", "name", ".", "If", "the", "name", "is", "empty", "it", "connect", "to", "the", "current", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connector.py#L78-L101
train
25,252
juju/python-libjuju
juju/client/connector.py
Connector.bakery_client_for_controller
def bakery_client_for_controller(self, controller_name): '''Make a copy of the bakery client with a the appropriate controller's cookiejar in it. ''' bakery_client = self.bakery_client if bakery_client: bakery_client = copy.copy(bakery_client) else: bakery_client = httpbakery.Client() bakery_client.cookies = self.jujudata.cookies_for_controller( controller_name) return bakery_client
python
def bakery_client_for_controller(self, controller_name): '''Make a copy of the bakery client with a the appropriate controller's cookiejar in it. ''' bakery_client = self.bakery_client if bakery_client: bakery_client = copy.copy(bakery_client) else: bakery_client = httpbakery.Client() bakery_client.cookies = self.jujudata.cookies_for_controller( controller_name) return bakery_client
[ "def", "bakery_client_for_controller", "(", "self", ",", "controller_name", ")", ":", "bakery_client", "=", "self", ".", "bakery_client", "if", "bakery_client", ":", "bakery_client", "=", "copy", ".", "copy", "(", "bakery_client", ")", "else", ":", "bakery_client"...
Make a copy of the bakery client with a the appropriate controller's cookiejar in it.
[ "Make", "a", "copy", "of", "the", "bakery", "client", "with", "a", "the", "appropriate", "controller", "s", "cookiejar", "in", "it", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connector.py#L145-L156
train
25,253
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._get_ssh_client
def _get_ssh_client(self, host, user, key): """Return a connected Paramiko ssh object. :param str host: The host to connect to. :param str user: The user to connect as. :param str key: The private key to authenticate with. :return: object: A paramiko.SSHClient :raises: :class:`paramiko.ssh_exception.SSHException` if the connection failed """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) pkey = None # Read the private key into a paramiko.RSAKey if os.path.exists(key): with open(key, 'r') as f: pkey = paramiko.RSAKey.from_private_key(f) ####################################################################### # There is a bug in some versions of OpenSSH 4.3 (CentOS/RHEL5) where # # the server may not send the SSH_MSG_USERAUTH_BANNER message except # # when responding to an auth_none request. For example, paramiko will # # attempt to use password authentication when a password is set, but # # the server could deny that, instead requesting keyboard-interactive.# # The hack to workaround this is to attempt a reconnect, which will # # receive the right banner, and authentication can proceed. See the # # following for more info: # # https://github.com/paramiko/paramiko/issues/432 # # https://github.com/paramiko/paramiko/pull/438 # ####################################################################### try: ssh.connect(host, port=22, username=user, pkey=pkey) except paramiko.ssh_exception.SSHException as e: if 'Error reading SSH protocol banner' == str(e): # Once more, with feeling ssh.connect(host, port=22, username=user, pkey=pkey) else: # Reraise the original exception raise e return ssh
python
def _get_ssh_client(self, host, user, key): """Return a connected Paramiko ssh object. :param str host: The host to connect to. :param str user: The user to connect as. :param str key: The private key to authenticate with. :return: object: A paramiko.SSHClient :raises: :class:`paramiko.ssh_exception.SSHException` if the connection failed """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) pkey = None # Read the private key into a paramiko.RSAKey if os.path.exists(key): with open(key, 'r') as f: pkey = paramiko.RSAKey.from_private_key(f) ####################################################################### # There is a bug in some versions of OpenSSH 4.3 (CentOS/RHEL5) where # # the server may not send the SSH_MSG_USERAUTH_BANNER message except # # when responding to an auth_none request. For example, paramiko will # # attempt to use password authentication when a password is set, but # # the server could deny that, instead requesting keyboard-interactive.# # The hack to workaround this is to attempt a reconnect, which will # # receive the right banner, and authentication can proceed. See the # # following for more info: # # https://github.com/paramiko/paramiko/issues/432 # # https://github.com/paramiko/paramiko/pull/438 # ####################################################################### try: ssh.connect(host, port=22, username=user, pkey=pkey) except paramiko.ssh_exception.SSHException as e: if 'Error reading SSH protocol banner' == str(e): # Once more, with feeling ssh.connect(host, port=22, username=user, pkey=pkey) else: # Reraise the original exception raise e return ssh
[ "def", "_get_ssh_client", "(", "self", ",", "host", ",", "user", ",", "key", ")", ":", "ssh", "=", "paramiko", ".", "SSHClient", "(", ")", "ssh", ".", "set_missing_host_key_policy", "(", "paramiko", ".", "AutoAddPolicy", "(", ")", ")", "pkey", "=", "None...
Return a connected Paramiko ssh object. :param str host: The host to connect to. :param str user: The user to connect as. :param str key: The private key to authenticate with. :return: object: A paramiko.SSHClient :raises: :class:`paramiko.ssh_exception.SSHException` if the connection failed
[ "Return", "a", "connected", "Paramiko", "ssh", "object", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L72-L117
train
25,254
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._run_command
def _run_command(self, ssh, cmd, pty=True): """Run a command remotely via SSH. :param object ssh: The SSHClient :param str cmd: The command to execute :param list cmd: The `shlex.split` command to execute :param bool pty: Whether to allocate a pty :return: tuple: The stdout and stderr of the command execution :raises: :class:`CalledProcessError` if the command fails """ if isinstance(cmd, str): cmd = shlex.split(cmd) if type(cmd) is not list: cmd = [cmd] cmds = ' '.join(cmd) stdin, stdout, stderr = ssh.exec_command(cmds, get_pty=pty) retcode = stdout.channel.recv_exit_status() if retcode > 0: output = stderr.read().strip() raise CalledProcessError(returncode=retcode, cmd=cmd, output=output) return ( stdout.read().decode('utf-8').strip(), stderr.read().decode('utf-8').strip() )
python
def _run_command(self, ssh, cmd, pty=True): """Run a command remotely via SSH. :param object ssh: The SSHClient :param str cmd: The command to execute :param list cmd: The `shlex.split` command to execute :param bool pty: Whether to allocate a pty :return: tuple: The stdout and stderr of the command execution :raises: :class:`CalledProcessError` if the command fails """ if isinstance(cmd, str): cmd = shlex.split(cmd) if type(cmd) is not list: cmd = [cmd] cmds = ' '.join(cmd) stdin, stdout, stderr = ssh.exec_command(cmds, get_pty=pty) retcode = stdout.channel.recv_exit_status() if retcode > 0: output = stderr.read().strip() raise CalledProcessError(returncode=retcode, cmd=cmd, output=output) return ( stdout.read().decode('utf-8').strip(), stderr.read().decode('utf-8').strip() )
[ "def", "_run_command", "(", "self", ",", "ssh", ",", "cmd", ",", "pty", "=", "True", ")", ":", "if", "isinstance", "(", "cmd", ",", "str", ")", ":", "cmd", "=", "shlex", ".", "split", "(", "cmd", ")", "if", "type", "(", "cmd", ")", "is", "not",...
Run a command remotely via SSH. :param object ssh: The SSHClient :param str cmd: The command to execute :param list cmd: The `shlex.split` command to execute :param bool pty: Whether to allocate a pty :return: tuple: The stdout and stderr of the command execution :raises: :class:`CalledProcessError` if the command fails
[ "Run", "a", "command", "remotely", "via", "SSH", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L119-L148
train
25,255
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._init_ubuntu_user
def _init_ubuntu_user(self): """Initialize the ubuntu user. :return: bool: If the initialization was successful :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the authentication fails """ # TODO: Test this on an image without the ubuntu user setup. auth_user = self.user ssh = None try: # Run w/o allocating a pty, so we fail if sudo prompts for a passwd ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) stdout, stderr = self._run_command(ssh, "sudo -n true", pty=False) except paramiko.ssh_exception.AuthenticationException as e: raise e else: auth_user = "ubuntu" finally: if ssh: ssh.close() # if the above fails, run the init script as the authenticated user # Infer the public key public_key = None public_key_path = "{}.pub".format(self.private_key_path) if not os.path.exists(public_key_path): raise FileNotFoundError( "Public key '{}' doesn't exist.".format(public_key_path) ) with open(public_key_path, "r") as f: public_key = f.readline() script = INITIALIZE_UBUNTU_SCRIPT.format(public_key) try: ssh = self._get_ssh_client( self.host, auth_user, self.private_key_path, ) self._run_command( ssh, ["sudo", "/bin/bash -c " + shlex.quote(script)], pty=True ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: ssh.close() return True
python
def _init_ubuntu_user(self): """Initialize the ubuntu user. :return: bool: If the initialization was successful :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the authentication fails """ # TODO: Test this on an image without the ubuntu user setup. auth_user = self.user ssh = None try: # Run w/o allocating a pty, so we fail if sudo prompts for a passwd ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) stdout, stderr = self._run_command(ssh, "sudo -n true", pty=False) except paramiko.ssh_exception.AuthenticationException as e: raise e else: auth_user = "ubuntu" finally: if ssh: ssh.close() # if the above fails, run the init script as the authenticated user # Infer the public key public_key = None public_key_path = "{}.pub".format(self.private_key_path) if not os.path.exists(public_key_path): raise FileNotFoundError( "Public key '{}' doesn't exist.".format(public_key_path) ) with open(public_key_path, "r") as f: public_key = f.readline() script = INITIALIZE_UBUNTU_SCRIPT.format(public_key) try: ssh = self._get_ssh_client( self.host, auth_user, self.private_key_path, ) self._run_command( ssh, ["sudo", "/bin/bash -c " + shlex.quote(script)], pty=True ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: ssh.close() return True
[ "def", "_init_ubuntu_user", "(", "self", ")", ":", "# TODO: Test this on an image without the ubuntu user setup.", "auth_user", "=", "self", ".", "user", "ssh", "=", "None", "try", ":", "# Run w/o allocating a pty, so we fail if sudo prompts for a passwd", "ssh", "=", "self",...
Initialize the ubuntu user. :return: bool: If the initialization was successful :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the authentication fails
[ "Initialize", "the", "ubuntu", "user", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L150-L212
train
25,256
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._detect_hardware_and_os
def _detect_hardware_and_os(self, ssh): """Detect the target hardware capabilities and OS series. :param object ssh: The SSHClient :return: str: A raw string containing OS and hardware information. """ info = { 'series': '', 'arch': '', 'cpu-cores': '', 'mem': '', } stdout, stderr = self._run_command( ssh, ["sudo", "/bin/bash -c " + shlex.quote(DETECTION_SCRIPT)], pty=True, ) lines = stdout.split("\n") info['series'] = lines[0].strip() info['arch'] = normalize_arch(lines[1].strip()) memKb = re.split(r'\s+', lines[2])[1] # Convert megabytes -> kilobytes info['mem'] = round(int(memKb) / 1024) # Detect available CPUs recorded = {} for line in lines[3:]: physical_id = "" print(line) if line.find("physical id") == 0: physical_id = line.split(":")[1].strip() elif line.find("cpu cores") == 0: cores = line.split(":")[1].strip() if physical_id not in recorded.keys(): info['cpu-cores'] += cores recorded[physical_id] = True return info
python
def _detect_hardware_and_os(self, ssh): """Detect the target hardware capabilities and OS series. :param object ssh: The SSHClient :return: str: A raw string containing OS and hardware information. """ info = { 'series': '', 'arch': '', 'cpu-cores': '', 'mem': '', } stdout, stderr = self._run_command( ssh, ["sudo", "/bin/bash -c " + shlex.quote(DETECTION_SCRIPT)], pty=True, ) lines = stdout.split("\n") info['series'] = lines[0].strip() info['arch'] = normalize_arch(lines[1].strip()) memKb = re.split(r'\s+', lines[2])[1] # Convert megabytes -> kilobytes info['mem'] = round(int(memKb) / 1024) # Detect available CPUs recorded = {} for line in lines[3:]: physical_id = "" print(line) if line.find("physical id") == 0: physical_id = line.split(":")[1].strip() elif line.find("cpu cores") == 0: cores = line.split(":")[1].strip() if physical_id not in recorded.keys(): info['cpu-cores'] += cores recorded[physical_id] = True return info
[ "def", "_detect_hardware_and_os", "(", "self", ",", "ssh", ")", ":", "info", "=", "{", "'series'", ":", "''", ",", "'arch'", ":", "''", ",", "'cpu-cores'", ":", "''", ",", "'mem'", ":", "''", ",", "}", "stdout", ",", "stderr", "=", "self", ".", "_r...
Detect the target hardware capabilities and OS series. :param object ssh: The SSHClient :return: str: A raw string containing OS and hardware information.
[ "Detect", "the", "target", "hardware", "capabilities", "and", "OS", "series", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L214-L258
train
25,257
juju/python-libjuju
juju/provisioner.py
SSHProvisioner.provision_machine
def provision_machine(self): """Perform the initial provisioning of the target machine. :return: bool: The client.AddMachineParams :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ params = client.AddMachineParams() if self._init_ubuntu_user(): try: ssh = self._get_ssh_client( self.host, self.user, self.private_key_path ) hw = self._detect_hardware_and_os(ssh) params.series = hw['series'] params.instance_id = "manual:{}".format(self.host) params.nonce = "manual:{}:{}".format( self.host, str(uuid.uuid4()), # a nop for Juju w/manual machines ) params.hardware_characteristics = { 'arch': hw['arch'], 'mem': int(hw['mem']), 'cpu-cores': int(hw['cpu-cores']), } params.addresses = [{ 'value': self.host, 'type': 'ipv4', 'scope': 'public', }] except paramiko.ssh_exception.AuthenticationException as e: raise e finally: ssh.close() return params
python
def provision_machine(self): """Perform the initial provisioning of the target machine. :return: bool: The client.AddMachineParams :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ params = client.AddMachineParams() if self._init_ubuntu_user(): try: ssh = self._get_ssh_client( self.host, self.user, self.private_key_path ) hw = self._detect_hardware_and_os(ssh) params.series = hw['series'] params.instance_id = "manual:{}".format(self.host) params.nonce = "manual:{}:{}".format( self.host, str(uuid.uuid4()), # a nop for Juju w/manual machines ) params.hardware_characteristics = { 'arch': hw['arch'], 'mem': int(hw['mem']), 'cpu-cores': int(hw['cpu-cores']), } params.addresses = [{ 'value': self.host, 'type': 'ipv4', 'scope': 'public', }] except paramiko.ssh_exception.AuthenticationException as e: raise e finally: ssh.close() return params
[ "def", "provision_machine", "(", "self", ")", ":", "params", "=", "client", ".", "AddMachineParams", "(", ")", "if", "self", ".", "_init_ubuntu_user", "(", ")", ":", "try", ":", "ssh", "=", "self", ".", "_get_ssh_client", "(", "self", ".", "host", ",", ...
Perform the initial provisioning of the target machine. :return: bool: The client.AddMachineParams :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails
[ "Perform", "the", "initial", "provisioning", "of", "the", "target", "machine", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L260-L301
train
25,258
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._run_configure_script
def _run_configure_script(self, script): """Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ _, tmpFile = tempfile.mkstemp() with open(tmpFile, 'w') as f: f.write(script) try: # get ssh client ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) # copy the local copy of the script to the remote machine sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) sftp.put( tmpFile, tmpFile, ) # run the provisioning script stdout, stderr = self._run_command( ssh, "sudo /bin/bash {}".format(tmpFile), ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: os.remove(tmpFile) ssh.close()
python
def _run_configure_script(self, script): """Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ _, tmpFile = tempfile.mkstemp() with open(tmpFile, 'w') as f: f.write(script) try: # get ssh client ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) # copy the local copy of the script to the remote machine sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) sftp.put( tmpFile, tmpFile, ) # run the provisioning script stdout, stderr = self._run_command( ssh, "sudo /bin/bash {}".format(tmpFile), ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: os.remove(tmpFile) ssh.close()
[ "def", "_run_configure_script", "(", "self", ",", "script", ")", ":", "_", ",", "tmpFile", "=", "tempfile", ".", "mkstemp", "(", ")", "with", "open", "(", "tmpFile", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "script", ")", "try", ":"...
Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails
[ "Run", "the", "script", "to", "install", "the", "Juju", "agent", "on", "the", "target", "machine", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L329-L366
train
25,259
juju/python-libjuju
juju/annotationhelper.py
_get_annotations
async def _get_annotations(entity_tag, connection): """Get annotations for the specified entity :return dict: The annotations for the entity """ facade = client.AnnotationsFacade.from_connection(connection) result = (await facade.Get([{"tag": entity_tag}])).results[0] if result.error is not None: raise JujuError(result.error) return result.annotations
python
async def _get_annotations(entity_tag, connection): """Get annotations for the specified entity :return dict: The annotations for the entity """ facade = client.AnnotationsFacade.from_connection(connection) result = (await facade.Get([{"tag": entity_tag}])).results[0] if result.error is not None: raise JujuError(result.error) return result.annotations
[ "async", "def", "_get_annotations", "(", "entity_tag", ",", "connection", ")", ":", "facade", "=", "client", ".", "AnnotationsFacade", ".", "from_connection", "(", "connection", ")", "result", "=", "(", "await", "facade", ".", "Get", "(", "[", "{", "\"tag\""...
Get annotations for the specified entity :return dict: The annotations for the entity
[ "Get", "annotations", "for", "the", "specified", "entity" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/annotationhelper.py#L9-L18
train
25,260
juju/python-libjuju
juju/annotationhelper.py
_set_annotations
async def _set_annotations(entity_tag, annotations, connection): """Set annotations on the specified entity. :param annotations map[string]string: the annotations as key/value pairs. """ # TODO: ensure annotations is dict with only string keys # and values. log.debug('Updating annotations on %s', entity_tag) facade = client.AnnotationsFacade.from_connection(connection) args = client.EntityAnnotations( entity=entity_tag, annotations=annotations, ) return await facade.Set([args])
python
async def _set_annotations(entity_tag, annotations, connection): """Set annotations on the specified entity. :param annotations map[string]string: the annotations as key/value pairs. """ # TODO: ensure annotations is dict with only string keys # and values. log.debug('Updating annotations on %s', entity_tag) facade = client.AnnotationsFacade.from_connection(connection) args = client.EntityAnnotations( entity=entity_tag, annotations=annotations, ) return await facade.Set([args])
[ "async", "def", "_set_annotations", "(", "entity_tag", ",", "annotations", ",", "connection", ")", ":", "# TODO: ensure annotations is dict with only string keys", "# and values.", "log", ".", "debug", "(", "'Updating annotations on %s'", ",", "entity_tag", ")", "facade", ...
Set annotations on the specified entity. :param annotations map[string]string: the annotations as key/value pairs.
[ "Set", "annotations", "on", "the", "specified", "entity", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/annotationhelper.py#L21-L35
train
25,261
juju/python-libjuju
juju/relation.py
Relation.matches
def matches(self, *specs): """ Check if this relation matches relationship specs. Relation specs are strings that would be given to Juju to establish a relation, and should be in the form ``<application>[:<endpoint_name>]`` where the ``:<endpoint_name>`` suffix is optional. If the suffix is omitted, this relation will match on any endpoint as long as the given application is involved. In other words, this relation will match a spec if that spec could have created this relation. :return: True if all specs match. """ for spec in specs: if ':' in spec: app_name, endpoint_name = spec.split(':') else: app_name, endpoint_name = spec, None for endpoint in self.endpoints: if app_name == endpoint.application.name and \ endpoint_name in (endpoint.name, None): # found a match for this spec, so move to next one break else: # no match for this spec return False return True
python
def matches(self, *specs): """ Check if this relation matches relationship specs. Relation specs are strings that would be given to Juju to establish a relation, and should be in the form ``<application>[:<endpoint_name>]`` where the ``:<endpoint_name>`` suffix is optional. If the suffix is omitted, this relation will match on any endpoint as long as the given application is involved. In other words, this relation will match a spec if that spec could have created this relation. :return: True if all specs match. """ for spec in specs: if ':' in spec: app_name, endpoint_name = spec.split(':') else: app_name, endpoint_name = spec, None for endpoint in self.endpoints: if app_name == endpoint.application.name and \ endpoint_name in (endpoint.name, None): # found a match for this spec, so move to next one break else: # no match for this spec return False return True
[ "def", "matches", "(", "self", ",", "*", "specs", ")", ":", "for", "spec", "in", "specs", ":", "if", "':'", "in", "spec", ":", "app_name", ",", "endpoint_name", "=", "spec", ".", "split", "(", "':'", ")", "else", ":", "app_name", ",", "endpoint_name"...
Check if this relation matches relationship specs. Relation specs are strings that would be given to Juju to establish a relation, and should be in the form ``<application>[:<endpoint_name>]`` where the ``:<endpoint_name>`` suffix is optional. If the suffix is omitted, this relation will match on any endpoint as long as the given application is involved. In other words, this relation will match a spec if that spec could have created this relation. :return: True if all specs match.
[ "Check", "if", "this", "relation", "matches", "relationship", "specs", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/relation.py#L84-L112
train
25,262
juju/python-libjuju
juju/client/overrides.py
ResourcesFacade.AddPendingResources
async def AddPendingResources(self, application_tag, charm_url, resources): """Fix the calling signature of AddPendingResources. The ResourcesFacade doesn't conform to the standard facade pattern in the Juju source, which leads to the schemagened code not matching up properly with the actual calling convention in the API. There is work planned to fix this in Juju, but we have to work around it for now. application_tag : str charm_url : str resources : typing.Sequence<+T_co>[~CharmResource]<~CharmResource> Returns -> typing.Union[_ForwardRef('ErrorResult'), typing.Sequence<+T_co>[str]] """ # map input types to rpc msg _params = dict() msg = dict(type='Resources', request='AddPendingResources', version=1, params=_params) _params['tag'] = application_tag _params['url'] = charm_url _params['resources'] = resources reply = await self.rpc(msg) return reply
python
async def AddPendingResources(self, application_tag, charm_url, resources): """Fix the calling signature of AddPendingResources. The ResourcesFacade doesn't conform to the standard facade pattern in the Juju source, which leads to the schemagened code not matching up properly with the actual calling convention in the API. There is work planned to fix this in Juju, but we have to work around it for now. application_tag : str charm_url : str resources : typing.Sequence<+T_co>[~CharmResource]<~CharmResource> Returns -> typing.Union[_ForwardRef('ErrorResult'), typing.Sequence<+T_co>[str]] """ # map input types to rpc msg _params = dict() msg = dict(type='Resources', request='AddPendingResources', version=1, params=_params) _params['tag'] = application_tag _params['url'] = charm_url _params['resources'] = resources reply = await self.rpc(msg) return reply
[ "async", "def", "AddPendingResources", "(", "self", ",", "application_tag", ",", "charm_url", ",", "resources", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Resources'", ",", "request", "="...
Fix the calling signature of AddPendingResources. The ResourcesFacade doesn't conform to the standard facade pattern in the Juju source, which leads to the schemagened code not matching up properly with the actual calling convention in the API. There is work planned to fix this in Juju, but we have to work around it for now. application_tag : str charm_url : str resources : typing.Sequence<+T_co>[~CharmResource]<~CharmResource> Returns -> typing.Union[_ForwardRef('ErrorResult'), typing.Sequence<+T_co>[str]]
[ "Fix", "the", "calling", "signature", "of", "AddPendingResources", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/overrides.py#L65-L89
train
25,263
juju/python-libjuju
juju/cloud.py
Cloud.bootstrap
def bootstrap( self, controller_name, region=None, agent_version=None, auto_upgrade=False, bootstrap_constraints=None, bootstrap_series=None, config=None, constraints=None, credential=None, default_model=None, keep_broken=False, metadata_source=None, no_gui=False, to=None, upload_tools=False): """Initialize a cloud environment. :param str controller_name: Name of controller to create :param str region: Cloud region in which to bootstrap :param str agent_version: Version of tools to use for Juju agents :param bool auto_upgrade: Upgrade to latest path release tools on first bootstrap :param bootstrap_constraints: Constraints for the bootstrap machine :type bootstrap_constraints: :class:`juju.Constraints` :param str bootstrap_series: Series of the bootstrap machine :param dict config: Controller configuration :param constraints: Default constraints for all future workload machines :type constraints: :class:`juju.Constraints` :param credential: Credential to use when bootstrapping :type credential: :class:`juju.Credential` :param str default_model: Name to give the default model :param bool keep_broken: Don't destroy model if bootstrap fails :param str metadata_source: Local path to use as tools and/or metadata source :param bool no_gui: Don't install the Juju GUI in the controller when bootstrapping :param str to: Placement directive for bootstrap node (typically used with MAAS) :param bool upload_tools: Upload local version of tools before bootstrapping """ raise NotImplementedError()
python
def bootstrap( self, controller_name, region=None, agent_version=None, auto_upgrade=False, bootstrap_constraints=None, bootstrap_series=None, config=None, constraints=None, credential=None, default_model=None, keep_broken=False, metadata_source=None, no_gui=False, to=None, upload_tools=False): """Initialize a cloud environment. :param str controller_name: Name of controller to create :param str region: Cloud region in which to bootstrap :param str agent_version: Version of tools to use for Juju agents :param bool auto_upgrade: Upgrade to latest path release tools on first bootstrap :param bootstrap_constraints: Constraints for the bootstrap machine :type bootstrap_constraints: :class:`juju.Constraints` :param str bootstrap_series: Series of the bootstrap machine :param dict config: Controller configuration :param constraints: Default constraints for all future workload machines :type constraints: :class:`juju.Constraints` :param credential: Credential to use when bootstrapping :type credential: :class:`juju.Credential` :param str default_model: Name to give the default model :param bool keep_broken: Don't destroy model if bootstrap fails :param str metadata_source: Local path to use as tools and/or metadata source :param bool no_gui: Don't install the Juju GUI in the controller when bootstrapping :param str to: Placement directive for bootstrap node (typically used with MAAS) :param bool upload_tools: Upload local version of tools before bootstrapping """ raise NotImplementedError()
[ "def", "bootstrap", "(", "self", ",", "controller_name", ",", "region", "=", "None", ",", "agent_version", "=", "None", ",", "auto_upgrade", "=", "False", ",", "bootstrap_constraints", "=", "None", ",", "bootstrap_series", "=", "None", ",", "config", "=", "N...
Initialize a cloud environment. :param str controller_name: Name of controller to create :param str region: Cloud region in which to bootstrap :param str agent_version: Version of tools to use for Juju agents :param bool auto_upgrade: Upgrade to latest path release tools on first bootstrap :param bootstrap_constraints: Constraints for the bootstrap machine :type bootstrap_constraints: :class:`juju.Constraints` :param str bootstrap_series: Series of the bootstrap machine :param dict config: Controller configuration :param constraints: Default constraints for all future workload machines :type constraints: :class:`juju.Constraints` :param credential: Credential to use when bootstrapping :type credential: :class:`juju.Credential` :param str default_model: Name to give the default model :param bool keep_broken: Don't destroy model if bootstrap fails :param str metadata_source: Local path to use as tools and/or metadata source :param bool no_gui: Don't install the Juju GUI in the controller when bootstrapping :param str to: Placement directive for bootstrap node (typically used with MAAS) :param bool upload_tools: Upload local version of tools before bootstrapping
[ "Initialize", "a", "cloud", "environment", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/cloud.py#L29-L65
train
25,264
juju/python-libjuju
juju/unit.py
Unit.machine
def machine(self): """Get the machine object for this unit. """ machine_id = self.safe_data['machine-id'] if machine_id: return self.model.machines.get(machine_id, None) else: return None
python
def machine(self): """Get the machine object for this unit. """ machine_id = self.safe_data['machine-id'] if machine_id: return self.model.machines.get(machine_id, None) else: return None
[ "def", "machine", "(", "self", ")", ":", "machine_id", "=", "self", ".", "safe_data", "[", "'machine-id'", "]", "if", "machine_id", ":", "return", "self", ".", "model", ".", "machines", ".", "get", "(", "machine_id", ",", "None", ")", "else", ":", "ret...
Get the machine object for this unit.
[ "Get", "the", "machine", "object", "for", "this", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L56-L64
train
25,265
juju/python-libjuju
juju/unit.py
Unit.run
async def run(self, command, timeout=None): """Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance. """ action = client.ActionFacade.from_connection(self.connection) log.debug( 'Running `%s` on %s', command, self.name) if timeout: # Convert seconds to nanoseconds timeout = int(timeout * 1000000000) res = await action.Run( [], command, [], timeout, [self.name], ) return await self.model.wait_for_action(res.results[0].action.tag)
python
async def run(self, command, timeout=None): """Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance. """ action = client.ActionFacade.from_connection(self.connection) log.debug( 'Running `%s` on %s', command, self.name) if timeout: # Convert seconds to nanoseconds timeout = int(timeout * 1000000000) res = await action.Run( [], command, [], timeout, [self.name], ) return await self.model.wait_for_action(res.results[0].action.tag)
[ "async", "def", "run", "(", "self", ",", "command", ",", "timeout", "=", "None", ")", ":", "action", "=", "client", ".", "ActionFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Running `%s` on %s'", ",", "...
Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance.
[ "Run", "command", "on", "this", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L122-L147
train
25,266
juju/python-libjuju
juju/unit.py
Unit.run_action
async def run_action(self, action_name, **params): """Run an action on this unit. :param str action_name: Name of action to run :param **params: Action parameters :returns: A :class:`juju.action.Action` instance. Note that this only enqueues the action. You will need to call ``action.wait()`` on the resulting `Action` instance if you wish to block until the action is complete. """ action_facade = client.ActionFacade.from_connection(self.connection) log.debug('Starting action `%s` on %s', action_name, self.name) res = await action_facade.Enqueue([client.Action( name=action_name, parameters=params, receiver=self.tag, )]) action = res.results[0].action error = res.results[0].error if error and error.code == 'not found': raise ValueError('Action `%s` not found on %s' % (action_name, self.name)) elif error: raise Exception('Unknown action error: %s' % error.serialize()) action_id = action.tag[len('action-'):] log.debug('Action started as %s', action_id) # we mustn't use wait_for_action because that blocks until the # action is complete, rather than just being in the model return await self.model._wait_for_new('action', action_id)
python
async def run_action(self, action_name, **params): """Run an action on this unit. :param str action_name: Name of action to run :param **params: Action parameters :returns: A :class:`juju.action.Action` instance. Note that this only enqueues the action. You will need to call ``action.wait()`` on the resulting `Action` instance if you wish to block until the action is complete. """ action_facade = client.ActionFacade.from_connection(self.connection) log.debug('Starting action `%s` on %s', action_name, self.name) res = await action_facade.Enqueue([client.Action( name=action_name, parameters=params, receiver=self.tag, )]) action = res.results[0].action error = res.results[0].error if error and error.code == 'not found': raise ValueError('Action `%s` not found on %s' % (action_name, self.name)) elif error: raise Exception('Unknown action error: %s' % error.serialize()) action_id = action.tag[len('action-'):] log.debug('Action started as %s', action_id) # we mustn't use wait_for_action because that blocks until the # action is complete, rather than just being in the model return await self.model._wait_for_new('action', action_id)
[ "async", "def", "run_action", "(", "self", ",", "action_name", ",", "*", "*", "params", ")", ":", "action_facade", "=", "client", ".", "ActionFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Starting action `%...
Run an action on this unit. :param str action_name: Name of action to run :param **params: Action parameters :returns: A :class:`juju.action.Action` instance. Note that this only enqueues the action. You will need to call ``action.wait()`` on the resulting `Action` instance if you wish to block until the action is complete.
[ "Run", "an", "action", "on", "this", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L149-L181
train
25,267
juju/python-libjuju
juju/unit.py
Unit.scp_to
async def scp_to(self, source, destination, user='ubuntu', proxy=False, scp_opts=''): """Transfer files to this unit. :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 """ await self.machine.scp_to(source, destination, user=user, proxy=proxy, scp_opts=scp_opts)
python
async def scp_to(self, source, destination, user='ubuntu', proxy=False, scp_opts=''): """Transfer files to this unit. :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 """ await self.machine.scp_to(source, destination, user=user, proxy=proxy, scp_opts=scp_opts)
[ "async", "def", "scp_to", "(", "self", ",", "source", ",", "destination", ",", "user", "=", "'ubuntu'", ",", "proxy", "=", "False", ",", "scp_opts", "=", "''", ")", ":", "await", "self", ".", "machine", ".", "scp_to", "(", "source", ",", "destination",...
Transfer files to this unit. :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", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L183-L195
train
25,268
juju/python-libjuju
juju/unit.py
Unit.get_metrics
async def get_metrics(self): """Get metrics for the unit. :return: Dictionary of metrics for this unit. """ metrics = await self.model.get_metrics(self.tag) return metrics[self.name]
python
async def get_metrics(self): """Get metrics for the unit. :return: Dictionary of metrics for this unit. """ metrics = await self.model.get_metrics(self.tag) return metrics[self.name]
[ "async", "def", "get_metrics", "(", "self", ")", ":", "metrics", "=", "await", "self", ".", "model", ".", "get_metrics", "(", "self", ".", "tag", ")", "return", "metrics", "[", "self", ".", "name", "]" ]
Get metrics for the unit. :return: Dictionary of metrics for this unit.
[ "Get", "metrics", "for", "the", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L275-L282
train
25,269
juju/python-libjuju
juju/constraints.py
parse
def parse(constraints): """ Constraints must be expressed as a string containing only spaces and key value pairs joined by an '='. """ if not constraints: return None if type(constraints) is dict: # Fowards compatibilty: already parsed return constraints constraints = { normalize_key(k): ( normalize_list_value(v) if k in LIST_KEYS else normalize_value(v) ) for k, v in [s.split("=") for s in constraints.split(" ")]} return constraints
python
def parse(constraints): """ Constraints must be expressed as a string containing only spaces and key value pairs joined by an '='. """ if not constraints: return None if type(constraints) is dict: # Fowards compatibilty: already parsed return constraints constraints = { normalize_key(k): ( normalize_list_value(v) if k in LIST_KEYS else normalize_value(v) ) for k, v in [s.split("=") for s in constraints.split(" ")]} return constraints
[ "def", "parse", "(", "constraints", ")", ":", "if", "not", "constraints", ":", "return", "None", "if", "type", "(", "constraints", ")", "is", "dict", ":", "# Fowards compatibilty: already parsed", "return", "constraints", "constraints", "=", "{", "normalize_key", ...
Constraints must be expressed as a string containing only spaces and key value pairs joined by an '='.
[ "Constraints", "must", "be", "expressed", "as", "a", "string", "containing", "only", "spaces", "and", "key", "value", "pairs", "joined", "by", "an", "=", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/constraints.py#L38-L57
train
25,270
juju/python-libjuju
juju/application.py
Application.add_relation
async def add_relation(self, local_relation, remote_relation): """Add a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]' """ if ':' not in local_relation: local_relation = '{}:{}'.format(self.name, local_relation) return await self.model.add_relation(local_relation, remote_relation)
python
async def add_relation(self, local_relation, remote_relation): """Add a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]' """ if ':' not in local_relation: local_relation = '{}:{}'.format(self.name, local_relation) return await self.model.add_relation(local_relation, remote_relation)
[ "async", "def", "add_relation", "(", "self", ",", "local_relation", ",", "remote_relation", ")", ":", "if", "':'", "not", "in", "local_relation", ":", "local_relation", "=", "'{}:{}'", ".", "format", "(", "self", ".", "name", ",", "local_relation", ")", "ret...
Add a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]'
[ "Add", "a", "relation", "to", "another", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L91-L102
train
25,271
juju/python-libjuju
juju/application.py
Application.add_unit
async def add_unit(self, count=1, to=None): """Add one or more units to this application. :param int count: Number of units to add :param str to: Placement directive, e.g.:: '23' - machine 23 'lxc:7' - new lxc container on machine 7 '24/lxc/3' - lxc container 3 or machine 24 If None, a new machine is provisioned. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Adding %s unit%s to %s', count, '' if count == 1 else 's', self.name) result = await app_facade.AddUnits( application=self.name, placement=parse_placement(to) if to else None, num_units=count, ) return await asyncio.gather(*[ asyncio.ensure_future(self.model._wait_for_new('unit', unit_id)) for unit_id in result.units ])
python
async def add_unit(self, count=1, to=None): """Add one or more units to this application. :param int count: Number of units to add :param str to: Placement directive, e.g.:: '23' - machine 23 'lxc:7' - new lxc container on machine 7 '24/lxc/3' - lxc container 3 or machine 24 If None, a new machine is provisioned. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Adding %s unit%s to %s', count, '' if count == 1 else 's', self.name) result = await app_facade.AddUnits( application=self.name, placement=parse_placement(to) if to else None, num_units=count, ) return await asyncio.gather(*[ asyncio.ensure_future(self.model._wait_for_new('unit', unit_id)) for unit_id in result.units ])
[ "async", "def", "add_unit", "(", "self", ",", "count", "=", "1", ",", "to", "=", "None", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Adding %s u...
Add one or more units to this application. :param int count: Number of units to add :param str to: Placement directive, e.g.:: '23' - machine 23 'lxc:7' - new lxc container on machine 7 '24/lxc/3' - lxc container 3 or machine 24 If None, a new machine is provisioned.
[ "Add", "one", "or", "more", "units", "to", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L104-L131
train
25,272
juju/python-libjuju
juju/application.py
Application.destroy_relation
async def destroy_relation(self, local_relation, remote_relation): """Remove a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]' """ if ':' not in local_relation: local_relation = '{}:{}'.format(self.name, local_relation) app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Destroying relation %s <-> %s', local_relation, remote_relation) return await app_facade.DestroyRelation([ local_relation, remote_relation])
python
async def destroy_relation(self, local_relation, remote_relation): """Remove a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]' """ if ':' not in local_relation: local_relation = '{}:{}'.format(self.name, local_relation) app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Destroying relation %s <-> %s', local_relation, remote_relation) return await app_facade.DestroyRelation([ local_relation, remote_relation])
[ "async", "def", "destroy_relation", "(", "self", ",", "local_relation", ",", "remote_relation", ")", ":", "if", "':'", "not", "in", "local_relation", ":", "local_relation", "=", "'{}:{}'", ".", "format", "(", "self", ".", "name", ",", "local_relation", ")", ...
Remove a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]'
[ "Remove", "a", "relation", "to", "another", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L184-L201
train
25,273
juju/python-libjuju
juju/application.py
Application.destroy
async def destroy(self): """Remove this application from the model. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Destroying %s', self.name) return await app_facade.Destroy(self.name)
python
async def destroy(self): """Remove this application from the model. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Destroying %s', self.name) return await app_facade.Destroy(self.name)
[ "async", "def", "destroy", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Destroying %s'", ",", "self", ".", "name", ")", "return", "awa...
Remove this application from the model.
[ "Remove", "this", "application", "from", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L211-L220
train
25,274
juju/python-libjuju
juju/application.py
Application.expose
async def expose(self): """Make this application publicly available over the network. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Exposing %s', self.name) return await app_facade.Expose(self.name)
python
async def expose(self): """Make this application publicly available over the network. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Exposing %s', self.name) return await app_facade.Expose(self.name)
[ "async", "def", "expose", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Exposing %s'", ",", "self", ".", "name", ")", "return", "await"...
Make this application publicly available over the network.
[ "Make", "this", "application", "publicly", "available", "over", "the", "network", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L223-L232
train
25,275
juju/python-libjuju
juju/application.py
Application.get_config
async def get_config(self): """Return the configuration settings dict for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Getting config for %s', self.name) return (await app_facade.Get(self.name)).config
python
async def get_config(self): """Return the configuration settings dict for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Getting config for %s', self.name) return (await app_facade.Get(self.name)).config
[ "async", "def", "get_config", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Getting config for %s'", ",", "self", ".", "name", ")", "retu...
Return the configuration settings dict for this application.
[ "Return", "the", "configuration", "settings", "dict", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L234-L243
train
25,276
juju/python-libjuju
juju/application.py
Application.get_constraints
async def get_constraints(self): """Return the machine constraints dict for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Getting constraints for %s', self.name) result = (await app_facade.Get(self.name)).constraints return vars(result) if result else result
python
async def get_constraints(self): """Return the machine constraints dict for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Getting constraints for %s', self.name) result = (await app_facade.Get(self.name)).constraints return vars(result) if result else result
[ "async", "def", "get_constraints", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Getting constraints for %s'", ",", "self", ".", "name", ")...
Return the machine constraints dict for this application.
[ "Return", "the", "machine", "constraints", "dict", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L245-L255
train
25,277
juju/python-libjuju
juju/application.py
Application.get_actions
async def get_actions(self, schema=False): """Get actions defined for this application. :param bool schema: Return the full action schema :return dict: The charms actions, empty dict if none are defined. """ actions = {} entity = [{"tag": self.tag}] action_facade = client.ActionFacade.from_connection(self.connection) results = ( await action_facade.ApplicationsCharmsActions(entity)).results for result in results: if result.application_tag == self.tag and result.actions: actions = result.actions break if not schema: actions = {k: v['description'] for k, v in actions.items()} return actions
python
async def get_actions(self, schema=False): """Get actions defined for this application. :param bool schema: Return the full action schema :return dict: The charms actions, empty dict if none are defined. """ actions = {} entity = [{"tag": self.tag}] action_facade = client.ActionFacade.from_connection(self.connection) results = ( await action_facade.ApplicationsCharmsActions(entity)).results for result in results: if result.application_tag == self.tag and result.actions: actions = result.actions break if not schema: actions = {k: v['description'] for k, v in actions.items()} return actions
[ "async", "def", "get_actions", "(", "self", ",", "schema", "=", "False", ")", ":", "actions", "=", "{", "}", "entity", "=", "[", "{", "\"tag\"", ":", "self", ".", "tag", "}", "]", "action_facade", "=", "client", ".", "ActionFacade", ".", "from_connecti...
Get actions defined for this application. :param bool schema: Return the full action schema :return dict: The charms actions, empty dict if none are defined.
[ "Get", "actions", "defined", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L257-L274
train
25,278
juju/python-libjuju
juju/application.py
Application.get_resources
async def get_resources(self): """Return resources for this application. Returns a dict mapping resource name to :class:`~juju._definitions.CharmResource` instances. """ facade = client.ResourcesFacade.from_connection(self.connection) response = await facade.ListResources([client.Entity(self.tag)]) resources = dict() for result in response.results: for resource in result.charm_store_resources or []: resources[resource.name] = resource for resource in result.resources or []: if resource.charmresource: resource = resource.charmresource resources[resource.name] = resource return resources
python
async def get_resources(self): """Return resources for this application. Returns a dict mapping resource name to :class:`~juju._definitions.CharmResource` instances. """ facade = client.ResourcesFacade.from_connection(self.connection) response = await facade.ListResources([client.Entity(self.tag)]) resources = dict() for result in response.results: for resource in result.charm_store_resources or []: resources[resource.name] = resource for resource in result.resources or []: if resource.charmresource: resource = resource.charmresource resources[resource.name] = resource return resources
[ "async", "def", "get_resources", "(", "self", ")", ":", "facade", "=", "client", ".", "ResourcesFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "response", "=", "await", "facade", ".", "ListResources", "(", "[", "client", ".", "Entity",...
Return resources for this application. Returns a dict mapping resource name to :class:`~juju._definitions.CharmResource` instances.
[ "Return", "resources", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L276-L293
train
25,279
juju/python-libjuju
juju/application.py
Application.run
async def run(self, command, timeout=None): """Run command on all units for this application. :param str command: The command to run :param int timeout: Time to wait before command is considered failed """ action = client.ActionFacade.from_connection(self.connection) log.debug( 'Running `%s` on all units of %s', command, self.name) # TODO this should return a list of Actions return await action.Run( [self.name], command, [], timeout, [], )
python
async def run(self, command, timeout=None): """Run command on all units for this application. :param str command: The command to run :param int timeout: Time to wait before command is considered failed """ action = client.ActionFacade.from_connection(self.connection) log.debug( 'Running `%s` on all units of %s', command, self.name) # TODO this should return a list of Actions return await action.Run( [self.name], command, [], timeout, [], )
[ "async", "def", "run", "(", "self", ",", "command", ",", "timeout", "=", "None", ")", ":", "action", "=", "client", ".", "ActionFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Running `%s` on all units of %s'...
Run command on all units for this application. :param str command: The command to run :param int timeout: Time to wait before command is considered failed
[ "Run", "command", "on", "all", "units", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L295-L314
train
25,280
juju/python-libjuju
juju/application.py
Application.set_config
async def set_config(self, config): """Set configuration options for this application. :param config: Dict of configuration to set """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Setting config for %s: %s', self.name, config) return await app_facade.Set(self.name, config)
python
async def set_config(self, config): """Set configuration options for this application. :param config: Dict of configuration to set """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Setting config for %s: %s', self.name, config) return await app_facade.Set(self.name, config)
[ "async", "def", "set_config", "(", "self", ",", "config", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Setting config for %s: %s'", ",", "self", ".", ...
Set configuration options for this application. :param config: Dict of configuration to set
[ "Set", "configuration", "options", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L332-L342
train
25,281
juju/python-libjuju
juju/application.py
Application.reset_config
async def reset_config(self, to_default): """ Restore application config to default values. :param list to_default: A list of config options to be reset to their default value. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Restoring default config for %s: %s', self.name, to_default) return await app_facade.Unset(self.name, to_default)
python
async def reset_config(self, to_default): """ Restore application config to default values. :param list to_default: A list of config options to be reset to their default value. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Restoring default config for %s: %s', self.name, to_default) return await app_facade.Unset(self.name, to_default)
[ "async", "def", "reset_config", "(", "self", ",", "to_default", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Restoring default config for %s: %s'", ",", ...
Restore application config to default values. :param list to_default: A list of config options to be reset to their default value.
[ "Restore", "application", "config", "to", "default", "values", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L344-L356
train
25,282
juju/python-libjuju
juju/application.py
Application.set_constraints
async def set_constraints(self, constraints): """Set machine constraints for this application. :param dict constraints: Dict of machine constraints """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Setting constraints for %s: %s', self.name, constraints) return await app_facade.SetConstraints(self.name, constraints)
python
async def set_constraints(self, constraints): """Set machine constraints for this application. :param dict constraints: Dict of machine constraints """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Setting constraints for %s: %s', self.name, constraints) return await app_facade.SetConstraints(self.name, constraints)
[ "async", "def", "set_constraints", "(", "self", ",", "constraints", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Setting constraints for %s: %s'", ",", "...
Set machine constraints for this application. :param dict constraints: Dict of machine constraints
[ "Set", "machine", "constraints", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L358-L369
train
25,283
juju/python-libjuju
juju/application.py
Application.unexpose
async def unexpose(self): """Remove public availability over the network for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Unexposing %s', self.name) return await app_facade.Unexpose(self.name)
python
async def unexpose(self): """Remove public availability over the network for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Unexposing %s', self.name) return await app_facade.Unexpose(self.name)
[ "async", "def", "unexpose", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Unexposing %s'", ",", "self", ".", "name", ")", "return", "aw...
Remove public availability over the network for this application.
[ "Remove", "public", "availability", "over", "the", "network", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L388-L397
train
25,284
juju/python-libjuju
juju/client/facade.py
write_client
def write_client(captures, options): """ Write the TypeFactory classes to _client.py, along with some imports and tables so that we can look up versioned Facades. """ with open("{}/_client.py".format(options.output_dir), "w") as f: f.write(HEADER) f.write("from juju.client._definitions import *\n\n") clients = ", ".join("_client{}".format(v) for v in captures) f.write("from juju.client import " + clients + "\n\n") f.write(CLIENT_TABLE.format(clients=",\n ".join( ['"{}": _client{}'.format(v, v) for v in captures]))) f.write(LOOKUP_FACADE) f.write(TYPE_FACTORY) for key in sorted([k for k in factories.keys() if "Facade" in k]): print(factories[key], file=f)
python
def write_client(captures, options): """ Write the TypeFactory classes to _client.py, along with some imports and tables so that we can look up versioned Facades. """ with open("{}/_client.py".format(options.output_dir), "w") as f: f.write(HEADER) f.write("from juju.client._definitions import *\n\n") clients = ", ".join("_client{}".format(v) for v in captures) f.write("from juju.client import " + clients + "\n\n") f.write(CLIENT_TABLE.format(clients=",\n ".join( ['"{}": _client{}'.format(v, v) for v in captures]))) f.write(LOOKUP_FACADE) f.write(TYPE_FACTORY) for key in sorted([k for k in factories.keys() if "Facade" in k]): print(factories[key], file=f)
[ "def", "write_client", "(", "captures", ",", "options", ")", ":", "with", "open", "(", "\"{}/_client.py\"", ".", "format", "(", "options", ".", "output_dir", ")", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "HEADER", ")", "f", ".", "wr...
Write the TypeFactory classes to _client.py, along with some imports and tables so that we can look up versioned Facades.
[ "Write", "the", "TypeFactory", "classes", "to", "_client", ".", "py", "along", "with", "some", "imports", "and", "tables", "so", "that", "we", "can", "look", "up", "versioned", "Facades", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/facade.py#L733-L749
train
25,285
juju/python-libjuju
juju/client/facade.py
KindRegistry.lookup
def lookup(self, name, version=None): """If version is omitted, max version is used""" versions = self.get(name) if not versions: return None if version: return versions[version] return versions[max(versions)]
python
def lookup(self, name, version=None): """If version is omitted, max version is used""" versions = self.get(name) if not versions: return None if version: return versions[version] return versions[max(versions)]
[ "def", "lookup", "(", "self", ",", "name", ",", "version", "=", "None", ")", ":", "versions", "=", "self", ".", "get", "(", "name", ")", "if", "not", "versions", ":", "return", "None", "if", "version", ":", "return", "versions", "[", "version", "]", ...
If version is omitted, max version is used
[ "If", "version", "is", "omitted", "max", "version", "is", "used" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/facade.py#L110-L117
train
25,286
cloudify-cosmo/wagon
wagon.py
install_package
def install_package(package, wheels_path, venv=None, requirement_files=None, upgrade=False, install_args=None): """Install a Python package. Can specify a specific version. Can specify a prerelease. Can specify a venv to install in. Can specify a list of paths or urls to requirement txt files. Can specify a local wheels_path to use for offline installation. Can request an upgrade. """ requirement_files = requirement_files or [] logger.info('Installing %s...', package) if venv and not os.path.isdir(venv): raise WagonError('virtualenv {0} does not exist'.format(venv)) pip_command = _construct_pip_command( package, wheels_path, venv, requirement_files, upgrade, install_args) if IS_VIRTUALENV and not venv: logger.info('Installing within current virtualenv') result = _run(pip_command) if not result.returncode == 0: raise WagonError('Could not install package: {0} ({1})'.format( package, result.aggr_stderr))
python
def install_package(package, wheels_path, venv=None, requirement_files=None, upgrade=False, install_args=None): """Install a Python package. Can specify a specific version. Can specify a prerelease. Can specify a venv to install in. Can specify a list of paths or urls to requirement txt files. Can specify a local wheels_path to use for offline installation. Can request an upgrade. """ requirement_files = requirement_files or [] logger.info('Installing %s...', package) if venv and not os.path.isdir(venv): raise WagonError('virtualenv {0} does not exist'.format(venv)) pip_command = _construct_pip_command( package, wheels_path, venv, requirement_files, upgrade, install_args) if IS_VIRTUALENV and not venv: logger.info('Installing within current virtualenv') result = _run(pip_command) if not result.returncode == 0: raise WagonError('Could not install package: {0} ({1})'.format( package, result.aggr_stderr))
[ "def", "install_package", "(", "package", ",", "wheels_path", ",", "venv", "=", "None", ",", "requirement_files", "=", "None", ",", "upgrade", "=", "False", ",", "install_args", "=", "None", ")", ":", "requirement_files", "=", "requirement_files", "or", "[", ...
Install a Python package. Can specify a specific version. Can specify a prerelease. Can specify a venv to install in. Can specify a list of paths or urls to requirement txt files. Can specify a local wheels_path to use for offline installation. Can request an upgrade.
[ "Install", "a", "Python", "package", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L247-L282
train
25,287
cloudify-cosmo/wagon
wagon.py
_get_platform_for_set_of_wheels
def _get_platform_for_set_of_wheels(wheels_path): """For any set of wheel files, extracts a single platform. Since a set of wheels created or downloaded on one machine can only be for a single platform, if any wheel in the set has a platform which is not `any`, it will be used with one exception: In Linux, a wagon can contain wheels for both manylinux1 and linux. If, at any point we find that a wheel has `linux` as a platform, it will be used since it means it doesn't cross-fit all distros. If a platform other than `any` was not found, `any` will be assumed """ real_platform = '' for wheel in _get_downloaded_wheels(wheels_path): platform = _get_platform_from_wheel_name( os.path.join(wheels_path, wheel)) if 'linux' in platform and 'manylinux' not in platform: # Means either linux_x64_86 or linux_i686 on all wheels # If, at any point, a wheel matches this, it will be # returned so it'll only match that platform. return platform elif platform != ALL_PLATFORMS_TAG: # Means it can be either Windows, OSX or manylinux1 on all wheels real_platform = platform return real_platform or ALL_PLATFORMS_TAG
python
def _get_platform_for_set_of_wheels(wheels_path): """For any set of wheel files, extracts a single platform. Since a set of wheels created or downloaded on one machine can only be for a single platform, if any wheel in the set has a platform which is not `any`, it will be used with one exception: In Linux, a wagon can contain wheels for both manylinux1 and linux. If, at any point we find that a wheel has `linux` as a platform, it will be used since it means it doesn't cross-fit all distros. If a platform other than `any` was not found, `any` will be assumed """ real_platform = '' for wheel in _get_downloaded_wheels(wheels_path): platform = _get_platform_from_wheel_name( os.path.join(wheels_path, wheel)) if 'linux' in platform and 'manylinux' not in platform: # Means either linux_x64_86 or linux_i686 on all wheels # If, at any point, a wheel matches this, it will be # returned so it'll only match that platform. return platform elif platform != ALL_PLATFORMS_TAG: # Means it can be either Windows, OSX or manylinux1 on all wheels real_platform = platform return real_platform or ALL_PLATFORMS_TAG
[ "def", "_get_platform_for_set_of_wheels", "(", "wheels_path", ")", ":", "real_platform", "=", "''", "for", "wheel", "in", "_get_downloaded_wheels", "(", "wheels_path", ")", ":", "platform", "=", "_get_platform_from_wheel_name", "(", "os", ".", "path", ".", "join", ...
For any set of wheel files, extracts a single platform. Since a set of wheels created or downloaded on one machine can only be for a single platform, if any wheel in the set has a platform which is not `any`, it will be used with one exception: In Linux, a wagon can contain wheels for both manylinux1 and linux. If, at any point we find that a wheel has `linux` as a platform, it will be used since it means it doesn't cross-fit all distros. If a platform other than `any` was not found, `any` will be assumed
[ "For", "any", "set", "of", "wheel", "files", "extracts", "a", "single", "platform", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L377-L404
train
25,288
cloudify-cosmo/wagon
wagon.py
_get_os_properties
def _get_os_properties(): """Retrieve distribution properties. **Note that platform.linux_distribution and platform.dist are deprecated and will be removed in Python 3.7. By that time, distro will become mandatory. """ if IS_DISTRO_INSTALLED: return distro.linux_distribution(full_distribution_name=False) return platform.linux_distribution(full_distribution_name=False)
python
def _get_os_properties(): """Retrieve distribution properties. **Note that platform.linux_distribution and platform.dist are deprecated and will be removed in Python 3.7. By that time, distro will become mandatory. """ if IS_DISTRO_INSTALLED: return distro.linux_distribution(full_distribution_name=False) return platform.linux_distribution(full_distribution_name=False)
[ "def", "_get_os_properties", "(", ")", ":", "if", "IS_DISTRO_INSTALLED", ":", "return", "distro", ".", "linux_distribution", "(", "full_distribution_name", "=", "False", ")", "return", "platform", ".", "linux_distribution", "(", "full_distribution_name", "=", "False",...
Retrieve distribution properties. **Note that platform.linux_distribution and platform.dist are deprecated and will be removed in Python 3.7. By that time, distro will become mandatory.
[ "Retrieve", "distribution", "properties", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L416-L425
train
25,289
cloudify-cosmo/wagon
wagon.py
_get_env_bin_path
def _get_env_bin_path(env_path): """Return the bin path for a virtualenv This provides a fallback for a situation in which you're trying to use the script and create a virtualenv from within a virtualenv in which virtualenv isn't installed and so is not importable. """ if IS_VIRTUALENV_INSTALLED: path = virtualenv.path_locations(env_path)[3] else: path = os.path.join(env_path, 'Scripts' if IS_WIN else 'bin') return r'{0}'.format(path)
python
def _get_env_bin_path(env_path): """Return the bin path for a virtualenv This provides a fallback for a situation in which you're trying to use the script and create a virtualenv from within a virtualenv in which virtualenv isn't installed and so is not importable. """ if IS_VIRTUALENV_INSTALLED: path = virtualenv.path_locations(env_path)[3] else: path = os.path.join(env_path, 'Scripts' if IS_WIN else 'bin') return r'{0}'.format(path)
[ "def", "_get_env_bin_path", "(", "env_path", ")", ":", "if", "IS_VIRTUALENV_INSTALLED", ":", "path", "=", "virtualenv", ".", "path_locations", "(", "env_path", ")", "[", "3", "]", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "env_path", ...
Return the bin path for a virtualenv This provides a fallback for a situation in which you're trying to use the script and create a virtualenv from within a virtualenv in which virtualenv isn't installed and so is not importable.
[ "Return", "the", "bin", "path", "for", "a", "virtualenv" ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L428-L440
train
25,290
cloudify-cosmo/wagon
wagon.py
_generate_metadata_file
def _generate_metadata_file(workdir, archive_name, platform, python_versions, package_name, package_version, build_tag, package_source, wheels): """Generate a metadata file for the package. """ logger.debug('Generating Metadata...') metadata = { 'created_by_wagon_version': _get_wagon_version(), 'archive_name': archive_name, 'supported_platform': platform, 'supported_python_versions': python_versions, 'build_server_os_properties': { 'distribution': None, 'distribution_version': None, 'distribution_release': None, }, 'package_name': package_name, 'package_version': package_version, 'package_build_tag': build_tag, 'package_source': package_source, 'wheels': wheels, } if IS_LINUX and platform != ALL_PLATFORMS_TAG: distribution, version, release = _get_os_properties() metadata.update( {'build_server_os_properties': { 'distribution': distribution.lower(), 'distribution_version': version.lower(), 'distribution_release': release.lower() }}) formatted_metadata = json.dumps(metadata, indent=4, sort_keys=True) if is_verbose(): logger.debug('Metadata is: %s', formatted_metadata) output_path = os.path.join(workdir, METADATA_FILE_NAME) with open(output_path, 'w') as f: logger.debug('Writing metadata to file: %s', output_path) f.write(formatted_metadata)
python
def _generate_metadata_file(workdir, archive_name, platform, python_versions, package_name, package_version, build_tag, package_source, wheels): """Generate a metadata file for the package. """ logger.debug('Generating Metadata...') metadata = { 'created_by_wagon_version': _get_wagon_version(), 'archive_name': archive_name, 'supported_platform': platform, 'supported_python_versions': python_versions, 'build_server_os_properties': { 'distribution': None, 'distribution_version': None, 'distribution_release': None, }, 'package_name': package_name, 'package_version': package_version, 'package_build_tag': build_tag, 'package_source': package_source, 'wheels': wheels, } if IS_LINUX and platform != ALL_PLATFORMS_TAG: distribution, version, release = _get_os_properties() metadata.update( {'build_server_os_properties': { 'distribution': distribution.lower(), 'distribution_version': version.lower(), 'distribution_release': release.lower() }}) formatted_metadata = json.dumps(metadata, indent=4, sort_keys=True) if is_verbose(): logger.debug('Metadata is: %s', formatted_metadata) output_path = os.path.join(workdir, METADATA_FILE_NAME) with open(output_path, 'w') as f: logger.debug('Writing metadata to file: %s', output_path) f.write(formatted_metadata)
[ "def", "_generate_metadata_file", "(", "workdir", ",", "archive_name", ",", "platform", ",", "python_versions", ",", "package_name", ",", "package_version", ",", "build_tag", ",", "package_source", ",", "wheels", ")", ":", "logger", ".", "debug", "(", "'Generating...
Generate a metadata file for the package.
[ "Generate", "a", "metadata", "file", "for", "the", "package", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L513-L556
train
25,291
cloudify-cosmo/wagon
wagon.py
_set_archive_name
def _set_archive_name(package_name, package_version, python_versions, platform, build_tag=''): """Set the format of the output archive file. We should aspire for the name of the archive to be as compatible as possible with the wheel naming convention described here: https://www.python.org/dev/peps/pep-0491/#file-name-convention, as we're basically providing a "wheel" of our package. """ package_name = package_name.replace('-', '_') python_versions = '.'.join(python_versions) archive_name_tags = [ package_name, package_version, python_versions, 'none', platform, ] if build_tag: archive_name_tags.insert(2, build_tag) archive_name = '{0}.wgn'.format('-'.join(archive_name_tags)) return archive_name
python
def _set_archive_name(package_name, package_version, python_versions, platform, build_tag=''): """Set the format of the output archive file. We should aspire for the name of the archive to be as compatible as possible with the wheel naming convention described here: https://www.python.org/dev/peps/pep-0491/#file-name-convention, as we're basically providing a "wheel" of our package. """ package_name = package_name.replace('-', '_') python_versions = '.'.join(python_versions) archive_name_tags = [ package_name, package_version, python_versions, 'none', platform, ] if build_tag: archive_name_tags.insert(2, build_tag) archive_name = '{0}.wgn'.format('-'.join(archive_name_tags)) return archive_name
[ "def", "_set_archive_name", "(", "package_name", ",", "package_version", ",", "python_versions", ",", "platform", ",", "build_tag", "=", "''", ")", ":", "package_name", "=", "package_name", ".", "replace", "(", "'-'", ",", "'_'", ")", "python_versions", "=", "...
Set the format of the output archive file. We should aspire for the name of the archive to be as compatible as possible with the wheel naming convention described here: https://www.python.org/dev/peps/pep-0491/#file-name-convention, as we're basically providing a "wheel" of our package.
[ "Set", "the", "format", "of", "the", "output", "archive", "file", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L559-L587
train
25,292
cloudify-cosmo/wagon
wagon.py
get_source_name_and_version
def get_source_name_and_version(source): """Retrieve the source package's name and version. If the source is a path, the name and version will be retrieved by querying the setup.py file in the path. If the source is PACKAGE_NAME==PACKAGE_VERSION, they will be used as the name and version. If the source is PACKAGE_NAME, the version will be extracted from the wheel of the latest version. """ if os.path.isfile(os.path.join(source, 'setup.py')): package_name, package_version = \ _get_name_and_version_from_setup(source) # TODO: maybe we don't want to be that explicit and allow using >= # elif any(symbol in source for symbol in ['==', '>=', '<=']): elif '==' in source: base_name, package_version = source.split('==') package_name = _get_package_info_from_pypi(base_name)['name'] else: package_info = _get_package_info_from_pypi(source) package_name = package_info['name'] package_version = package_info['version'] return package_name, package_version
python
def get_source_name_and_version(source): """Retrieve the source package's name and version. If the source is a path, the name and version will be retrieved by querying the setup.py file in the path. If the source is PACKAGE_NAME==PACKAGE_VERSION, they will be used as the name and version. If the source is PACKAGE_NAME, the version will be extracted from the wheel of the latest version. """ if os.path.isfile(os.path.join(source, 'setup.py')): package_name, package_version = \ _get_name_and_version_from_setup(source) # TODO: maybe we don't want to be that explicit and allow using >= # elif any(symbol in source for symbol in ['==', '>=', '<=']): elif '==' in source: base_name, package_version = source.split('==') package_name = _get_package_info_from_pypi(base_name)['name'] else: package_info = _get_package_info_from_pypi(source) package_name = package_info['name'] package_version = package_info['version'] return package_name, package_version
[ "def", "get_source_name_and_version", "(", "source", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "source", ",", "'setup.py'", ")", ")", ":", "package_name", ",", "package_version", "=", "_get_name_and_version_f...
Retrieve the source package's name and version. If the source is a path, the name and version will be retrieved by querying the setup.py file in the path. If the source is PACKAGE_NAME==PACKAGE_VERSION, they will be used as the name and version. If the source is PACKAGE_NAME, the version will be extracted from the wheel of the latest version.
[ "Retrieve", "the", "source", "package", "s", "name", "and", "version", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L590-L614
train
25,293
cloudify-cosmo/wagon
wagon.py
get_source
def get_source(source): """Return a pip-installable source If the source is a url to a package's tar file, this will download the source and extract it to a temporary directory. If the source is neither a url nor a local path, and is not provided as PACKAGE_NAME==PACKAGE_VERSION, the provided source string will be regarded as the source, which, by default, will assume that the string is a name of a package in PyPI. """ def extract_source(source, destination): if tarfile.is_tarfile(source): _untar(source, destination) elif zipfile.is_zipfile(source): _unzip(source, destination) else: raise WagonError( 'Failed to extract {0}. Please verify that the ' 'provided file is a valid zip or tar.gz ' 'archive'.format(source)) source = os.path.join( destination, [d for d in next(os.walk(destination))[1]][0]) return source logger.debug('Retrieving source...') if '://' in source: split = source.split('://') schema = split[0] if schema in ['file', 'http', 'https']: tmpdir = tempfile.mkdtemp() fd, tmpfile = tempfile.mkstemp() os.close(fd) try: _download_file(source, tmpfile) source = extract_source(tmpfile, tmpdir) finally: os.remove(tmpfile) else: raise WagonError('Source URL type {0} is not supported'.format( schema)) elif os.path.isfile(source): tmpdir = tempfile.mkdtemp() source = extract_source(source, tmpdir) elif os.path.isdir(os.path.expanduser(source)): source = os.path.expanduser(source) elif '==' in source: base_name, version = source.split('==') source = _get_package_info_from_pypi(base_name)['name'] source = '{0}=={1}'.format(source, version) else: source = _get_package_info_from_pypi(source)['name'] logger.debug('Source is: %s', source) return source
python
def get_source(source): """Return a pip-installable source If the source is a url to a package's tar file, this will download the source and extract it to a temporary directory. If the source is neither a url nor a local path, and is not provided as PACKAGE_NAME==PACKAGE_VERSION, the provided source string will be regarded as the source, which, by default, will assume that the string is a name of a package in PyPI. """ def extract_source(source, destination): if tarfile.is_tarfile(source): _untar(source, destination) elif zipfile.is_zipfile(source): _unzip(source, destination) else: raise WagonError( 'Failed to extract {0}. Please verify that the ' 'provided file is a valid zip or tar.gz ' 'archive'.format(source)) source = os.path.join( destination, [d for d in next(os.walk(destination))[1]][0]) return source logger.debug('Retrieving source...') if '://' in source: split = source.split('://') schema = split[0] if schema in ['file', 'http', 'https']: tmpdir = tempfile.mkdtemp() fd, tmpfile = tempfile.mkstemp() os.close(fd) try: _download_file(source, tmpfile) source = extract_source(tmpfile, tmpdir) finally: os.remove(tmpfile) else: raise WagonError('Source URL type {0} is not supported'.format( schema)) elif os.path.isfile(source): tmpdir = tempfile.mkdtemp() source = extract_source(source, tmpdir) elif os.path.isdir(os.path.expanduser(source)): source = os.path.expanduser(source) elif '==' in source: base_name, version = source.split('==') source = _get_package_info_from_pypi(base_name)['name'] source = '{0}=={1}'.format(source, version) else: source = _get_package_info_from_pypi(source)['name'] logger.debug('Source is: %s', source) return source
[ "def", "get_source", "(", "source", ")", ":", "def", "extract_source", "(", "source", ",", "destination", ")", ":", "if", "tarfile", ".", "is_tarfile", "(", "source", ")", ":", "_untar", "(", "source", ",", "destination", ")", "elif", "zipfile", ".", "is...
Return a pip-installable source If the source is a url to a package's tar file, this will download the source and extract it to a temporary directory. If the source is neither a url nor a local path, and is not provided as PACKAGE_NAME==PACKAGE_VERSION, the provided source string will be regarded as the source, which, by default, will assume that the string is a name of a package in PyPI.
[ "Return", "a", "pip", "-", "installable", "source" ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L628-L682
train
25,294
cloudify-cosmo/wagon
wagon.py
create
def create(source, requirement_files=None, force=False, keep_wheels=False, archive_destination_dir='.', python_versions=None, validate_archive=False, wheel_args='', archive_format='zip', build_tag=''): """Create a Wagon archive and returns its path. Package name and version are extracted from the setup.py file of the `source` or from the PACKAGE_NAME==PACKAGE_VERSION if the source is a PyPI package. Supported `python_versions` must be in the format e.g [33, 27, 2, 3].. `force` will remove any excess dirs or archives before creation. `requirement_files` can be either a link/local path to a requirements.txt file or just `.`, in which case requirement files will be automatically extracted from either the GitHub archive URL or the local path provided provided in `source`. """ if validate_archive: _assert_virtualenv_is_installed() logger.info('Creating archive for %s...', source) processed_source = get_source(source) if os.path.isdir(processed_source) and not \ os.path.isfile(os.path.join(processed_source, 'setup.py')): raise WagonError( 'Source directory must contain a setup.py file') package_name, package_version = get_source_name_and_version( processed_source) tempdir = tempfile.mkdtemp() workdir = os.path.join(tempdir, package_name) wheels_path = os.path.join(workdir, DEFAULT_WHEELS_PATH) try: wheels = wheel( processed_source, requirement_files, wheels_path, wheel_args) finally: if processed_source != source: shutil.rmtree(processed_source, ignore_errors=True) platform = _get_platform_for_set_of_wheels(wheels_path) if is_verbose(): logger.debug('Platform is: %s', platform) python_versions = _set_python_versions(python_versions) if not os.path.isdir(archive_destination_dir): os.makedirs(archive_destination_dir) archive_name = _set_archive_name( package_name, package_version, python_versions, platform, build_tag) archive_path = os.path.join(archive_destination_dir, archive_name) _handle_output_file(archive_path, force) _generate_metadata_file( workdir, archive_name, platform, python_versions, package_name, package_version, build_tag, source, wheels) _create_wagon_archive(workdir, archive_path, archive_format) if not keep_wheels: logger.debug('Removing work directory...') shutil.rmtree(tempdir, ignore_errors=True) if validate_archive: validate(archive_path) logger.info('Wagon created successfully at: %s', archive_path) return archive_path
python
def create(source, requirement_files=None, force=False, keep_wheels=False, archive_destination_dir='.', python_versions=None, validate_archive=False, wheel_args='', archive_format='zip', build_tag=''): """Create a Wagon archive and returns its path. Package name and version are extracted from the setup.py file of the `source` or from the PACKAGE_NAME==PACKAGE_VERSION if the source is a PyPI package. Supported `python_versions` must be in the format e.g [33, 27, 2, 3].. `force` will remove any excess dirs or archives before creation. `requirement_files` can be either a link/local path to a requirements.txt file or just `.`, in which case requirement files will be automatically extracted from either the GitHub archive URL or the local path provided provided in `source`. """ if validate_archive: _assert_virtualenv_is_installed() logger.info('Creating archive for %s...', source) processed_source = get_source(source) if os.path.isdir(processed_source) and not \ os.path.isfile(os.path.join(processed_source, 'setup.py')): raise WagonError( 'Source directory must contain a setup.py file') package_name, package_version = get_source_name_and_version( processed_source) tempdir = tempfile.mkdtemp() workdir = os.path.join(tempdir, package_name) wheels_path = os.path.join(workdir, DEFAULT_WHEELS_PATH) try: wheels = wheel( processed_source, requirement_files, wheels_path, wheel_args) finally: if processed_source != source: shutil.rmtree(processed_source, ignore_errors=True) platform = _get_platform_for_set_of_wheels(wheels_path) if is_verbose(): logger.debug('Platform is: %s', platform) python_versions = _set_python_versions(python_versions) if not os.path.isdir(archive_destination_dir): os.makedirs(archive_destination_dir) archive_name = _set_archive_name( package_name, package_version, python_versions, platform, build_tag) archive_path = os.path.join(archive_destination_dir, archive_name) _handle_output_file(archive_path, force) _generate_metadata_file( workdir, archive_name, platform, python_versions, package_name, package_version, build_tag, source, wheels) _create_wagon_archive(workdir, archive_path, archive_format) if not keep_wheels: logger.debug('Removing work directory...') shutil.rmtree(tempdir, ignore_errors=True) if validate_archive: validate(archive_path) logger.info('Wagon created successfully at: %s', archive_path) return archive_path
[ "def", "create", "(", "source", ",", "requirement_files", "=", "None", ",", "force", "=", "False", ",", "keep_wheels", "=", "False", ",", "archive_destination_dir", "=", "'.'", ",", "python_versions", "=", "None", ",", "validate_archive", "=", "False", ",", ...
Create a Wagon archive and returns its path. Package name and version are extracted from the setup.py file of the `source` or from the PACKAGE_NAME==PACKAGE_VERSION if the source is a PyPI package. Supported `python_versions` must be in the format e.g [33, 27, 2, 3].. `force` will remove any excess dirs or archives before creation. `requirement_files` can be either a link/local path to a requirements.txt file or just `.`, in which case requirement files will be automatically extracted from either the GitHub archive URL or the local path provided provided in `source`.
[ "Create", "a", "Wagon", "archive", "and", "returns", "its", "path", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L691-L773
train
25,295
cloudify-cosmo/wagon
wagon.py
install
def install(source, venv=None, requirement_files=None, upgrade=False, ignore_platform=False, install_args=''): """Install a Wagon archive. This can install in a provided `venv` or in the current virtualenv in case one is currently active. `upgrade` is merely pip's upgrade. `ignore_platform` will allow to ignore the platform check, meaning that if an archive was created for a specific platform (e.g. win32), and the current platform is different, it will still attempt to install it. Platform check will fail on the following: If not linux and no platform match (e.g. win32 vs. darwin) If linux and: architecture doesn't match (e.g. manylinux1_x86_64 vs. linux_i686) wheel not manylinux and no platform match (linux_x86_64 vs. linux_i686) """ requirement_files = requirement_files or [] logger.info('Installing %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) def raise_unsupported_platform(machine_platform): # TODO: Print which platform is supported? raise WagonError( 'Platform unsupported for wagon ({0})'.format( machine_platform)) try: supported_platform = metadata['supported_platform'] if not ignore_platform and supported_platform != ALL_PLATFORMS_TAG: logger.debug( 'Validating Platform %s is supported...', supported_platform) machine_platform = get_platform() if not _is_platform_supported( supported_platform, machine_platform): raise_unsupported_platform(machine_platform) wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH) install_package( metadata['package_name'], wheels_path, venv, requirement_files, upgrade, install_args) finally: # Install can only be done on local or remote archives. # This means that a temporary directory is always created # with the sources to install within it. This is why we can allow # ourselves to delete the parent dir without worrying. # TODO: Make this even less dangerous by changing `get_source` # to return the directory to delete instead. Much safer. if processed_source != source: shutil.rmtree(os.path.dirname( processed_source), ignore_errors=True)
python
def install(source, venv=None, requirement_files=None, upgrade=False, ignore_platform=False, install_args=''): """Install a Wagon archive. This can install in a provided `venv` or in the current virtualenv in case one is currently active. `upgrade` is merely pip's upgrade. `ignore_platform` will allow to ignore the platform check, meaning that if an archive was created for a specific platform (e.g. win32), and the current platform is different, it will still attempt to install it. Platform check will fail on the following: If not linux and no platform match (e.g. win32 vs. darwin) If linux and: architecture doesn't match (e.g. manylinux1_x86_64 vs. linux_i686) wheel not manylinux and no platform match (linux_x86_64 vs. linux_i686) """ requirement_files = requirement_files or [] logger.info('Installing %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) def raise_unsupported_platform(machine_platform): # TODO: Print which platform is supported? raise WagonError( 'Platform unsupported for wagon ({0})'.format( machine_platform)) try: supported_platform = metadata['supported_platform'] if not ignore_platform and supported_platform != ALL_PLATFORMS_TAG: logger.debug( 'Validating Platform %s is supported...', supported_platform) machine_platform = get_platform() if not _is_platform_supported( supported_platform, machine_platform): raise_unsupported_platform(machine_platform) wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH) install_package( metadata['package_name'], wheels_path, venv, requirement_files, upgrade, install_args) finally: # Install can only be done on local or remote archives. # This means that a temporary directory is always created # with the sources to install within it. This is why we can allow # ourselves to delete the parent dir without worrying. # TODO: Make this even less dangerous by changing `get_source` # to return the directory to delete instead. Much safer. if processed_source != source: shutil.rmtree(os.path.dirname( processed_source), ignore_errors=True)
[ "def", "install", "(", "source", ",", "venv", "=", "None", ",", "requirement_files", "=", "None", ",", "upgrade", "=", "False", ",", "ignore_platform", "=", "False", ",", "install_args", "=", "''", ")", ":", "requirement_files", "=", "requirement_files", "or...
Install a Wagon archive. This can install in a provided `venv` or in the current virtualenv in case one is currently active. `upgrade` is merely pip's upgrade. `ignore_platform` will allow to ignore the platform check, meaning that if an archive was created for a specific platform (e.g. win32), and the current platform is different, it will still attempt to install it. Platform check will fail on the following: If not linux and no platform match (e.g. win32 vs. darwin) If linux and: architecture doesn't match (e.g. manylinux1_x86_64 vs. linux_i686) wheel not manylinux and no platform match (linux_x86_64 vs. linux_i686)
[ "Install", "a", "Wagon", "archive", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L791-L855
train
25,296
cloudify-cosmo/wagon
wagon.py
validate
def validate(source): """Validate a Wagon archive. Return True if succeeds, False otherwise. It also prints a list of all validation errors. This will test that some of the metadata is solid, that the required wheels are present within the archives and that the package is installable. Note that if the metadata file is corrupted, validation of the required wheels will be corrupted as well, since validation checks that the required wheels exist vs. the list of wheels supplied in the `wheels` key. """ _assert_virtualenv_is_installed() logger.info('Validating %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH) validation_errors = [] logger.debug('Verifying that all required files exist...') for wheel in metadata['wheels']: if not os.path.isfile(os.path.join(wheels_path, wheel)): validation_errors.append( '{0} is missing from the archive'.format(wheel)) logger.debug('Testing package installation...') tmpenv = _make_virtualenv() try: install(source=processed_source, venv=tmpenv) if not _check_installed(metadata['package_name'], tmpenv): validation_errors.append( '{0} failed to install (Reason unknown)'.format( metadata['package_name'])) finally: shutil.rmtree(tmpenv) if validation_errors: logger.info('Validation failed!') for error in validation_errors: logger.info(error) logger.info('Source can be found at: %s', processed_source) else: logger.info('Validation Passed!') if processed_source != source: shutil.rmtree(processed_source) return validation_errors
python
def validate(source): """Validate a Wagon archive. Return True if succeeds, False otherwise. It also prints a list of all validation errors. This will test that some of the metadata is solid, that the required wheels are present within the archives and that the package is installable. Note that if the metadata file is corrupted, validation of the required wheels will be corrupted as well, since validation checks that the required wheels exist vs. the list of wheels supplied in the `wheels` key. """ _assert_virtualenv_is_installed() logger.info('Validating %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH) validation_errors = [] logger.debug('Verifying that all required files exist...') for wheel in metadata['wheels']: if not os.path.isfile(os.path.join(wheels_path, wheel)): validation_errors.append( '{0} is missing from the archive'.format(wheel)) logger.debug('Testing package installation...') tmpenv = _make_virtualenv() try: install(source=processed_source, venv=tmpenv) if not _check_installed(metadata['package_name'], tmpenv): validation_errors.append( '{0} failed to install (Reason unknown)'.format( metadata['package_name'])) finally: shutil.rmtree(tmpenv) if validation_errors: logger.info('Validation failed!') for error in validation_errors: logger.info(error) logger.info('Source can be found at: %s', processed_source) else: logger.info('Validation Passed!') if processed_source != source: shutil.rmtree(processed_source) return validation_errors
[ "def", "validate", "(", "source", ")", ":", "_assert_virtualenv_is_installed", "(", ")", "logger", ".", "info", "(", "'Validating %s'", ",", "source", ")", "processed_source", "=", "get_source", "(", "source", ")", "metadata", "=", "_get_metadata", "(", "process...
Validate a Wagon archive. Return True if succeeds, False otherwise. It also prints a list of all validation errors. This will test that some of the metadata is solid, that the required wheels are present within the archives and that the package is installable. Note that if the metadata file is corrupted, validation of the required wheels will be corrupted as well, since validation checks that the required wheels exist vs. the list of wheels supplied in the `wheels` key.
[ "Validate", "a", "Wagon", "archive", ".", "Return", "True", "if", "succeeds", "False", "otherwise", ".", "It", "also", "prints", "a", "list", "of", "all", "validation", "errors", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L866-L914
train
25,297
cloudify-cosmo/wagon
wagon.py
show
def show(source): """Merely returns the metadata for the provided archive. """ if is_verbose(): logger.info('Retrieving Metadata for: %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) shutil.rmtree(processed_source) return metadata
python
def show(source): """Merely returns the metadata for the provided archive. """ if is_verbose(): logger.info('Retrieving Metadata for: %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) shutil.rmtree(processed_source) return metadata
[ "def", "show", "(", "source", ")", ":", "if", "is_verbose", "(", ")", ":", "logger", ".", "info", "(", "'Retrieving Metadata for: %s'", ",", "source", ")", "processed_source", "=", "get_source", "(", "source", ")", "metadata", "=", "_get_metadata", "(", "pro...
Merely returns the metadata for the provided archive.
[ "Merely", "returns", "the", "metadata", "for", "the", "provided", "archive", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L917-L925
train
25,298
scottjbarr/bitfinex
bitfinex/client.py
Client._convert_to_floats
def _convert_to_floats(self, data): """ Convert all values in a dict to floats """ for key, value in data.items(): data[key] = float(value) return data
python
def _convert_to_floats(self, data): """ Convert all values in a dict to floats """ for key, value in data.items(): data[key] = float(value) return data
[ "def", "_convert_to_floats", "(", "self", ",", "data", ")", ":", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "data", "[", "key", "]", "=", "float", "(", "value", ")", "return", "data" ]
Convert all values in a dict to floats
[ "Convert", "all", "values", "in", "a", "dict", "to", "floats" ]
03f7c71615fe38c2e28be0ebb761d3106ef0a51a
https://github.com/scottjbarr/bitfinex/blob/03f7c71615fe38c2e28be0ebb761d3106ef0a51a/bitfinex/client.py#L497-L504
train
25,299