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 update_envoy_stats(self, last_attempt: float) -> None:
"""
Heavy lifting around updating the Envoy stats.
You MUST hold the update lock when calling this method.
You MUST NOT hold the access lock when calling this method.
update_envoy_stats does all the work of talking to E... |
Heavy lifting around updating the Envoy stats.
You MUST hold the update lock when calling this method.
You MUST NOT hold the access lock when calling this method.
update_envoy_stats does all the work of talking to Envoy and computing
new stats, then grabs the access_lock just ... | update_envoy_stats | 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(self) -> None:
"""
Update the Envoy stats object, including our take on Envoy's loglevel and
lower-level statistics.
You MUST NOT hold the update lock when calling this method.
You MUST NOT hold the access lock when calling this method.
The first thing that u... |
Update the Envoy stats object, including our take on Envoy's loglevel and
lower-level statistics.
You MUST NOT hold the update lock when calling this method.
You MUST NOT hold the access lock when calling this method.
The first thing that update_envoy_stats does is to acquire ... | 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 __init__(self, spec: str) -> None:
"""
Initialize a CIDRRange from a spec, which can look like any of:
127.0.0.1 -- an exact IPv4 match
::1 -- an exact IPv6 match
192.168.0.0/16 -- an IPv4 range
2001:2000::/64 -- an IPv6 range
If the prefix is not a valid IP... |
Initialize a CIDRRange from a spec, which can look like any of:
127.0.0.1 -- an exact IPv4 match
::1 -- an exact IPv6 match
192.168.0.0/16 -- an IPv4 range
2001:2000::/64 -- an IPv6 range
If the prefix is not a valid IP address, or if the prefix length
isn't a ... | __init__ | python | emissary-ingress/emissary | python/ambassador/envoy/v3/v3cidrrange.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/envoy/v3/v3cidrrange.py | Apache-2.0 |
def add_route(self, virtual_host: str, route: DictifiedV3Route) -> None:
"""
add_route will add the route to the matching virtual host. If the
virtual_host doesn't already exist in routes then we initialize an
empty list and append the route
"""
if virtual_host not in sel... |
add_route will add the route to the matching virtual host. If the
virtual_host doesn't already exist in routes then we initialize an
empty list and append the route
| add_route | python | emissary-ingress/emissary | python/ambassador/envoy/v3/v3listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/envoy/v3/v3listener.py | Apache-2.0 |
def traverse(self) -> Iterator[Any]:
"""
Returns the items in this graph in topological order.
"""
if len(self.vertices) == 0:
return
# This method implements Kahn's algorithm. See
# https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm for
... |
Returns the items in this graph in topological order.
| traverse | python | emissary-ingress/emissary | python/ambassador/fetch/dependency.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/fetch/dependency.py | Apache-2.0 |
def mark_annotated(self) -> ContextManager[Location]:
"""
Keeps the current stack, adding an annotation flag to the end of the
filename.
"""
previous_filename = self.current.filename
if self.current.filename and not self.current.filename.endswith(":annotation"):
... |
Keeps the current stack, adding an annotation flag to the end of the
filename.
| mark_annotated | python | emissary-ingress/emissary | python/ambassador/fetch/location.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/fetch/location.py | Apache-2.0 |
def agent_init(self, aconf: Config) -> None:
"""
Initialize as the Intercept Agent, if we're doing that.
THIS WHOLE METHOD NEEDS TO GO AWAY: instead, just configure the agent with CRDs as usual.
However, that's just too painful to contemplate without `edgectl inject-agent`.
:pa... |
Initialize as the Intercept Agent, if we're doing that.
THIS WHOLE METHOD NEEDS TO GO AWAY: instead, just configure the agent with CRDs as usual.
However, that's just too painful to contemplate without `edgectl inject-agent`.
:param aconf: Config to work with
:return: None
... | agent_init | python | emissary-ingress/emissary | python/ambassador/ir/ir.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/ir.py | Apache-2.0 |
def cache_fetch(self, key: str) -> Optional[IRResource]:
"""
Fetch a key from our cache. If we get anything, make sure that its
IR pointer is set back to us -- since the cache can easily outlive
the IR, chances are pretty high that the object might've originally
been part of a di... |
Fetch a key from our cache. If we get anything, make sure that its
IR pointer is set back to us -- since the cache can easily outlive
the IR, chances are pretty high that the object might've originally
been part of a different IR.
Yes, this implies that trying to use the cache ... | cache_fetch | python | emissary-ingress/emissary | python/ambassador/ir/ir.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/ir.py | Apache-2.0 |
def handle_ip_allow_deny(self, allow: bool, principals: List[str]) -> None:
"""
Handle IP Allow/Deny. "allow" here states whether this is an
allow rule (True) or a deny rule (False); "principals" is a list
of IP addresses or CIDR ranges to allow or deny.
Only one of ip_allow or ... |
Handle IP Allow/Deny. "allow" here states whether this is an
allow rule (True) or a deny rule (False); "principals" is a list
of IP addresses or CIDR ranges to allow or deny.
Only one of ip_allow or ip_deny can be set, so it's an error to
call this twice (even if "allow" is the... | handle_ip_allow_deny | python | emissary-ingress/emissary | python/ambassador/ir/irambassador.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irambassador.py | Apache-2.0 |
def would_confuse_urlparse(url: str) -> bool:
"""Returns whether an URL-ish string would be interpretted by urlparse()
differently than we want, by parsing it as a non-URL URI ("scheme:path")
instead of as a URL ("[scheme:]//authority[:port]/path"). We don't want to
interpret "myhost:8080" as "ParseRes... | Returns whether an URL-ish string would be interpretted by urlparse()
differently than we want, by parsing it as a non-URL URI ("scheme:path")
instead of as a URL ("[scheme:]//authority[:port]/path"). We don't want to
interpret "myhost:8080" as "ParseResult(scheme='myhost', path='8080')"!
Note: This h... | would_confuse_urlparse | python | emissary-ingress/emissary | python/ambassador/ir/irbasemapping.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irbasemapping.py | Apache-2.0 |
def normalize_service_name(
ir: "IR",
in_service: str,
mapping_namespace: Optional[str],
resolver_kind: str,
rkey: Optional[str] = None,
) -> str:
"""
Note: This has a Go equivalent in github.com/emissary-ingress/emissary/v3/pkg/emissaryutil. Please
keep them in-sync.
"""
try:
... |
Note: This has a Go equivalent in github.com/emissary-ingress/emissary/v3/pkg/emissaryutil. Please
keep them in-sync.
| normalize_service_name | python | emissary-ingress/emissary | python/ambassador/ir/irbasemapping.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irbasemapping.py | Apache-2.0 |
def _cors_normalize(value: Any) -> Any:
"""
List values get turned into a comma-separated string. Other values
are returned unaltered.
"""
if type(value) == list:
return ", ".join([str(x) for x in value])
else:
return value |
List values get turned into a comma-separated string. Other values
are returned unaltered.
| _cors_normalize | python | emissary-ingress/emissary | python/ambassador/ir/ircors.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/ircors.py | Apache-2.0 |
def matches_httpgroup(self, group: "IRHTTPMappingGroup") -> bool:
"""
Make sure a given IRHTTPMappingGroup is a match for this Host, meaning
that at least one of the following is true:
- The Host specifies mappingSelector.matchLabels, and the group has matching labels
- The grou... |
Make sure a given IRHTTPMappingGroup is a match for this Host, meaning
that at least one of the following is true:
- The Host specifies mappingSelector.matchLabels, and the group has matching labels
- The group specifies a host glob, and the Host has a matching domain.
A Mappi... | matches_httpgroup | python | emissary-ingress/emissary | python/ambassador/ir/irhost.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irhost.py | Apache-2.0 |
def finalize(self, ir: "IR", aconf: Config) -> List[IRCluster]:
"""
Finalize a MappingGroup based on the attributes of its Mappings. Core elements get lifted into
the Group so we can more easily build Envoy routes; host-redirect and shadow get handled, etc.
:param ir: the IR we're worki... |
Finalize a MappingGroup based on the attributes of its Mappings. Core elements get lifted into
the Group so we can more easily build Envoy routes; host-redirect and shadow get handled, etc.
:param ir: the IR we're working from
:param aconf: the Config we're working from
:return... | finalize | python | emissary-ingress/emissary | python/ambassador/ir/irhttpmappinggroup.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irhttpmappinggroup.py | Apache-2.0 |
def __init__(
self,
ir: "IR",
aconf: Config,
rkey: str = "ir.ipallowdeny",
name: str = "ir.ipallowdeny",
kind: str = "IRIPAllowDeny",
parent: IRResource | None = None,
action: str | None = None,
**kwargs,
) -> None:
"""
Initiali... |
Initialize an IRIPAllowDeny. In addition to the usual IRFilter parameters,
parent and action are required:
parent is the IRResource in which the IRIPAllowDeny is defined; at present,
this will be the Ambassador module. It's required because it's where errors
should be posted.
... | __init__ | python | emissary-ingress/emissary | python/ambassador/ir/iripallowdeny.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/iripallowdeny.py | Apache-2.0 |
def setup(self, ir: "IR", aconf: Config) -> bool:
"""
Set up an IRIPAllowDeny based on the action and principals passed into
__init__.
"""
assert self.parent
# These pops will crash if the action or principals are missing. That's
# OK -- they're required element... |
Set up an IRIPAllowDeny based on the action and principals passed into
__init__.
| setup | python | emissary-ingress/emissary | python/ambassador/ir/iripallowdeny.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/iripallowdeny.py | Apache-2.0 |
def matches_host(self, host: IRHost) -> bool:
"""
Returns True IFF this Listener wants to take the given IRHost -- meaning,
the Host's namespace and selectors match what we want.
"""
nsmatch = (self.namespace_literal == "*") or (self.namespace_literal == host.namespace)
... |
Returns True IFF this Listener wants to take the given IRHost -- meaning,
the Host's namespace and selectors match what we want.
| matches_host | python | emissary-ingress/emissary | python/ambassador/ir/irlistener.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irlistener.py | Apache-2.0 |
def lookup_default(
self, key: str, default_value: Optional[Any] = None, lookup_class: Optional[str] = None
) -> Any:
"""
Look up a key in the Ambassador module's "defaults" element.
The "lookup class" is
- the lookup_class parameter if one was passed, else
- self.de... |
Look up a key in the Ambassador module's "defaults" element.
The "lookup class" is
- the lookup_class parameter if one was passed, else
- self.default_class if that's set, else
- None.
We can look in two places for key -- the first match wins:
1. defaults[look... | lookup_default | python | emissary-ingress/emissary | python/ambassador/ir/irresource.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irresource.py | Apache-2.0 |
def lookup(
self,
key: str,
*args,
default_class: Optional[str] = None,
default_key: Optional[str] = None
) -> Any:
"""
Look up a key in this IRResource, with a fallback to the Ambassador module's "defaults"
element.
Here's the resolution orde... |
Look up a key in this IRResource, with a fallback to the Ambassador module's "defaults"
element.
Here's the resolution order:
- if key is present in self, use its value.
- if not, use lookup_default above to try to find a value in the Ambassador module
- if we don't fi... | lookup | python | emissary-ingress/emissary | python/ambassador/ir/irresource.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irresource.py | Apache-2.0 |
def __init__(
self,
ir: "IR",
aconf: Config,
rkey: str = "ir.tlsmodule",
kind: str = "IRTLSModule",
name: str = "ir.tlsmodule",
enabled: bool = True,
**kwargs
) -> None:
"""
Initialize an IRAmbassadorTLS from the raw fields of its Resou... |
Initialize an IRAmbassadorTLS from the raw fields of its Resource.
| __init__ | python | emissary-ingress/emissary | python/ambassador/ir/irtls.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irtls.py | Apache-2.0 |
def from_legacy(
cls,
ir: "IR",
name: str,
rkey: str,
location: str,
cert: "IRAmbassadorTLS",
termination: bool,
validation_ca: Optional["IRAmbassadorTLS"],
) -> "IRTLSContext":
"""
Create an IRTLSContext from a legacy TLS-module style ... |
Create an IRTLSContext from a legacy TLS-module style definition.
'cert' is the TLS certificate that we'll offer to our peer -- for a termination
context, this is our server cert, and for an origination context, it's our client
cert.
For termination contexts, 'validation_ca' m... | from_legacy | python | emissary-ingress/emissary | python/ambassador/ir/irtlscontext.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irtlscontext.py | Apache-2.0 |
def hostglob_matches(g1: str, g2: str) -> bool:
"""
hostglob_matches determines whether or not two given DNS globs are
compatible with each other, i.e. whether or not there can be a hostname
that matches both globs.
Note that it does not actually find such a hostname: a return of True
just mean... |
hostglob_matches determines whether or not two given DNS globs are
compatible with each other, i.e. whether or not there can be a hostname
that matches both globs.
Note that it does not actually find such a hostname: a return of True
just means that such a hostname could exist.
| hostglob_matches | python | emissary-ingress/emissary | python/ambassador/ir/irutils.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador/ir/irutils.py | Apache-2.0 |
def diag(self) -> Optional[Diagnostics]:
"""
It turns out to be expensive to generate the Diagnostics class, so
app.diag is a property that does it on demand, handling Timers and
the config lock for you.
You MUST NOT already hold the config_lock or the diag_lock when
try... |
It turns out to be expensive to generate the Diagnostics class, so
app.diag is a property that does it on demand, handling Timers and
the config lock for you.
You MUST NOT already hold the config_lock or the diag_lock when
trying to read app.diag.
You MUST already have... | diag | python | emissary-ingress/emissary | python/ambassador_diag/diagd.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador_diag/diagd.py | Apache-2.0 |
def _generate_diagnostics(self) -> Optional[Diagnostics]:
"""
Do the heavy lifting of generating Diagnostics for our current configuration.
Really, only the diag() property should be calling this method, but if you
are convinced that you need to call it from elsewhere:
1. You're... |
Do the heavy lifting of generating Diagnostics for our current configuration.
Really, only the diag() property should be calling this method, but if you
are convinced that you need to call it from elsewhere:
1. You're almost certainly wrong about needing to call it from elsewhere.
... | _generate_diagnostics | python | emissary-ingress/emissary | python/ambassador_diag/diagd.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador_diag/diagd.py | Apache-2.0 |
def internal_handler(f):
"""
Reject requests where the remote address is not localhost. See the docstring
for _is_local_request() for important caveats!
"""
func_name = getattr(f, "__name__", "<anonymous>")
@functools.wraps(f)
def wrapper(*args, **kwds):
if not _is_local_request():
... |
Reject requests where the remote address is not localhost. See the docstring
for _is_local_request() for important caveats!
| internal_handler | python | emissary-ingress/emissary | python/ambassador_diag/diagd.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador_diag/diagd.py | Apache-2.0 |
def _is_local_request() -> bool:
"""
Determine if this request originated with localhost.
We rely on healthcheck_server.go setting the X-Ambassador-Diag-IP header for us
(and we rely on it overwriting anything that's already there!).
It might be possible to consider the environment variables SERVE... |
Determine if this request originated with localhost.
We rely on healthcheck_server.go setting the X-Ambassador-Diag-IP header for us
(and we rely on it overwriting anything that's already there!).
It might be possible to consider the environment variables SERVER_NAME and
SERVER_PORT instead, as t... | _is_local_request | python | emissary-ingress/emissary | python/ambassador_diag/diagd.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador_diag/diagd.py | Apache-2.0 |
def _allow_diag_ui() -> bool:
"""
Helper function to check if diag ui traffic is allowed or not
based on the different flags from the config:
* diagnostics.enabled: Enable to diag UI by adding mappings
* diagnostics.allow_non_local: Allow non local traffic
even whe... |
Helper function to check if diag ui traffic is allowed or not
based on the different flags from the config:
* diagnostics.enabled: Enable to diag UI by adding mappings
* diagnostics.allow_non_local: Allow non local traffic
even when diagnotics UI is disabled.
... | _allow_diag_ui | python | emissary-ingress/emissary | python/ambassador_diag/diagd.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador_diag/diagd.py | Apache-2.0 |
def main(
snapshot_path=None,
bootstrap_path=None,
ads_path=None,
*,
dev_magic=False,
config_path=None,
ambex_pid=0,
kick=None,
banner_endpoint="http://127.0.0.1:8500/banner",
metrics_endpoint="http://127.0.0.1:8500/metrics",
k8s=False,
no_checks=False,
no_envoy=False... |
Run the diagnostic daemon.
Arguments:
SNAPSHOT_PATH
Path to directory in which to save configuration snapshots and dynamic secrets
BOOTSTRAP_PATH
Path to which to write bootstrap Envoy configuration
ADS_PATH
Path to which to write ADS Envoy configuration
| main | python | emissary-ingress/emissary | python/ambassador_diag/diagd.py | https://github.com/emissary-ingress/emissary/blob/master/python/ambassador_diag/diagd.py | Apache-2.0 |
def strip_version(ver: str):
"""
strip_version is needed to strip a major/minor version of non-standard symbols. For example, when working with GKE,
`kubectl version` returns a minor version like '14+', which is not semver or any standard version, for that matter.
So we handle exceptions like that here.... |
strip_version is needed to strip a major/minor version of non-standard symbols. For example, when working with GKE,
`kubectl version` returns a minor version like '14+', which is not semver or any standard version, for that matter.
So we handle exceptions like that here.
:param ver: version string
... | strip_version | python | emissary-ingress/emissary | python/kat/harness.py | https://github.com/emissary-ingress/emissary/blob/master/python/kat/harness.py | Apache-2.0 |
def quote(arg):
r"""
>>> quote('\t')
'\\\t'
>>> quote('foo bar')
'foo\\ bar'
"""
# This is the logic emacs uses
if arg:
return _quote_pos.sub("\\\\", arg).replace("\n", "'\n'")
else:
return "''" |
>>> quote('\t')
'\\\t'
>>> quote('foo bar')
'foo\\ bar'
| quote | python | emissary-ingress/emissary | python/kat/utils.py | https://github.com/emissary-ingress/emissary/blob/master/python/kat/utils.py | Apache-2.0 |
def test_tracing_zipkin_invalid_collector_version():
"""test to ensure that providing an improper value will result in an error and the tracer not included"""
yaml = """
---
apiVersion: getambassador.io/v3alpha1
kind: TracingService
metadata:
name: myts
namespace: default
spec:
service: zipkin-test... | test to ensure that providing an improper value will result in an error and the tracer not included | test_tracing_zipkin_invalid_collector_version | python | emissary-ingress/emissary | python/tests/integration/test_tracing.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/integration/test_tracing.py | Apache-2.0 |
def install_ambassador(namespace, single_namespace=True, envs=None, debug=None):
"""
Install Ambassador into a given namespace. NOTE WELL that although there
is a 'single_namespace' parameter, this function probably needs work to do
the fully-correct thing with single_namespace False.
:param namesp... |
Install Ambassador into a given namespace. NOTE WELL that although there
is a 'single_namespace' parameter, this function probably needs work to do
the fully-correct thing with single_namespace False.
:param namespace: namespace to install Ambassador in
:param single_namespace: should we set AMBAS... | install_ambassador | python | emissary-ingress/emissary | python/tests/integration/utils.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/integration/utils.py | Apache-2.0 |
def test_irauth_grpcservice_version_v2():
"""Test to ensure that setting protocol_version to will cause an error"""
yaml = """
---
apiVersion: getambassador.io/v3alpha1
kind: AuthService
metadata:
name: mycoolauthservice
namespace: default
spec:
auth_service: someservice
protocol_version: "v2"
proto... | Test to ensure that setting protocol_version to will cause an error | test_irauth_grpcservice_version_v2 | python | emissary-ingress/emissary | python/tests/unit/test_irauth.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irauth.py | Apache-2.0 |
def test_basic_http_redirect_with_no_authservice():
"""Test that http --> https redirect route exists when no AuthService is provided
and verify that the typed_per_filter_config is NOT included
"""
yaml = """
apiVersion: getambassador.io/v3alpha1
kind: Mapping
metadata:
name: ambassador
namespace: ... | Test that http --> https redirect route exists when no AuthService is provided
and verify that the typed_per_filter_config is NOT included
| test_basic_http_redirect_with_no_authservice | python | emissary-ingress/emissary | python/tests/unit/test_irauth.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irauth.py | Apache-2.0 |
def test_redirects_disables_ext_authz():
"""Test that the ext_authz is disabled on envoy redirect routes
for https_redirects and host_redirects. This is to ensure that the
redirect occurs before making any calls to the ext_authz service
"""
if EDGE_STACK:
pytest.xfail("XFailing for now, cus... | Test that the ext_authz is disabled on envoy redirect routes
for https_redirects and host_redirects. This is to ensure that the
redirect occurs before making any calls to the ext_authz service
| test_redirects_disables_ext_authz | python | emissary-ingress/emissary | python/tests/unit/test_irauth.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irauth.py | Apache-2.0 |
def test_irlogservice_http_defaults():
"""tests defaults for log service when http driver is used and ensures that transport protocol is v3"""
yaml = (
"""
---
apiVersion: getambassador.io/v3alpha1
kind: LogService
metadata:
name: myls
namespace: default
spec:
service: """
+ SERVICE_NAME
... | tests defaults for log service when http driver is used and ensures that transport protocol is v3 | test_irlogservice_http_defaults | python | emissary-ingress/emissary | python/tests/unit/test_irlogservice.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irlogservice.py | Apache-2.0 |
def test_irlogservice_http_default_overrides():
"""tests default overrides for log service and ensures that transport protocol is v3"""
yaml = (
"""
---
apiVersion: getambassador.io/v3alpha1
kind: LogService
metadata:
name: myls
namespace: default
spec:
service: """
+ SERVICE_NAME
... | tests default overrides for log service and ensures that transport protocol is v3 | test_irlogservice_http_default_overrides | python | emissary-ingress/emissary | python/tests/unit/test_irlogservice.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irlogservice.py | Apache-2.0 |
def test_irlogservice_http_v2():
"""ensures that no longer supported v2 transport protocol is defaulted to v3"""
yaml = (
"""
---
apiVersion: getambassador.io/v3alpha1
kind: LogService
metadata:
name: myls
namespace: default
spec:
service: """
+ SERVICE_NAME
+ """
driver: http
... | ensures that no longer supported v2 transport protocol is defaulted to v3 | test_irlogservice_http_v2 | python | emissary-ingress/emissary | python/tests/unit/test_irlogservice.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irlogservice.py | Apache-2.0 |
def test_irlogservice_http_v3():
"""ensures that when transport protocol v3 is provided, nothing is logged"""
yaml = (
"""
---
apiVersion: getambassador.io/v3alpha1
kind: LogService
metadata:
name: myls
namespace: default
spec:
service: """
+ SERVICE_NAME
+ """
driver: http
dr... | ensures that when transport protocol v3 is provided, nothing is logged | test_irlogservice_http_v3 | python | emissary-ingress/emissary | python/tests/unit/test_irlogservice.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irlogservice.py | Apache-2.0 |
def test_irlogservice_tcp_defaults():
"""tests defaults for log service using tcp driver and ensures that transport protocol is v3"""
yaml = (
"""
---
apiVersion: getambassador.io/v3alpha1
kind: LogService
metadata:
name: myls
namespace: default
spec:
service: """
+ SERVICE_NAME
+... | tests defaults for log service using tcp driver and ensures that transport protocol is v3 | test_irlogservice_tcp_defaults | python | emissary-ingress/emissary | python/tests/unit/test_irlogservice.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irlogservice.py | Apache-2.0 |
def test_irlogservice_tcp_default_overrides():
"""tests default overrides for log service with tcp driver and ensures that transport protocol is v3"""
yaml = (
"""
---
apiVersion: getambassador.io/v3alpha1
kind: LogService
metadata:
name: myls
namespace: default
spec:
service: """
+ SERVI... | tests default overrides for log service with tcp driver and ensures that transport protocol is v3 | test_irlogservice_tcp_default_overrides | python | emissary-ingress/emissary | python/tests/unit/test_irlogservice.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irlogservice.py | Apache-2.0 |
def test_irratelimit_error():
"""Test error no valid spec with service name"""
yaml = """
---
apiVersion: getambassador.io/v3alpha1
kind: RateLimitService
metadata:
name: myrls
namespace: default
spec: {}
"""
econf = _get_envoy_config(yaml)
conf = _get_rl_config(econf.as_dict())
assert not co... | Test error no valid spec with service name | test_irratelimit_error | python | emissary-ingress/emissary | python/tests/unit/test_irratelimit.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irratelimit.py | Apache-2.0 |
def test_irratelimit_overrides():
"""Test that default are properly overriden"""
yaml = """
---
apiVersion: getambassador.io/v3alpha1
kind: RateLimitService
metadata:
name: myrls
namespace: someotherns
spec:
service: {}
domain: otherdomain
timeout_ms: 500
tls: rl-tls-context
protocol_version: v3
... | Test that default are properly overriden | test_irratelimit_overrides | python | emissary-ingress/emissary | python/tests/unit/test_irratelimit.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_irratelimit.py | Apache-2.0 |
def _ensure_alt_svc_header_injected(listener, expectedAltSvc):
"""helper function to ensure that the alt-svc header is getting injected properly"""
filter_chains = listener["filter_chains"]
for filter_chain in filter_chains:
hcm_typed_config = filter_chain["filters"][0]["typed_config"]
virt... | helper function to ensure that the alt-svc header is getting injected properly | _ensure_alt_svc_header_injected | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def _verify_no_added_response_headers(listener):
"""helper function to ensure response_headers_to_add do not exist"""
filter_chains = listener["filter_chains"]
for filter_chain in filter_chains:
hcm_typed_config = filter_chain["filters"][0]["typed_config"]
virtual_hosts = hcm_typed_config["... | helper function to ensure response_headers_to_add do not exist | _verify_no_added_response_headers | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def test_socket_protocol(self):
"""ensure that we can identify the listener socket protocol based on the provided protocol and protocolStack"""
@dataclass
class TestCase:
name: str
protocol: Optional[str]
protocolStack: Optional[List[str]]
expecte... | ensure that we can identify the listener socket protocol based on the provided protocol and protocolStack | test_socket_protocol | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def test_http3_valid_quic_listener(self):
"""ensure that a valid http3 listener is created using QUIC"""
yaml = default_http3_listener_manifest()
econf = econf_compile(yaml)
listeners = econf["static_resources"]["listeners"]
assert len(listeners) == 2
# verify listene... | ensure that a valid http3 listener is created using QUIC | test_http3_valid_quic_listener | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def test_http3_missing_tls_context(self):
"""UDP listener supporting the Quic protocol requires that a the "transport_socket" be set
in the filter_chains due to the fact that QUIC requires TLS. Envoy will reject the configuration
if it is not found. This test ensures that the HTTP/3 Listener is ... | UDP listener supporting the Quic protocol requires that a the "transport_socket" be set
in the filter_chains due to the fact that QUIC requires TLS. Envoy will reject the configuration
if it is not found. This test ensures that the HTTP/3 Listener is dropped when a valid TLSContext is not available.
... | test_http3_missing_tls_context | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def test_http3_companion_listeners(self):
"""ensure that when we have companion http3 (udp)/tcp listeners bound to same port that we properly set
port reuse, and ensure the TCP listener broadcast http/3 support
"""
yaml = (
"""
---
apiVersion: getambassador.io/v3alpha1
kind:... | ensure that when we have companion http3 (udp)/tcp listeners bound to same port that we properly set
port reuse, and ensure the TCP listener broadcast http/3 support
| test_http3_companion_listeners | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def test_http3_non_matching_ports(self):
"""support having the http (tcp) listener to be bound to different address:port, by default
the alt-svc will not be injected. Note, this test ensures that envoy can be configured
this way and will not crash. However, due to developer not setting the `alt-... | support having the http (tcp) listener to be bound to different address:port, by default
the alt-svc will not be injected. Note, this test ensures that envoy can be configured
this way and will not crash. However, due to developer not setting the `alt-svc` most clients
will not be able to upgrad... | test_http3_non_matching_ports | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def test_listener_filterchain_vhost_generation(self):
"""Ensure that the Listener FilterChain and correct vhosts are generated based on the
provided Listener, Host and Mappings to ensure mutliple scenarios are covered such as
clients sending hostname:port and addressing h2/h3 connection re-use o... | Ensure that the Listener FilterChain and correct vhosts are generated based on the
provided Listener, Host and Mappings to ensure mutliple scenarios are covered such as
clients sending hostname:port and addressing h2/h3 connection re-use on parent domains
| test_listener_filterchain_vhost_generation | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def _cleanse_secrets(listeners: dict):
"""
For these tests the full path of the secret is not what is being tested. This will
mutate the listeners and remove secret paths and replace with static values so that when
diffing against expected results they don't cause varianc... |
For these tests the full path of the secret is not what is being tested. This will
mutate the listeners and remove secret paths and replace with static values so that when
diffing against expected results they don't cause variance in tests.
| _cleanse_secrets | python | emissary-ingress/emissary | python/tests/unit/test_listener.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_listener.py | Apache-2.0 |
def _get_envoy_config() -> EnvoyConfig:
"""Helper function for getting an envoy config with correctly initialized ready listener"""
aconf = Config()
secret_handler = NullSecretHandler(logger, None, None, "0")
ir = IR(aconf, file_checker=lambda path: True, secret_handler=secret_handler)
assert ir
... | Helper function for getting an envoy config with correctly initialized ready listener | _get_envoy_config | python | emissary-ingress/emissary | python/tests/unit/test_ready.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_ready.py | Apache-2.0 |
def _validate_ready_listener_config(econf: EnvoyConfig, expectedPort: int, readyLogEnabled: bool):
"""
Helper function that fails if the envoy config does not match an expected ready listener config
"""
conf = econf.as_dict()
readyListener = conf["static_resources"]["listeners"][0]
assert readyL... |
Helper function that fails if the envoy config does not match an expected ready listener config
| _validate_ready_listener_config | python | emissary-ingress/emissary | python/tests/unit/test_ready.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_ready.py | Apache-2.0 |
def test_ready_listener_custom():
"""
Test to ensure that the ready endpoint is configurable using the AMBASSADOR_READY_PORT and
AMBASSADOR_READY_LOG environment variables.
"""
os.environ["AMBASSADOR_READY_PORT"] = str(8010)
os.environ["AMBASSADOR_READY_LOG"] = str(True)
econf = _get_envoy_c... |
Test to ensure that the ready endpoint is configurable using the AMBASSADOR_READY_PORT and
AMBASSADOR_READY_LOG environment variables.
| test_ready_listener_custom | python | emissary-ingress/emissary | python/tests/unit/test_ready.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_ready.py | Apache-2.0 |
def test_ready_listener_default():
"""Test to ensure that the ready endpoint is configured with sensible defaults."""
# Unset environment variables that could have been set in an earlier test
os.environ.pop("AMBASSADOR_READY_PORT", None)
os.environ.pop("AMBASSADOR_READY_LOG", None)
econf = _get_envo... | Test to ensure that the ready endpoint is configured with sensible defaults. | test_ready_listener_default | python | emissary-ingress/emissary | python/tests/unit/test_ready.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_ready.py | Apache-2.0 |
def test_ready_listener_high_port():
"""
Test to ensure that the ready endpoint falls back to the default port if a port above 32767 is
used.
"""
os.environ["AMBASSADOR_READY_PORT"] = str(32767)
os.environ.pop("AMBASSADOR_READY_LOG", None)
econf = _get_envoy_config()
_validate_ready_list... |
Test to ensure that the ready endpoint falls back to the default port if a port above 32767 is
used.
| test_ready_listener_high_port | python | emissary-ingress/emissary | python/tests/unit/test_ready.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_ready.py | Apache-2.0 |
def test_ready_listener_invalid_logs():
"""
Test to ensure that invalid values passed to AMBASSADOR_READY_LOG are handled gracefully.
"""
os.environ.pop("AMBASSADOR_READY_PORT")
os.environ["AMBASSADOR_READY_LOG"] = "0.6666666666666666"
econf = _get_envoy_config()
_validate_ready_listener_con... |
Test to ensure that invalid values passed to AMBASSADOR_READY_LOG are handled gracefully.
| test_ready_listener_invalid_logs | python | emissary-ingress/emissary | python/tests/unit/test_ready.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_ready.py | Apache-2.0 |
def test_ready_listener_invalid_port():
"""
Test to ensure that an error is raised when an invalid port string is passed to
AMBASSADOR_READY_PORT.
"""
os.environ["AMBASSADOR_READY_PORT"] = "420/1337.abcd"
os.environ.pop("AMBASSADOR_READY_LOG", None)
with pytest.raises(ValueError):
ec... |
Test to ensure that an error is raised when an invalid port string is passed to
AMBASSADOR_READY_PORT.
| test_ready_listener_invalid_port | python | emissary-ingress/emissary | python/tests/unit/test_ready.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_ready.py | Apache-2.0 |
def test_ready_listener_zero_port():
"""
Test to ensure that the ready endpoint falls back to the default port if a zero port is used.
"""
os.environ["AMBASSADOR_READY_PORT"] = str(0)
os.environ.pop("AMBASSADOR_READY_LOG", None)
econf = _get_envoy_config()
_validate_ready_listener_config(eco... |
Test to ensure that the ready endpoint falls back to the default port if a zero port is used.
| test_ready_listener_zero_port | python | emissary-ingress/emissary | python/tests/unit/test_ready.py | https://github.com/emissary-ingress/emissary/blob/master/python/tests/unit/test_ready.py | Apache-2.0 |
def docker_pull(tag: str) -> str:
"""`docker pull` and then return the image ID"""
run(['docker', 'pull', tag])
return run_txtcapture(['docker', 'image', 'inspect', tag, '--format={{.Id}}']) | `docker pull` and then return the image ID | docker_pull | python | emissary-ingress/emissary | releng/lib/check_artifacts.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/check_artifacts.py | Apache-2.0 |
def git_check_clean(allow_staged: bool = False, allow_untracked: bool = False) -> None:
"""
Use `git status --porcelain` to check if the working tree is dirty.
If allow_staged is True, allow staged files, but no unstaged changes.
If allow_untracked is True, allow untracked files.
"""
cmdvec = [... |
Use `git status --porcelain` to check if the working tree is dirty.
If allow_staged is True, allow staged files, but no unstaged changes.
If allow_untracked is True, allow untracked files.
| git_check_clean | python | emissary-ingress/emissary | releng/lib/gitutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/gitutil.py | Apache-2.0 |
def run(args: List[str]) -> None:
"""run is like "subprocess.run(args)", but with helpful settings and
obeys "with capture_output(out)".
"""
if _capturing:
try:
subprocess.run(args, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
except subprocess.Cal... | run is like "subprocess.run(args)", but with helpful settings and
obeys "with capture_output(out)".
| run | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def run_bincapture(args: List[str]) -> bytes:
"""run is like "subprocess.run(args, capture_out=True, text=False)",
but with helpful settings and obeys "with capture_output(out)".
"""
if _capturing:
try:
return subprocess.run(args, check=True, capture_output=True).stdout
excep... | run is like "subprocess.run(args, capture_out=True, text=False)",
but with helpful settings and obeys "with capture_output(out)".
| run_bincapture | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def run_txtcapture(args: List[str]) -> str:
"""run is like "subprocess.run(args, capture_out=True, text=true)",
but with helpful settings and obeys "with capture_output(out)".
"""
if _capturing:
try:
out = subprocess.run(args, check=True, capture_output=True, text=True).stdout
... | run is like "subprocess.run(args, capture_out=True, text=true)",
but with helpful settings and obeys "with capture_output(out)".
| run_txtcapture | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def capture_output(log: io.StringIO) -> Generator[None, None, None]:
"""capture_output is like contextlib.redirect_stdout but also
redirects stderr, and also does some extra stuff so that we can
have run/run_bincapture/run_txtcapture functions that obey it.
"""
global _capturing
saved_capturing... | capture_output is like contextlib.redirect_stdout but also
redirects stderr, and also does some extra stuff so that we can
have run/run_bincapture/run_txtcapture functions that obey it.
| capture_output | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def _lex_char_or_cs(text: str) -> Tuple[str, str]:
"""Look atthe beginning of the given text and trim either a byte, or
an ANSI control sequence from the beginning, returning a tuple
("char-or-cs", "remaining-text"). If it looks like the text is a
truncated control seqence, then it doesn't trim anythin... | Look atthe beginning of the given text and trim either a byte, or
an ANSI control sequence from the beginning, returning a tuple
("char-or-cs", "remaining-text"). If it looks like the text is a
truncated control seqence, then it doesn't trim anything, and
returns ("", "original"); signaling that it nee... | _lex_char_or_cs | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def __init__(self, indent: str = "", output: Optional[TextIO] = None, columns: Optional[int] = None) -> None:
"""Arguments:
indent: str: The string to indent with.
output: Optional[TextIO]: A TextIO to write to, instead of
building an in-memory buffer.
columns: Op... | Arguments:
indent: str: The string to indent with.
output: Optional[TextIO]: A TextIO to write to, instead of
building an in-memory buffer.
columns: Optional[int]: How wide the terminal is; this is
imporant because a line wrap needs to trigger an
... | __init__ | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def input(self) -> str:
"""Use "myindent.input()" instead of "input()" in order to nest well
with LineTrackers.
"""
if hasattr(self._output, 'input'):
text: str = self._output.input() # type: ignore
else:
text = input()
return text | Use "myindent.input()" instead of "input()" in order to nest well
with LineTrackers.
| input | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def input(self) -> str:
"""Use "mylinetracker.input()" instead of "input()" to avoid the
LineTracker not seeing any newlines input by the user.
"""
if hasattr(self._output, 'input'):
text: str = self._output.input() # type: ignore
else:
text = input()
... | Use "mylinetracker.input()" instead of "input()" to avoid the
LineTracker not seeing any newlines input by the user.
| input | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def goto_line(self, line: int) -> None:
"""goto_line moves the cursor to the beginning of the given line;
where line 1 is the line that the LineTracker started on, line
0 is the line above that, and line 1 is the line below
that.
"""
self.write("\r")
if line < sel... | goto_line moves the cursor to the beginning of the given line;
where line 1 is the line that the LineTracker started on, line
0 is the line above that, and line 1 is the line below
that.
| goto_line | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def check(self, name: str, clear_on_success: bool = True) -> Generator['CheckResult', None, None]:
"""check returns a context manager that handles printing a '[....]' /
'[ OK ]' / '[FAIL]' check. While the check is running, it
will stream whatever you write to stdout/stderr. If
clear_... | check returns a context manager that handles printing a '[....]' /
'[ OK ]' / '[FAIL]' check. While the check is running, it
will stream whatever you write to stdout/stderr. If
clear_on_success is True, then once the check finishes, if the
check passed then it will erase that stdout/s... | check | python | emissary-ingress/emissary | releng/lib/uiutil.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/uiutil.py | Apache-2.0 |
def assert_eq(actual: Any, expected: Any) -> None:
"""`assert_eq(a, b)` is like `assert a == b`, but has a useful error
message when they're not equal.
"""
if actual != expected:
raise AssertionError(f"wanted '{expected}', got '{actual}'") | `assert_eq(a, b)` is like `assert a == b`, but has a useful error
message when they're not equal.
| assert_eq | python | emissary-ingress/emissary | releng/lib/__init__.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/__init__.py | Apache-2.0 |
def get_is_private() -> bool:
"""Return whether we're in a "private" Git checkout, for doing
embargoed work.
"""
remote_names = run_txtcapture(['git', 'remote']).split()
remote_urls: List[str] = []
for remote_name in remote_names:
remote_urls += run_txtcapture(['git', 'remote', 'get-url'... | Return whether we're in a "private" Git checkout, for doing
embargoed work.
| get_is_private | python | emissary-ingress/emissary | releng/lib/__init__.py | https://github.com/emissary-ingress/emissary/blob/master/releng/lib/__init__.py | Apache-2.0 |
def parse_members(filepath: str) -> Set[str]:
"""parse_members parses a .py file and returns a set of all of the
symbols exposed by file; whether they come from that file itself
or from its imports.
For example, given a file containing
from foo import bar
def baz():
pass
... | parse_members parses a .py file and returns a set of all of the
symbols exposed by file; whether they come from that file itself
or from its imports.
For example, given a file containing
from foo import bar
def baz():
pass
parse_members would return {'bar', 'baz'}.
I... | parse_members | python | emissary-ingress/emissary | tools/src/py-list-deps.py | https://github.com/emissary-ingress/emissary/blob/master/tools/src/py-list-deps.py | Apache-2.0 |
def parse_imports(filepath: str) -> List[ImportedItem]:
"""parse_imports parses a .py file and returns a list of all of the
things that the file imports.
"""
with open(filepath, 'r') as filehandle:
filecontent = filehandle.read()
imports = []
for node in ast.parse(filecontent, filename... | parse_imports parses a .py file and returns a list of all of the
things that the file imports.
| parse_imports | python | emissary-ingress/emissary | tools/src/py-list-deps.py | https://github.com/emissary-ingress/emissary/blob/master/tools/src/py-list-deps.py | Apache-2.0 |
def _make_layer(self, block, planes, blocks, stride=1, dcn_layers=0, dcn_interval=1):
""" Here one layer means a string of n Bottleneck blocks. """
downsample = None
# This is actually just to create the connection between layers, and not necessarily to
# downsample. Even if the second ... | Here one layer means a string of n Bottleneck blocks. | _make_layer | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def forward(self, x):
""" Returns a list of convouts for each layer. """
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
outs = []
for layer in self.layers:
x = layer(x)
outs.append(x)
return tuple(outs) | Returns a list of convouts for each layer. | forward | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def init_backbone(self, path):
""" Initializes the backbone weights for training. """
state_dict = torch.load(path)
# Replace layer1 -> layers.0 etc.
keys = list(state_dict)
for key in keys:
if key.startswith('layer'):
idx = int(key[5])
... | Initializes the backbone weights for training. | init_backbone | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def init_backbone(self, path):
""" The path here comes from detectron. So we load it differently. """
with open(path, 'rb') as f:
state_dict = pickle.load(f, encoding='latin1') # From the detectron source
state_dict = state_dict['blobs']
our_state_dict_keys = lis... | The path here comes from detectron. So we load it differently. | init_backbone | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def darknetconvlayer(in_channels, out_channels, *args, **kwdargs):
"""
Implements a conv, activation, then batch norm.
Arguments are passed into the conv layer.
"""
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, *args, **kwdargs, bias=False),
nn.BatchNorm2d(out_channels),... |
Implements a conv, activation, then batch norm.
Arguments are passed into the conv layer.
| darknetconvlayer | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def _make_layer(self, block, channels, num_blocks, stride=2):
""" Here one layer means a string of n blocks. """
layer_list = []
# The downsample layer
layer_list.append(
darknetconvlayer(self.in_channels, channels * block.expansion,
kernel_size=... | Here one layer means a string of n blocks. | _make_layer | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def _make_layer(self, cfg):
"""
Each layer is a sequence of conv layers usually preceded by a max pooling.
Adapted from torchvision.models.vgg.make_layers.
"""
layers = []
for v in cfg:
# VGG in SSD requires some special layers, so allow layers to be tuples ... |
Each layer is a sequence of conv layers usually preceded by a max pooling.
Adapted from torchvision.models.vgg.make_layers.
| _make_layer | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def transform_key(self, k):
""" Transform e.g. features.24.bias to layers.4.1.bias """
vals = k.split('.')
layerIdx = self.state_dict_lookup[int(vals[0])]
return 'layers.%s.%s' % (layerIdx, vals[1]) | Transform e.g. features.24.bias to layers.4.1.bias | transform_key | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def add_layer(self, conv_channels=128, downsample=2):
""" Add a downsample layer to the backbone as per what SSD does. """
if len(self.extra_args) > 0:
conv_channels, downsample = self.extra_args.pop()
padding = 1 if downsample > 1 else 0
layer = nn.Sequenti... | Add a downsample layer to the backbone as per what SSD does. | add_layer | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def construct_backbone(cfg):
""" Constructs a backbone given a backbone config object (see config.py). """
backbone = cfg.type(*cfg.args)
# Add downsampling layers until we reach the number we need
num_layers = max(cfg.selected_layers) + 1
while len(backbone.layers) < num_layers:
backbone.... | Constructs a backbone given a backbone config object (see config.py). | construct_backbone | python | dbolya/yolact | backbone.py | https://github.com/dbolya/yolact/blob/master/backbone.py | MIT |
def prep_display(dets_out, img, h, w, undo_transform=True, class_color=False, mask_alpha=0.45, fps_str=''):
"""
Note: If undo_transform=False then im_h and im_w are allowed to be None.
"""
if undo_transform:
img_numpy = undo_image_transformation(img, w, h)
img_gpu = torch.Tensor(img_nump... |
Note: If undo_transform=False then im_h and im_w are allowed to be None.
| prep_display | python | dbolya/yolact | eval.py | https://github.com/dbolya/yolact/blob/master/eval.py | MIT |
def prep_coco_cats():
""" Prepare inverted table for category id lookup given a coco cats object. """
for coco_cat_id, transformed_cat_id_p1 in get_label_map().items():
transformed_cat_id = transformed_cat_id_p1 - 1
coco_cats[transformed_cat_id] = coco_cat_id
coco_cats_inv[coco_cat_id] =... | Prepare inverted table for category id lookup given a coco cats object. | prep_coco_cats | python | dbolya/yolact | eval.py | https://github.com/dbolya/yolact/blob/master/eval.py | MIT |
def add_bbox(self, image_id:int, category_id:int, bbox:list, score:float):
""" Note that bbox should be a list or tuple of (x1, y1, x2, y2) """
bbox = [bbox[0], bbox[1], bbox[2]-bbox[0], bbox[3]-bbox[1]]
# Round to the nearest 10th to avoid huge file sizes, as COCO suggests
bbox = [roun... | Note that bbox should be a list or tuple of (x1, y1, x2, y2) | add_bbox | python | dbolya/yolact | eval.py | https://github.com/dbolya/yolact/blob/master/eval.py | MIT |
def add_mask(self, image_id:int, category_id:int, segmentation:np.ndarray, score:float):
""" The segmentation should be the full mask, the size of the image and with size [h, w]. """
rle = pycocotools.mask.encode(np.asfortranarray(segmentation.astype(np.uint8)))
rle['counts'] = rle['counts'].dec... | The segmentation should be the full mask, the size of the image and with size [h, w]. | add_mask | python | dbolya/yolact | eval.py | https://github.com/dbolya/yolact/blob/master/eval.py | MIT |
def dump_web(self):
""" Dumps it in the format for my web app. Warning: bad code ahead! """
config_outs = ['preserve_aspect_ratio', 'use_prediction_module',
'use_yolo_regressors', 'use_prediction_matching',
'train_masks']
output = {
'i... | Dumps it in the format for my web app. Warning: bad code ahead! | dump_web | python | dbolya/yolact | eval.py | https://github.com/dbolya/yolact/blob/master/eval.py | MIT |
def prep_metrics(ap_data, dets, img, gt, gt_masks, h, w, num_crowd, image_id, detections:Detections=None):
""" Returns a list of APs for this image, with each element being for a class """
if not args.output_coco_json:
with timer.env('Prepare gt'):
gt_boxes = torch.Tensor(gt[:, :4])
... | Returns a list of APs for this image, with each element being for a class | prep_metrics | python | dbolya/yolact | eval.py | https://github.com/dbolya/yolact/blob/master/eval.py | MIT |
def badhash(x):
"""
Just a quick and dirty hash function for doing a deterministic shuffle based on image_id.
Source:
https://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key
"""
x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF
x = (((x ... |
Just a quick and dirty hash function for doing a deterministic shuffle based on image_id.
Source:
https://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key
| badhash | python | dbolya/yolact | eval.py | https://github.com/dbolya/yolact/blob/master/eval.py | MIT |
def no_inf_mean(x:torch.Tensor):
"""
Computes the mean of a vector, throwing out all inf values.
If there are no non-inf values, this will return inf (i.e., just the normal mean).
"""
no_inf = [a for a in x if torch.isfinite(a)]
if len(no_inf) > 0:
return sum(no_inf) / len(no_inf)
... |
Computes the mean of a vector, throwing out all inf values.
If there are no non-inf values, this will return inf (i.e., just the normal mean).
| no_inf_mean | python | dbolya/yolact | train.py | https://github.com/dbolya/yolact/blob/master/train.py | MIT |
def forward(self, x):
"""
Args:
- x: The convOut from a layer in the backbone network
Size: [batch_size, in_channels, conv_h, conv_w])
Returns a tuple (bbox_coords, class_confs, mask_output, prior_boxes) with sizes
- bbox_coords: [batch_size, conv_h*conv... |
Args:
- x: The convOut from a layer in the backbone network
Size: [batch_size, in_channels, conv_h, conv_w])
Returns a tuple (bbox_coords, class_confs, mask_output, prior_boxes) with sizes
- bbox_coords: [batch_size, conv_h*conv_w*num_priors, 4]
- c... | forward | python | dbolya/yolact | yolact.py | https://github.com/dbolya/yolact/blob/master/yolact.py | MIT |
def make_priors(self, conv_h, conv_w, device):
""" Note that priors are [x,y,width,height] where (x,y) is the center of the box. """
global prior_cache
size = (conv_h, conv_w)
with timer.env('makepriors'):
if self.last_img_size != (cfg._tmp_img_w, cfg._tmp_img_h):
... | Note that priors are [x,y,width,height] where (x,y) is the center of the box. | make_priors | python | dbolya/yolact | yolact.py | https://github.com/dbolya/yolact/blob/master/yolact.py | MIT |
def forward(self, convouts:List[torch.Tensor]):
"""
Args:
- convouts (list): A list of convouts for the corresponding layers in in_channels.
Returns:
- A list of FPN convouts in the same order as x with extra downsample layers if requested.
"""
out = []
... |
Args:
- convouts (list): A list of convouts for the corresponding layers in in_channels.
Returns:
- A list of FPN convouts in the same order as x with extra downsample layers if requested.
| forward | python | dbolya/yolact | yolact.py | https://github.com/dbolya/yolact/blob/master/yolact.py | MIT |
def load_weights(self, path):
""" Loads weights from a compressed save file. """
state_dict = torch.load(path)
# For backward compatability, remove these (the new variable is called layers)
for key in list(state_dict.keys()):
if key.startswith('backbone.layer') and not key.s... | Loads weights from a compressed save file. | load_weights | python | dbolya/yolact | yolact.py | https://github.com/dbolya/yolact/blob/master/yolact.py | MIT |
def freeze_bn(self, enable=False):
""" Adapted from https://discuss.pytorch.org/t/how-to-train-with-frozen-batchnorm/12106/8 """
for module in self.modules():
if isinstance(module, nn.BatchNorm2d):
module.train() if enable else module.eval()
module.weight.req... | Adapted from https://discuss.pytorch.org/t/how-to-train-with-frozen-batchnorm/12106/8 | freeze_bn | python | dbolya/yolact | yolact.py | https://github.com/dbolya/yolact/blob/master/yolact.py | MIT |
def forward(self, x):
""" The input should be of size [batch_size, 3, img_h, img_w] """
_, _, img_h, img_w = x.size()
cfg._tmp_img_h = img_h
cfg._tmp_img_w = img_w
with timer.env('backbone'):
outs = self.backbone(x)
if cfg.fpn is not None:
... | The input should be of size [batch_size, 3, img_h, img_w] | forward | python | dbolya/yolact | yolact.py | https://github.com/dbolya/yolact/blob/master/yolact.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.