code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def test_make_package_unsigned_dist(upload_settings, monkeypatch, caplog): """Create a PackageFile and print path, size, and Twine-generated signature.""" filename = helpers.NEW_WHEEL_FIXTURE expected_size = "21.9 KB" signatures = {} upload_settings.sign = True upload_settings.verbose = True ...
Create a PackageFile and print path, size, and Twine-generated signature.
test_make_package_unsigned_dist
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_make_package_attestations_flagged_but_missing(upload_settings): """Fail when the user requests attestations but does not supply any attestations.""" upload_settings.attestations = True with pytest.raises( exceptions.InvalidDistribution, match="Upload with attestations requested" ): ...
Fail when the user requests attestations but does not supply any attestations.
test_make_package_attestations_flagged_but_missing
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_successs_prints_release_urls(upload_settings, stub_repository, capsys): """Print PyPI release URLS for each uploaded package.""" stub_repository.release_urls = lambda packages: {RELEASE_URL, NEW_RELEASE_URL} result = upload.upload( upload_settings, [ helpers.WHEEL_FIXTU...
Print PyPI release URLS for each uploaded package.
test_successs_prints_release_urls
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_print_packages_if_verbose(upload_settings, caplog): """Print the path and file size of each distribution attempting to be uploaded.""" dists_to_upload = { helpers.WHEEL_FIXTURE: "15.4 KB", helpers.NEW_WHEEL_FIXTURE: "21.9 KB", helpers.SDIST_FIXTURE: "20.8 KB", helpers.NE...
Print the path and file size of each distribution attempting to be uploaded.
test_print_packages_if_verbose
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_print_response_if_verbose(upload_settings, stub_response, caplog): """Print details about the response from the repository.""" upload_settings.verbose = True result = upload.upload( upload_settings, [helpers.WHEEL_FIXTURE, helpers.SDIST_FIXTURE], ) assert result is None ...
Print details about the response from the repository.
test_print_response_if_verbose
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_success_with_pre_signed_distribution(upload_settings, stub_repository, caplog): """Add GPG signature provided by user to uploaded package.""" # Upload a pre-signed distribution result = upload.upload( upload_settings, [helpers.WHEEL_FIXTURE, helpers.WHEEL_FIXTURE + ".asc"] ) assert ...
Add GPG signature provided by user to uploaded package.
test_success_with_pre_signed_distribution
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_warns_potential_pgp_removal_on_3p_index( make_settings, stub_repository, caplog ): """Warn when a PGP signature is specified for upload to a third-party index.""" upload_settings = make_settings( """ [pypi] repository: https://example.com/not-a-real-index/ username:f...
Warn when a PGP signature is specified for upload to a third-party index.
test_warns_potential_pgp_removal_on_3p_index
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_exception_with_only_pre_signed_file(upload_settings, stub_repository): """Raise an exception when only a signed file is uploaded.""" # Upload only pre-signed file with pytest.raises(exceptions.InvalidDistribution) as err: upload.upload(upload_settings, [helpers.WHEEL_FIXTURE + ".asc"]) ...
Raise an exception when only a signed file is uploaded.
test_exception_with_only_pre_signed_file
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_success_when_gpg_is_run(upload_settings, stub_repository, monkeypatch): """Add GPG signature generated by gpg command to uploaded package.""" # Indicate that upload() should run_gpg() to generate the signature, which # we'll stub out to use WHEEL_FIXTURE + ".asc" upload_settings.sign = True ...
Add GPG signature generated by gpg command to uploaded package.
test_success_when_gpg_is_run
python
pypa/twine
tests/test_upload.py
https://github.com/pypa/twine/blob/master/tests/test_upload.py
Apache-2.0
def test_get_config_no_distutils(write_config_file): """Upload by default to PyPI if an index server is not set in .pypirc.""" config_file = write_config_file( """ [pypi] username = testuser password = testpassword """ ) assert utils.get_config(config_file) == { ...
Upload by default to PyPI if an index server is not set in .pypirc.
test_get_config_no_distutils
python
pypa/twine
tests/test_utils.py
https://github.com/pypa/twine/blob/master/tests/test_utils.py
Apache-2.0
def test_empty_userpass(write_config_file): """Suppress prompts if empty username and password are provided in .pypirc.""" config_file = write_config_file( """ [pypi] username= password= """ ) config = utils.get_config(config_file) pypi = config["pypi"] ...
Suppress prompts if empty username and password are provided in .pypirc.
test_empty_userpass
python
pypa/twine
tests/test_utils.py
https://github.com/pypa/twine/blob/master/tests/test_utils.py
Apache-2.0
def test_get_repository_config_with_invalid_url(config_file, repo_url, message): """Raise an exception for a URL with an invalid/missing scheme and/or host.""" with pytest.raises( exceptions.UnreachableRepositoryURLDetected, match=message, ): utils.get_repository_from_config(config_f...
Raise an exception for a URL with an invalid/missing scheme and/or host.
test_get_repository_config_with_invalid_url
python
pypa/twine
tests/test_utils.py
https://github.com/pypa/twine/blob/master/tests/test_utils.py
Apache-2.0
def test_get_repository_config_missing_repository(write_config_file): """Raise an exception when a custom repository isn't defined in .pypirc.""" config_file = write_config_file("") with pytest.raises( exceptions.InvalidConfiguration, match="Missing 'missing-repository'", ): util...
Raise an exception when a custom repository isn't defined in .pypirc.
test_get_repository_config_missing_repository
python
pypa/twine
tests/test_utils.py
https://github.com/pypa/twine/blob/master/tests/test_utils.py
Apache-2.0
def test_get_repository_config_invalid_syntax(write_config_file, invalid_config): """Raise an exception when the .pypirc has invalid syntax.""" config_file = write_config_file(invalid_config) with pytest.raises( exceptions.InvalidConfiguration, match="Malformed configuration", ): ...
Raise an exception when the .pypirc has invalid syntax.
test_get_repository_config_invalid_syntax
python
pypa/twine
tests/test_utils.py
https://github.com/pypa/twine/blob/master/tests/test_utils.py
Apache-2.0
def test_get_repository_config_missing_file(repository): """Raise an exception when a custom config file doesn't exist.""" with pytest.raises( exceptions.InvalidConfiguration, match=r"No such file.*missing-file", ): utils.get_repository_from_config("missing-file", repository)
Raise an exception when a custom config file doesn't exist.
test_get_repository_config_missing_file
python
pypa/twine
tests/test_utils.py
https://github.com/pypa/twine/blob/master/tests/test_utils.py
Apache-2.0
def test_check_status_code_for_missing_status_code( caplog, repo_url, verbose, make_settings, config_file ): """Print HTTP errors based on verbosity level.""" response = pretend.stub( status_code=403, url=repo_url, raise_for_status=pretend.raiser(requests.HTTPError), text="Fo...
Print HTTP errors based on verbosity level.
test_check_status_code_for_missing_status_code
python
pypa/twine
tests/test_utils.py
https://github.com/pypa/twine/blob/master/tests/test_utils.py
Apache-2.0
def test_get_file_size(size_in_bytes, formatted_size, monkeypatch): """Get the size of file as a string with units.""" monkeypatch.setattr(os.path, "getsize", lambda _: size_in_bytes) file_size = utils.get_file_size(size_in_bytes) assert file_size == formatted_size
Get the size of file as a string with units.
test_get_file_size
python
pypa/twine
tests/test_utils.py
https://github.com/pypa/twine/blob/master/tests/test_utils.py
Apache-2.0
def test_read_valid(example_wheel): """Parse metadata from a valid wheel file.""" metadata = example_wheel.read().decode().splitlines() assert "Name: twine" in metadata assert "Version: 1.5.0" in metadata
Parse metadata from a valid wheel file.
test_read_valid
python
pypa/twine
tests/test_wheel.py
https://github.com/pypa/twine/blob/master/tests/test_wheel.py
Apache-2.0
def test_read_non_existent_wheel_file_name(): """Raise an exception when wheel file doesn't exist.""" file_name = str(pathlib.Path("/foo/bar/baz.whl").resolve()) with pytest.raises( exceptions.InvalidDistribution, match=re.escape(f"No such file: {file_name}") ): wheel.Wheel(file_name).re...
Raise an exception when wheel file doesn't exist.
test_read_non_existent_wheel_file_name
python
pypa/twine
tests/test_wheel.py
https://github.com/pypa/twine/blob/master/tests/test_wheel.py
Apache-2.0
def test_read_invalid_wheel_extension(): """Raise an exception when file is missing .whl extension.""" file_name = str(pathlib.Path(__file__).parent / "fixtures" / "twine-1.5.0.tar.gz") with pytest.raises( exceptions.InvalidDistribution, match=re.escape(f"Not a known archive format for file:...
Raise an exception when file is missing .whl extension.
test_read_invalid_wheel_extension
python
pypa/twine
tests/test_wheel.py
https://github.com/pypa/twine/blob/master/tests/test_wheel.py
Apache-2.0
def test_read_wheel_empty_metadata(tmpdir): """Raise an exception when a wheel file is missing METADATA.""" whl_file = tmpdir.mkdir("wheel").join("not-a-wheel.whl") with zipfile.ZipFile(whl_file, "w") as zip_file: zip_file.writestr("METADATA", "") with pytest.raises( exceptions.InvalidD...
Raise an exception when a wheel file is missing METADATA.
test_read_wheel_empty_metadata
python
pypa/twine
tests/test_wheel.py
https://github.com/pypa/twine/blob/master/tests/test_wheel.py
Apache-2.0
def is_pypi(self) -> bool: """As of 2024-01-01, PyPI requires API tokens for uploads.""" return cast(str, self.config["repository"]).startswith( ( utils.DEFAULT_REPOSITORY, utils.TEST_REPOSITORY, ) )
As of 2024-01-01, PyPI requires API tokens for uploads.
is_pypi
python
pypa/twine
twine/auth.py
https://github.com/pypa/twine/blob/master/twine/auth.py
Apache-2.0
def metadata_dictionary(self) -> PackageMetadata: """Merge multiple sources of metadata into a single dictionary. Includes values from filename, PKG-INFO, hashers, and signature. """ data = PackageMetadata() for key, value in self.metadata.items(): field = _RAW_TO_PA...
Merge multiple sources of metadata into a single dictionary. Includes values from filename, PKG-INFO, hashers, and signature.
metadata_dictionary
python
pypa/twine
twine/package.py
https://github.com/pypa/twine/blob/master/twine/package.py
Apache-2.0
def __init__(self, filename: str) -> None: """Initialize our manager and hasher objects.""" self.filename = filename self._md5_hasher = None try: self._md5_hasher = hashlib.md5() except ValueError: # FIPs mode disables MD5 pass self._...
Initialize our manager and hasher objects.
__init__
python
pypa/twine
twine/package.py
https://github.com/pypa/twine/blob/master/twine/package.py
Apache-2.0
def hexdigest(self) -> Hexdigest: """Return the hexdigest for the file.""" return Hexdigest( self._md5_hexdigest(), self._sha2_hexdigest(), self._blake_hexdigest(), )
Return the hexdigest for the file.
hexdigest
python
pypa/twine
twine/package.py
https://github.com/pypa/twine/blob/master/twine/package.py
Apache-2.0
def __init__( self, *, attestations: bool = False, sign: bool = False, sign_with: str = "gpg", identity: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, non_interactive: bool = False, comment: Optional[...
Initialize our settings instance. :param attestations: Whether the package file should be uploaded with attestations. :param sign: Configure whether the package file should be signed. :param sign_with: The name of the executable used to sign the package with....
__init__
python
pypa/twine
twine/settings.py
https://github.com/pypa/twine/blob/master/twine/settings.py
Apache-2.0
def verbose(self, verbose: bool) -> None: """Initialize a logger based on the --verbose option.""" self._verbose = verbose twine_logger = logging.getLogger("twine") twine_logger.setLevel(logging.INFO if verbose else logging.WARNING)
Initialize a logger based on the --verbose option.
verbose
python
pypa/twine
twine/settings.py
https://github.com/pypa/twine/blob/master/twine/settings.py
Apache-2.0
def from_argparse(cls, args: argparse.Namespace) -> "Settings": """Generate the Settings from parsed arguments.""" settings = vars(args) settings["repository_name"] = settings.pop("repository") settings["cacert"] = settings.pop("cert") return cls(**settings)
Generate the Settings from parsed arguments.
from_argparse
python
pypa/twine
twine/settings.py
https://github.com/pypa/twine/blob/master/twine/settings.py
Apache-2.0
def check_repository_url(self) -> None: """Verify we are not using legacy PyPI. :raises twine.exceptions.UploadToDeprecatedPyPIDetected: The configured repository URL is for legacy PyPI. """ repository_url = cast(str, self.repository_config["repository"]) if reposit...
Verify we are not using legacy PyPI. :raises twine.exceptions.UploadToDeprecatedPyPIDetected: The configured repository URL is for legacy PyPI.
check_repository_url
python
pypa/twine
twine/settings.py
https://github.com/pypa/twine/blob/master/twine/settings.py
Apache-2.0
def get_config(path: str) -> Dict[str, RepositoryConfig]: """Read repository configuration from a file (i.e. ~/.pypirc). Format: https://packaging.python.org/specifications/pypirc/ If the default config file doesn't exist, return a default configuration for pypyi and testpypi. """ realpath = o...
Read repository configuration from a file (i.e. ~/.pypirc). Format: https://packaging.python.org/specifications/pypirc/ If the default config file doesn't exist, return a default configuration for pypyi and testpypi.
get_config
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def sanitize_url(url: str) -> str: """Sanitize a URL. Sanitize URLs, removing any user:password combinations and replacing them with asterisks. Returns the original URL if the string is a non-matching pattern. :param url: str containing a URL to sanitize. return: str either sanit...
Sanitize a URL. Sanitize URLs, removing any user:password combinations and replacing them with asterisks. Returns the original URL if the string is a non-matching pattern. :param url: str containing a URL to sanitize. return: str either sanitized or as entered depending on pattern ma...
sanitize_url
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def _validate_repository_url(repository_url: str) -> None: """Validate the given url for allowed schemes and components.""" # Allowed schemes are http and https, based on whether the repository # supports TLS or not, and scheme and host must be present in the URL validator = ( rfc3986.validators...
Validate the given url for allowed schemes and components.
_validate_repository_url
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def get_repository_from_config( config_file: str, repository: str, repository_url: Optional[str] = None, ) -> RepositoryConfig: """Get repository config command-line values or the .pypirc file.""" # Prefer CLI `repository_url` over `repository` or .pypirc if repository_url: _validate_rep...
Get repository config command-line values or the .pypirc file.
get_repository_from_config
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def get_file_size(filename: str) -> str: """Return the size of a file in KB, or MB if >= 1024 KB.""" file_size = os.path.getsize(filename) / 1024 size_unit = "KB" if file_size > 1024: file_size = file_size / 1024 size_unit = "MB" return f"{file_size:.1f} {size_unit}"
Return the size of a file in KB, or MB if >= 1024 KB.
get_file_size
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def check_status_code(response: requests.Response, verbose: bool) -> None: """Generate a helpful message based on the response from the repository. Raise a custom exception for recognized errors. Otherwise, print the response content (based on the verbose option) before re-raising the HTTPError. ""...
Generate a helpful message based on the response from the repository. Raise a custom exception for recognized errors. Otherwise, print the response content (based on the verbose option) before re-raising the HTTPError.
check_status_code
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def get_userpass_value( cli_value: Optional[str], config: RepositoryConfig, key: str, prompt_strategy: Optional[Callable[[], str]] = None, ) -> Optional[str]: """Get a credential (e.g. a username or password) from the configuration. Uses the following rules: 1. If ``cli_value`` is specifie...
Get a credential (e.g. a username or password) from the configuration. Uses the following rules: 1. If ``cli_value`` is specified, use that. 2. If ``config[key]`` is specified, use that. 3. If ``prompt_strategy`` is specified, use its return value. 4. Otherwise return ``None`` :param cli_valu...
get_userpass_value
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def make_requests_session() -> requests.Session: """Prepare a requests Session with retries & twine's user-agent string.""" s = requests.Session() retry = urllib3.Retry( allowed_methods=["GET"], connect=5, total=10, status_forcelist=[500, 501, 502, 503], ) for schem...
Prepare a requests Session with retries & twine's user-agent string.
make_requests_session
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def bool_from_env(val: Optional[str]) -> bool: """Allow '0' and 'false' and 'no' to be False.""" falsey = {"0", "false", "no"} return bool(val and val.lower() not in falsey)
Allow '0' and 'false' and 'no' to be False.
bool_from_env
python
pypa/twine
twine/utils.py
https://github.com/pypa/twine/blob/master/twine/utils.py
Apache-2.0
def find_candidate_metadata_files(names: List[str]) -> List[List[str]]: """Filter files that may be METADATA files.""" tuples = [x.split("/") for x in names if "METADATA" in x] return [x[1] for x in sorted((len(x), x) for x in tuples)]
Filter files that may be METADATA files.
find_candidate_metadata_files
python
pypa/twine
twine/wheel.py
https://github.com/pypa/twine/blob/master/twine/wheel.py
Apache-2.0
def _parse_content_type(value: str) -> Tuple[str, Dict[str, str]]: """Implement logic of deprecated cgi.parse_header(). From https://docs.python.org/3.11/library/cgi.html#cgi.parse_header. """ msg = email.message.EmailMessage() msg["content-type"] = value return msg.get_content_type(), msg["con...
Implement logic of deprecated cgi.parse_header(). From https://docs.python.org/3.11/library/cgi.html#cgi.parse_header.
_parse_content_type
python
pypa/twine
twine/commands/check.py
https://github.com/pypa/twine/blob/master/twine/commands/check.py
Apache-2.0
def check( dists: List[str], strict: bool = False, ) -> bool: """Check that a distribution will render correctly on PyPI and display the results. This is currently only validates ``long_description``, but more checks could be added. :param dists: The distribution files to check. :p...
Check that a distribution will render correctly on PyPI and display the results. This is currently only validates ``long_description``, but more checks could be added. :param dists: The distribution files to check. :param output_stream: The destination of the resulting output. :par...
check
python
pypa/twine
twine/commands/check.py
https://github.com/pypa/twine/blob/master/twine/commands/check.py
Apache-2.0
def main(args: List[str]) -> bool: """Execute the ``check`` command. :param args: The command-line arguments. :return: The exit status of the ``check`` command. """ parser = argparse.ArgumentParser(prog="twine check") parser.add_argument( "dists", nargs="+", ...
Execute the ``check`` command. :param args: The command-line arguments. :return: The exit status of the ``check`` command.
main
python
pypa/twine
twine/commands/check.py
https://github.com/pypa/twine/blob/master/twine/commands/check.py
Apache-2.0
def register(register_settings: settings.Settings, package: str) -> None: """Pre-register a package name with a repository before uploading a distribution. Pre-registration is not supported on PyPI, so the ``register`` command is only necessary if you are using a different repository that requires it. ...
Pre-register a package name with a repository before uploading a distribution. Pre-registration is not supported on PyPI, so the ``register`` command is only necessary if you are using a different repository that requires it. :param register_settings: The configured options relating to repository ...
register
python
pypa/twine
twine/commands/register.py
https://github.com/pypa/twine/blob/master/twine/commands/register.py
Apache-2.0
def main(args: List[str]) -> None: """Execute the ``register`` command. :param args: The command-line arguments. """ parser = argparse.ArgumentParser( prog="twine register", description="register operation is not required with PyPI.org", ) settings.Settings.register_argp...
Execute the ``register`` command. :param args: The command-line arguments.
main
python
pypa/twine
twine/commands/register.py
https://github.com/pypa/twine/blob/master/twine/commands/register.py
Apache-2.0
def skip_upload( response: requests.Response, skip_existing: bool, package: package_file.PackageFile ) -> bool: """Determine if a failed upload is an error or can be safely ignored. :param response: The response from attempting to upload ``package`` to a repository. :param skip_existing: ...
Determine if a failed upload is an error or can be safely ignored. :param response: The response from attempting to upload ``package`` to a repository. :param skip_existing: If ``True``, use the status and content of ``response`` to determine if the package already exists on the reposit...
skip_upload
python
pypa/twine
twine/commands/upload.py
https://github.com/pypa/twine/blob/master/twine/commands/upload.py
Apache-2.0
def _make_package( filename: str, signatures: Dict[str, str], attestations: List[str], upload_settings: settings.Settings, ) -> package_file.PackageFile: """Create and sign a package, based off of filename, signatures, and settings. Additionally, any supplied attestations are attached to the pa...
Create and sign a package, based off of filename, signatures, and settings. Additionally, any supplied attestations are attached to the package when the settings indicate to do so.
_make_package
python
pypa/twine
twine/commands/upload.py
https://github.com/pypa/twine/blob/master/twine/commands/upload.py
Apache-2.0
def upload(upload_settings: settings.Settings, dists: List[str]) -> None: """Upload one or more distributions to a repository, and display the progress. If a package already exists on the repository, most repositories will return an error response. However, if ``upload_settings.skip_existing`` is ``True``,...
Upload one or more distributions to a repository, and display the progress. If a package already exists on the repository, most repositories will return an error response. However, if ``upload_settings.skip_existing`` is ``True``, a message will be displayed and any remaining distributions will be uploaded...
upload
python
pypa/twine
twine/commands/upload.py
https://github.com/pypa/twine/blob/master/twine/commands/upload.py
Apache-2.0
def main(args: List[str]) -> None: """Execute the ``upload`` command. :param args: The command-line arguments. """ parser = argparse.ArgumentParser(prog="twine upload") settings.Settings.register_argparse_arguments(parser) parser.add_argument( "dists", nargs="+", ...
Execute the ``upload`` command. :param args: The command-line arguments.
main
python
pypa/twine
twine/commands/upload.py
https://github.com/pypa/twine/blob/master/twine/commands/upload.py
Apache-2.0
def _split_inputs( inputs: List[str], ) -> Inputs: """ Split the unstructured list of input files provided by the user into groups. Three groups are returned: upload files (i.e. dists), signatures, and attestations. Upload files are returned as a linear list, signatures are returned as a dict ...
Split the unstructured list of input files provided by the user into groups. Three groups are returned: upload files (i.e. dists), signatures, and attestations. Upload files are returned as a linear list, signatures are returned as a dict of ``basename -> path``, and attestations are returned as a di...
_split_inputs
python
pypa/twine
twine/commands/__init__.py
https://github.com/pypa/twine/blob/master/twine/commands/__init__.py
Apache-2.0
def add(self, rsrc: Cacheable, on_delete: Optional[DeletionHandler] = None) -> None: """ Adds an entry to the cache, if it's not already present. If on_delete is not None, it will called when rsrc is removed from the cache. """ key = rsrc.cache_key if not key: ...
Adds an entry to the cache, if it's not already present. If on_delete is not None, it will called when rsrc is removed from the cache.
add
python
emissary-ingress/emissary
python/ambassador/cache.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/cache.py
Apache-2.0
def link(self, owner: Cacheable, owned: Cacheable) -> None: """ Adds a link to the cache. Links are directional from the owner to the owned. The basic idea is that if the owner changes, all the owned things get invalidated. Both the owner and the owned must be in the cache. ...
Adds a link to the cache. Links are directional from the owner to the owned. The basic idea is that if the owner changes, all the owned things get invalidated. Both the owner and the owned must be in the cache.
link
python
emissary-ingress/emissary
python/ambassador/cache.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/cache.py
Apache-2.0
def invalidate(self, key: str) -> None: """ Recursively invalidate the entry named by 'key' and everything to which it is linked. """ # We use worklist to keep track of things to consider: for starters, # it just has our key in it, and as we find owned things, we add the...
Recursively invalidate the entry named by 'key' and everything to which it is linked.
invalidate
python
emissary-ingress/emissary
python/ambassador/cache.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/cache.py
Apache-2.0
def __getitem__(self, key: str) -> Optional[Cacheable]: """ Fetches only the _resource_ for a given key from the cache. If the key is not present in the cache, returns None. If you need the deletion callback, you'll have to work with self.cache manually. """ ite...
Fetches only the _resource_ for a given key from the cache. If the key is not present in the cache, returns None. If you need the deletion callback, you'll have to work with self.cache manually.
__getitem__
python
emissary-ingress/emissary
python/ambassador/cache.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/cache.py
Apache-2.0
def dump(self, what, *args) -> None: """ Dump the cache to the logger. """ if self.logger.isEnabledFor(logging.DEBUG): self.logger.debug("CACHE DUMP AFTER " + what, *args) for k in sorted(self.cache.keys()): rsrc, on_delete = self.cache[k] ...
Dump the cache to the logger.
dump
python
emissary-ingress/emissary
python/ambassador/cache.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/cache.py
Apache-2.0
def Compile( logger: logging.Logger, input_text: str, cache: Optional[Cache] = None, file_checker: Optional[IRFileChecker] = None, secret_handler: Optional[SecretHandler] = None, k8s: bool = False, ) -> _CompileResult: """ Compile is a helper function to take a bunch of YAML and compile ...
Compile is a helper function to take a bunch of YAML and compile it into an IR and, optionally, an Envoy config. The output is a dictionary: { "ir": the IR data structure "xds": the Envoy config } :param input_text: The input text (WATT snapshot JSON or K8s YAML per 'k8s') ...
Compile
python
emissary-ingress/emissary
python/ambassador/compile.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/compile.py
Apache-2.0
def __init__( self, logger: logging.Logger, max_incr_between_checks=100, max_time_between_checks=600, max_config_between_timers=10, max_time_between_timers=120, ) -> None: """ Initialize this ReconfigStats. :param max_incr_between_checks: Maxi...
Initialize this ReconfigStats. :param max_incr_between_checks: Maximum number of outstanding incrementals before a sanity check :param max_time_between_checks: Maximum number of seconds between sanity checks :param max_config_between_timers: Maximum number of configurations before logg...
__init__
python
emissary-ingress/emissary
python/ambassador/reconfig_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/reconfig_stats.py
Apache-2.0
def mark(self, what: str, when: Optional[PerfCounter] = None) -> None: """ Mark that a reconfigure has occurred. The 'what' parameter is one of "complete" for a complete reconfigure, "incremental" for an incremental, or "diag" to indicate that we're not really reconfiguring, we just gene...
Mark that a reconfigure has occurred. The 'what' parameter is one of "complete" for a complete reconfigure, "incremental" for an incremental, or "diag" to indicate that we're not really reconfiguring, we just generated the diagnostics so may need to log timers. :param what: "co...
mark
python
emissary-ingress/emissary
python/ambassador/reconfig_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/reconfig_stats.py
Apache-2.0
def needs_check(self, when: Optional[PerfCounter] = None) -> bool: """ Determine if we need to do a complete reconfigure to doublecheck our incrementals. The logic here is that we need a check every 100 incrementals or every 10 minutes, whichever comes first. :param when: Overri...
Determine if we need to do a complete reconfigure to doublecheck our incrementals. The logic here is that we need a check every 100 incrementals or every 10 minutes, whichever comes first. :param when: Override the effective time of the check. Primarily useful for testing. :ret...
needs_check
python
emissary-ingress/emissary
python/ambassador/reconfig_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/reconfig_stats.py
Apache-2.0
def needs_timers(self, when: Optional[PerfCounter] = None) -> bool: """ Determine if we need to log the timers or not. The logic here is that we need to log every max_configs_between_timers incrementals or every or every max_time_between_timers seconds, whichever comes first. :p...
Determine if we need to log the timers or not. The logic here is that we need to log every max_configs_between_timers incrementals or every or every max_time_between_timers seconds, whichever comes first. :param when: Override the effective time of the check. Primarily useful for testi...
needs_timers
python
emissary-ingress/emissary
python/ambassador/reconfig_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/reconfig_stats.py
Apache-2.0
def mark_checked(self, result: bool, when: Optional[PerfCounter] = None) -> None: """ Mark that we have done a check, and note the results. This resets our outstanding incrementals to 0, and also resets our last check time. :param result: True if the check was good, False if not ...
Mark that we have done a check, and note the results. This resets our outstanding incrementals to 0, and also resets our last check time. :param result: True if the check was good, False if not :param when: Override the effective time. Primarily useful for testing.
mark_checked
python
emissary-ingress/emissary
python/ambassador/reconfig_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/reconfig_stats.py
Apache-2.0
def mark_timers_logged(self, when: Optional[PerfCounter] = None) -> None: """ Mark that we have logged timers. This resets our outstanding configurations to 0, and also resets our last timer log time. :param when: Override the effective time. Primarily useful for testing. """ ...
Mark that we have logged timers. This resets our outstanding configurations to 0, and also resets our last timer log time. :param when: Override the effective time. Primarily useful for testing.
mark_timers_logged
python
emissary-ingress/emissary
python/ambassador/reconfig_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/reconfig_stats.py
Apache-2.0
def from_resource( cls: Type[R], other: R, rkey: Optional[str] = None, location: Optional[str] = None, kind: Optional[str] = None, serialization: Optional[str] = None, **kwargs ) -> R: """ Create a Resource by copying another Resource, possibly...
Create a Resource by copying another Resource, possibly overriding elements along the way. NOTE WELL: if you pass in kwargs, we assume that any values are safe to use as-is and DO NOT COPY THEM. Otherwise, we SHALLOW COPY other.attrs for the new Resource. :param other: the bas...
from_resource
python
emissary-ingress/emissary
python/ambassador/resource.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/resource.py
Apache-2.0
def from_dict( cls: Type[R], rkey: str, location: str, serialization: Optional[str], attrs: Dict ) -> R: """ Create a Resource or subclass thereof from a dictionary. The new Resource's rkey and location must be handed in explicitly. The difference between this and simply int...
Create a Resource or subclass thereof from a dictionary. The new Resource's rkey and location must be handed in explicitly. The difference between this and simply intializing a Resource object is that from_dict will introspect the attrs passed in and create whatever kind of Resource ...
from_dict
python
emissary-ingress/emissary
python/ambassador/resource.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/resource.py
Apache-2.0
def from_yaml(cls: Type[R], rkey: str, location: str, serialization: str) -> R: """ Create a Resource from a YAML serialization. The new Resource's rkey and location must be handed in explicitly, and of course in this case the serialization is mandatory. Raises an exception if t...
Create a Resource from a YAML serialization. The new Resource's rkey and location must be handed in explicitly, and of course in this case the serialization is mandatory. Raises an exception if the serialization is not parseable. :param rkey: unique identifier for this source,...
from_yaml
python
emissary-ingress/emissary
python/ambassador/resource.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/resource.py
Apache-2.0
def __init__( self, app, version, install_id=None, id_plugin=None, id_plugin_args={}, scout_host="metriton.datawire.io", **kwargs ): """ Create a new Scout instance for later reports. :param app: The application name. Required....
Create a new Scout instance for later reports. :param app: The application name. Required. :param version: The application version. Required. :param install_id: Optional install_id. If set, Scout will believe it. :param id_plugin: Optional plugin function for obtaining an insta...
__init__
python
emissary-ingress/emissary
python/ambassador/scout.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/scout.py
Apache-2.0
def configmap_install_id_plugin(scout, app, map_name=None, namespace="default"): """ Scout id_plugin that uses a Kubernetes configmap to store the install ID. :param scout: Scout instance that's calling the plugin :param app: Name of the application that's using Scout :param map...
Scout id_plugin that uses a Kubernetes configmap to store the install ID. :param scout: Scout instance that's calling the plugin :param app: Name of the application that's using Scout :param map_name: Optional ConfigMap name to use; defaults to "scout.config.$app" :param namesp...
configmap_install_id_plugin
python
emissary-ingress/emissary
python/ambassador/scout.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/scout.py
Apache-2.0
def parse_bool(s: Optional[Union[str, bool]]) -> bool: """ Parse a boolean value from a string. T, True, Y, y, 1 return True; other things return False. """ # If `s` is already a bool, return its value. # # This allows a caller to not know or care whether their value is already # a bool...
Parse a boolean value from a string. T, True, Y, y, 1 return True; other things return False.
parse_bool
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def __init__(self, name: str, prom_metrics_registry: Optional[Any] = None) -> None: """ Create a Timer, given a name. The Timer is initially stopped. """ self.name = name if prom_metrics_registry: metric_prefix = re.sub(r"\s+", "_", name).lower() self._g...
Create a Timer, given a name. The Timer is initially stopped.
__init__
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def start(self, when: Optional[float] = None) -> None: """ Start a Timer running. :param when: Optional start time. If not supplied, the current time is used. """ # If we're already running, this method silently discards the # currently-running cycle. Why? Becau...
Start a Timer running. :param when: Optional start time. If not supplied, the current time is used.
start
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def stop(self, when: Optional[float] = None) -> float: """ Stop a Timer, increment the cycle count, and update the accumulated time with the amount of time since the Timer was started. :param when: Optional stop time. If not supplied, the current time is used. :r...
Stop a Timer, increment the cycle count, and update the accumulated time with the amount of time since the Timer was started. :param when: Optional stop time. If not supplied, the current time is used. :return: The amount of time the Timer has accumulated
stop
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def faketime(self, faketime: float) -> None: """ Add fake time to a Timer. This is intended solely for testing. """ if not self._running: raise Exception(f"Timer {self.name}.faketime: not running") self._faketime = faketime
Add fake time to a Timer. This is intended solely for testing.
faketime
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def average(self): """ The average cycle time for this Timer. """ if self._cycles > 0: return self._accumulated / self._cycles raise Exception(f"Timer {self.name}.average: no cycles to average")
The average cycle time for this Timer.
average
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def decode(b64_pem: str) -> Optional[str]: """ Do base64 decoding of a cryptographic element. :param b64_pem: Base64-encoded PEM element :return: Decoded PEM element """ utf8_pem = None pem = None try: utf8_pem = binascii.a2b_base64(b64_pem) ...
Do base64 decoding of a cryptographic element. :param b64_pem: Base64-encoded PEM element :return: Decoded PEM element
decode
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def fingerprint(pem: Optional[str]) -> str: """ Generate and return a cryptographic fingerprint of a PEM element. The fingerprint is the uppercase hex SHA-1 signature of the element's UTF-8 representation. :param pem: PEM element :return: fingerprint string """ ...
Generate and return a cryptographic fingerprint of a PEM element. The fingerprint is the uppercase hex SHA-1 signature of the element's UTF-8 representation. :param pem: PEM element :return: fingerprint string
fingerprint
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def to_dict(self) -> Dict[str, Any]: """ Return the dictionary representation of this SecretInfo. :return: dict """ return { "name": self.name, "namespace": self.namespace, "secret_type": self.secret_type, "tls_crt": self.fingerpri...
Return the dictionary representation of this SecretInfo. :return: dict
to_dict
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def from_aconf_secret(cls, aconf_object: "ACResource") -> "SecretInfo": """ Convert an ACResource containing a secret into a SecretInfo. This is used by the IR.save_secret_info() to convert saved secrets into SecretInfos. :param aconf_object: a ACResource containing a secret :re...
Convert an ACResource containing a secret into a SecretInfo. This is used by the IR.save_secret_info() to convert saved secrets into SecretInfos. :param aconf_object: a ACResource containing a secret :return: SecretInfo
from_aconf_secret
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def from_dict( cls, resource: "IRResource", secret_name: str, namespace: str, source: str, cert_data: Optional[Dict[str, Any]], secret_type="kubernetes.io/tls", ) -> Optional["SecretInfo"]: """ Given a secret's name and namespace, and a diction...
Given a secret's name and namespace, and a dictionary of configuration elements, return a SecretInfo for the secret. The "source" parameter needs some explanation. When working with secrets in most environments where Ambassador runs, secrets will be loaded from some external system (e....
from_dict
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def still_needed(self, resource: "IRResource", secret_name: str, namespace: str) -> None: """ still_needed: remember that a given secret is still needed, so that we can tell watt to keep paying attention to it. :param resource: referencing resource :param secret_name: name of th...
still_needed: remember that a given secret is still needed, so that we can tell watt to keep paying attention to it. :param resource: referencing resource :param secret_name: name of the secret :param namespace: namespace of the secret :return: None
still_needed
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def __init__( self, logger: logging.Logger, source_root: Optional[str], cache_dir: Optional[str], version: str, ) -> None: """ Returns a valid SecretInfo (with fake keys) for any requested secret. Also, you can pass None for source_root and cache_dir t...
Returns a valid SecretInfo (with fake keys) for any requested secret. Also, you can pass None for source_root and cache_dir to use random temporary directories for them.
__init__
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def __init__( self, logger: logging.Logger, source_root: Optional[str], cache_dir: Optional[str], version: str, ) -> None: """ Returns a None to simulate no provided secrets """ super().__init__(logger, "", "", version)
Returns a None to simulate no provided secrets
__init__
python
emissary-ingress/emissary
python/ambassador/utils.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/utils.py
Apache-2.0
def __init__( self, rkey: str, location: str, *, name: str, kind: str = "Mapping", apiVersion: Optional[str] = None, serialization: Optional[str] = None, service: str, prefix: str, prefix_regex: bool = False, rewrite: Option...
Initialize an ACMapping from the raw fields of its ACResource.
__init__
python
emissary-ingress/emissary
python/ambassador/config/acmapping.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/config/acmapping.py
Apache-2.0
def __init__( self, rkey: str, location: str = "-pragma-", *, name: str = "-pragma-", kind: str = "Pragma", apiVersion: Optional[str] = None, serialization: Optional[str] = None, **kwargs ) -> None: """ Initialize an ACPragma fr...
Initialize an ACPragma from the raw fields of its ACResource.
__init__
python
emissary-ingress/emissary
python/ambassador/config/acpragma.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/config/acpragma.py
Apache-2.0
def _reset(self) -> None: """ Resets this Config to the empty, default state so it can load a new config. """ self.logger.debug("ACONF RESET") self.current_resource = None self.helm_chart = None self.config = {} self.breakers = {} self.outliers...
Resets this Config to the empty, default state so it can load a new config.
_reset
python
emissary-ingress/emissary
python/ambassador/config/config.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/config/config.py
Apache-2.0
def load_all(self, resources: Iterable[ACResource]) -> None: """ Loads all of a set of ACResources. It is the caller's responsibility to arrange for the set of ACResources to be sorted in some way that makes sense. """ self.logger.debug(f"Loading config") rcount = 0 ...
Loads all of a set of ACResources. It is the caller's responsibility to arrange for the set of ACResources to be sorted in some way that makes sense.
load_all
python
emissary-ingress/emissary
python/ambassador/config/config.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/config/config.py
Apache-2.0
def get_module(self, module_name: str) -> Optional[ACResource]: """ Fetch a module from the module store. Can return None if no such module exists. :param module_name: name of the module you want. """ modules = self.get_config("modules") if modules: ...
Fetch a module from the module store. Can return None if no such module exists. :param module_name: name of the module you want.
get_module
python
emissary-ingress/emissary
python/ambassador/config/config.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/config/config.py
Apache-2.0
def module_lookup(self, module_name: str, key: str, default: Any = None) -> Any: """ Look up a specific key in a given module. If the named module doesn't exist, or if the key doesn't exist in the module, return the default. :param module_name: name of the module you want. :para...
Look up a specific key in a given module. If the named module doesn't exist, or if the key doesn't exist in the module, return the default. :param module_name: name of the module you want. :param key: key to look up within the module :param default: default value if the module ...
module_lookup
python
emissary-ingress/emissary
python/ambassador/config/config.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/config/config.py
Apache-2.0
def handle_secret(self, resource: ACResource) -> None: """ Handles a Secret resource. We need a handler for this because the key needs to be the rkey, not the name. """ self.logger.debug(f"Handling secret resource {resource.as_dict()}") storage = self.config.setdefault(...
Handles a Secret resource. We need a handler for this because the key needs to be the rkey, not the name.
handle_secret
python
emissary-ingress/emissary
python/ambassador/config/config.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/config/config.py
Apache-2.0
def handle_service(self, resource: ACResource) -> None: """ Handles a Service resource. We need a handler for this because the key needs to be the rkey, not the name, and because we need to check the helm_chart attribute. """ storage = self.config.setdefault("service", {}) ...
Handles a Service resource. We need a handler for this because the key needs to be the rkey, not the name, and because we need to check the helm_chart attribute.
handle_service
python
emissary-ingress/emissary
python/ambassador/config/config.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/config/config.py
Apache-2.0
def include_cluster(self, cluster: dict) -> DiagCluster: """ Note that a particular cluster and everything that references it are relevant to this result. If the cluster has related health information in our cstats, fold that in too. Don't pass an IRCluster here -- turn it into ...
Note that a particular cluster and everything that references it are relevant to this result. If the cluster has related health information in our cstats, fold that in too. Don't pass an IRCluster here -- turn it into a dict with as_dict() first. Returns the DiagCluste...
include_cluster
python
emissary-ingress/emissary
python/ambassador/diagnostics/diagnostics.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/diagnostics.py
Apache-2.0
def include_httpgroup(self, group: IRHTTPMappingGroup) -> None: """ Note that a particular IRHTTPMappingGroup, all of the clusters it uses for upstream traffic, and everything that references it are relevant to this result. This method actually does a fair amount of work around handling...
Note that a particular IRHTTPMappingGroup, all of the clusters it uses for upstream traffic, and everything that references it are relevant to this result. This method actually does a fair amount of work around handling clusters, shadow clusters, and host_redirects. It would be a horri...
include_httpgroup
python
emissary-ingress/emissary
python/ambassador/diagnostics/diagnostics.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/diagnostics.py
Apache-2.0
def finalize(self) -> None: """ Make sure that all the elements we've marked as included actually appear in the ambassador_resources and envoy_resources dictionaries, so that the UI can properly connect all the dots. """ for key in self.element_keys.keys(): a...
Make sure that all the elements we've marked as included actually appear in the ambassador_resources and envoy_resources dictionaries, so that the UI can properly connect all the dots.
finalize
python
emissary-ingress/emissary
python/ambassador/diagnostics/diagnostics.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/diagnostics.py
Apache-2.0
def add_ambassador_resolver(self, resolver, group_list) -> None: """ Remember information about a given Ambassador-wide resolver. :param resolver: resolver record :param group_list: list of groups that use this resolver """ self.ambassador_resolvers.append( ...
Remember information about a given Ambassador-wide resolver. :param resolver: resolver record :param group_list: list of groups that use this resolver
add_ambassador_resolver
python
emissary-ingress/emissary
python/ambassador/diagnostics/diagnostics.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/diagnostics.py
Apache-2.0
def split_key(key) -> Tuple[str, Optional[str]]: """ Split a key into its components (the base name and the object index). :param key: possibly-qualified key :return: tuple of the base and a possible index """ key_base = key key_index = None m = Diagnos...
Split a key into its components (the base name and the object index). :param key: possibly-qualified key :return: tuple of the base and a possible index
split_key
python
emissary-ingress/emissary
python/ambassador/diagnostics/diagnostics.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/diagnostics.py
Apache-2.0
def remember_source( self, uqkey: str, fqkey: Optional[str], location: Optional[str], dest_key: str ) -> None: """ Populate the source map in various ways. A mapping from uqkey to dest_key is always added; mappings for fqkey and location are added if they are unique keys. ...
Populate the source map in various ways. A mapping from uqkey to dest_key is always added; mappings for fqkey and location are added if they are unique keys. :param uqkey: unqualified source key :param fqkey: qualified source key :param location: source location ...
remember_source
python
emissary-ingress/emissary
python/ambassador/diagnostics/diagnostics.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/diagnostics.py
Apache-2.0
def overview(self, request, estat: EnvoyStats) -> Dict[str, Any]: """ Generate overview data describing the whole Ambassador setup, most notably the routing table. Returns the dictionary form of a DiagResult. :param request: the Flask request being handled :param estat: current ...
Generate overview data describing the whole Ambassador setup, most notably the routing table. Returns the dictionary form of a DiagResult. :param request: the Flask request being handled :param estat: current EnvoyStats :return: the dictionary form of a DiagResult
overview
python
emissary-ingress/emissary
python/ambassador/diagnostics/diagnostics.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/diagnostics.py
Apache-2.0
def lookup(self, request, key: str, estat: EnvoyStats) -> Optional[Dict[str, Any]]: """ Generate data describing a specific key in the Ambassador setup, and all the things connected to it. Returns the dictionary form of a DiagResult. 'key' can be a group key that starts with grp-, a clu...
Generate data describing a specific key in the Ambassador setup, and all the things connected to it. Returns the dictionary form of a DiagResult. 'key' can be a group key that starts with grp-, a cluster key that starts with cluster_, or a source key. :param request: the Flask...
lookup
python
emissary-ingress/emissary
python/ambassador/diagnostics/diagnostics.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/diagnostics.py
Apache-2.0
def is_alive(self) -> bool: """ Make sure we've heard from Envoy within max_live_age seconds. If we haven't yet heard from Envoy at all (we've just booted), consider Envoy alive if we haven't yet been running for max_live_age seconds -- basically, Envoy gets a grace period to st...
Make sure we've heard from Envoy within max_live_age seconds. If we haven't yet heard from Envoy at all (we've just booted), consider Envoy alive if we haven't yet been running for max_live_age seconds -- basically, Envoy gets a grace period to start running at boot time. ...
is_alive
python
emissary-ingress/emissary
python/ambassador/diagnostics/envoy_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/envoy_stats.py
Apache-2.0
def is_ready(self) -> bool: """ Make sure we've heard from Envoy within max_ready_age seconds. If we haven't yet heard from Envoy at all (we've just booted), then Envoy is not yet ready, and is_ready() returns False. """ epoch = self.last_update if not epoch: ...
Make sure we've heard from Envoy within max_ready_age seconds. If we haven't yet heard from Envoy at all (we've just booted), then Envoy is not yet ready, and is_ready() returns False.
is_ready
python
emissary-ingress/emissary
python/ambassador/diagnostics/envoy_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/envoy_stats.py
Apache-2.0
def time_since_update(self) -> Optional[float]: """ Return the number of seconds since we last heard from Envoy, or None if we've never heard from Envoy. """ if not self.last_update: return None else: return time.time() - self.last_update
Return the number of seconds since we last heard from Envoy, or None if we've never heard from Envoy.
time_since_update
python
emissary-ingress/emissary
python/ambassador/diagnostics/envoy_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/envoy_stats.py
Apache-2.0
def update_log_levels(self, last_attempt: float, level: Optional[str] = None) -> bool: """ Heavy lifting around updating the Envoy log levels. You MUST hold the update lock when calling this method. You MUST NOT hold the access lock when calling this method. update_log_levels d...
Heavy lifting around updating the Envoy log levels. You MUST hold the update lock when calling this method. You MUST NOT hold the access lock when calling this method. update_log_levels does all the work of talking to Envoy and computing new stats, then grabs the access_lock j...
update_log_levels
python
emissary-ingress/emissary
python/ambassador/diagnostics/envoy_stats.py
https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/diagnostics/envoy_stats.py
Apache-2.0