code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
client = get_client()
mode = _detect_mode(server)
# list (even if not necessary) in order to make errors more consistent when
# mode='id'
endpoint, server_list = get_endpoint_w_server_list(endpoint_id)
if server_list == "S3":
raise click.UsageError("You cannot delete servers from... | def server_delete(endpoint_id, server) | Executor for `globus endpoint server show` | 5.828697 | 5.532363 | 1.053564 |
conf = get_config_obj()
section = "cli"
if "." in parameter:
section, parameter = parameter.split(".", 1)
# ensure that the section exists
if section not in conf:
conf[section] = {}
# remove the value for the given parameter
del conf[section][parameter]
# write to... | def remove_command(parameter) | Executor for `globus config remove` | 4.392763 | 3.951379 | 1.111704 |
client = get_client()
rule = client.get_endpoint_acl_rule(endpoint_id, rule_id)
formatted_print(
rule,
text_format=FORMAT_TEXT_RECORD,
fields=(
("Rule ID", "id"),
("Permissions", "permissions"),
("Shared With", _shared_with_keyfunc),
... | def show_command(endpoint_id, rule_id) | Executor for `globus endpoint permission show` | 4.302183 | 3.662919 | 1.174523 |
client = get_client()
bookmark_id = resolve_id_or_name(client, bookmark_id_or_name)["id"]
submit_data = {"name": new_bookmark_name}
res = client.update_bookmark(bookmark_id, submit_data)
formatted_print(res, simple_text="Success") | def bookmark_rename(bookmark_id_or_name, new_bookmark_name) | Executor for `globus bookmark rename` | 4.062651 | 3.949166 | 1.028736 |
section = "cli"
if "." in parameter:
section, parameter = parameter.split(".", 1)
value = lookup_option(parameter, section=section)
if value is None:
safeprint("{} not set".format(parameter))
else:
safeprint("{} = {}".format(parameter, value)) | def show_command(parameter) | Executor for `globus config show` | 3.808914 | 3.520519 | 1.081918 |
source_ep, source_path = source
dest_ep, dest_path = destination
if source_ep != dest_ep:
raise click.UsageError(
(
"rename requires that the source and dest "
"endpoints are the same, {} != {}"
).format(source_ep, dest_ep)
)
... | def rename_command(source, destination) | Executor for `globus rename` | 3.935797 | 3.551842 | 1.1081 |
client = get_client()
res = client.get_endpoint(endpoint_id)
formatted_print(
res,
text_format=FORMAT_TEXT_RECORD,
fields=GCP_FIELDS if res["is_globus_connect"] else STANDARD_FIELDS,
) | def endpoint_show(endpoint_id) | Executor for `globus endpoint show` | 6.923378 | 4.67963 | 1.479471 |
client = get_client()
rule_data = assemble_generic_doc("access", permissions=permissions)
res = client.update_endpoint_acl_rule(endpoint_id, rule_id, rule_data)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | def update_command(permissions, rule_id, endpoint_id) | Executor for `globus endpoint permission update` | 5.476789 | 5.062035 | 1.081934 |
name = self.name + ":"
if not self.multiline or "\n" not in val:
val = u"{0} {1}".format(name.ljust(self._text_prefix_len), val)
else:
spacer = "\n" + " " * (self._text_prefix_len + 1)
val = u"{0}{1}{2}".format(name, spacer, spacer.join(val.split("\n"... | def _format_value(self, val) | formats a value to be good for textmode printing
val must be unicode | 3.370336 | 3.204581 | 1.051724 |
client = get_client()
res = client.delete_endpoint_acl_rule(endpoint_id, rule_id)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | def delete_command(endpoint_id, rule_id) | Executor for `globus endpoint permission delete` | 3.805846 | 3.190028 | 1.193045 |
source_endpoint, cmd_source_path = source
dest_endpoint, cmd_dest_path = destination
if recursive and batch:
raise click.UsageError(
(
"You cannot use --recursive in addition to --batch. "
"Instead, use --recursive on lines of --batch input "
... | def transfer_command(
batch,
sync_level,
recursive,
destination,
source,
label,
preserve_mtime,
verify_checksum,
encrypt,
submission_id,
dry_run,
delete,
deadline,
skip_activation_check,
notify,
perf_cc,
perf_p,
perf_pp,
perf_udt,
) | Executor for `globus transfer` | 3.754602 | 3.7242 | 1.008163 |
client = get_client()
res = client.delete_endpoint(endpoint_id)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | def endpoint_delete(endpoint_id) | Executor for `globus endpoint delete` | 4.525231 | 3.342355 | 1.353905 |
client = get_client()
bookmark_id = resolve_id_or_name(client, bookmark_id_or_name)["id"]
res = client.delete_bookmark(bookmark_id)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | def bookmark_delete(bookmark_id_or_name) | Executor for `globus bookmark delete` | 3.429518 | 3.013771 | 1.137949 |
endpoint_id, path = endpoint_plus_path
client = get_client()
autoactivate(client, endpoint_id, if_expires_in=60)
res = client.operation_mkdir(endpoint_id, path=path)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | def mkdir_command(endpoint_plus_path) | Executor for `globus mkdir` | 5.261966 | 4.469487 | 1.177309 |
# now handle the output format, requires a little bit more care
# first, prompt if it isn't given, but be clear that we have a sensible
# default if they don't set it
# then, make sure that if it is given, it's a valid format (discard
# otherwise)
# finally, set it only if given and valid
... | def init_command(default_output_format, default_myproxy_username) | Executor for `globus config init` | 4.357028 | 4.199057 | 1.037621 |
# special behavior when invoked with only one non-keyword argument: act as
# a normal decorator, decorating and returning that argument with
# click.option
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return decorator(args[0])
# if we're not doing that, we should see n... | def detect_and_decorate(decorator, args, kwargs) | Helper for applying a decorator when it is applied directly, and also
applying it when it is given arguments and then applied to a function. | 8.158013 | 8.340841 | 0.97808 |
client = get_client()
rules = client.endpoint_acl_list(endpoint_id)
resolved_ids = LazyIdentityMap(
x["principal"] for x in rules if x["principal_type"] == "identity"
)
def principal_str(rule):
principal = rule["principal"]
if rule["principal_type"] == "identity":
... | def list_command(endpoint_id) | Executor for `globus endpoint permission list` | 3.937603 | 3.60465 | 1.092368 |
client = get_client()
bookmark_iterator = client.bookmark_list()
def get_ep_name(item):
ep_id = item["endpoint_id"]
try:
ep_doc = client.get_endpoint(ep_id)
return display_name_or_cname(ep_doc)
except TransferAPIError as err:
if err.code == ... | def bookmark_list() | Executor for `globus bookmark list` | 4.30067 | 3.959746 | 1.086098 |
endpoint_id, path = endpoint_plus_path
client = get_client()
# attempt to activate unless --skip-activation-check is given
if not skip_activation_check:
autoactivate(client, endpoint_id, if_expires_in=60)
delete_data = DeleteData(
client,
endpoint_id,
label=la... | def rm_command(
ignore_missing,
star_silent,
recursive,
enable_globs,
endpoint_plus_path,
label,
submission_id,
dry_run,
deadline,
skip_activation_check,
notify,
meow,
heartbeat,
polling_interval,
timeout,
timeout_exit_code,
) | Executor for `globus rm` | 5.542229 | 5.382156 | 1.029741 |
session_params = session_params or {}
# get the ConfidentialApp client object
auth_client = internal_auth_client(
requires_instance=True, force_new_client=force_new_client
)
# start the Confidential App Grant flow
auth_client.oauth2_start_flow(
redirect_uri=auth_client.bas... | def do_link_auth_flow(session_params=None, force_new_client=False) | Prompts the user with a link to authenticate with globus auth
and authorize the CLI to act on their behalf. | 4.60871 | 4.138063 | 1.113736 |
session_params = session_params or {}
# start local server and create matching redirect_uri
with start_local_server(listen=("127.0.0.1", 0)) as server:
_, port = server.socket.getsockname()
redirect_uri = "http://localhost:{}".format(port)
# get the ConfidentialApp client obje... | def do_local_server_auth_flow(session_params=None, force_new_client=False) | Starts a local http server, opens a browser to have the user authenticate,
and gets the code redirected to the server (no copy and pasting required) | 3.404349 | 3.364815 | 1.011749 |
# do a token exchange with the given code
tkn = auth_client.oauth2_exchange_code_for_tokens(auth_code)
tkn = tkn.by_resource_server
# extract access tokens from final response
transfer_at = tkn["transfer.api.globus.org"]["access_token"]
transfer_at_expires = tkn["transfer.api.globus.org"][... | def exchange_code_and_store_config(auth_client, auth_code) | Finishes auth flow after code is gotten from command line or local server.
Exchanges code for tokens and gets user info from auth.
Stores tokens and user info in config. | 2.057098 | 2.091945 | 0.983342 |
if filter_scope == "all" and not filter_fulltext:
raise click.UsageError(
"When searching all endpoints (--filter-scope=all, the default), "
"a full-text search filter is required. Other scopes (e.g. "
"--filter-scope=recently-used) may be used without specifying "
... | def endpoint_search(filter_fulltext, filter_owner_id, filter_scope) | Executor for `globus endpoint search` | 3.856616 | 3.703491 | 1.041346 |
# validate params. Requires a get call to check the endpoint type
client = get_client()
endpoint_id = kwargs.pop("endpoint_id")
get_res = client.get_endpoint(endpoint_id)
if get_res["host_endpoint_id"]:
endpoint_type = "shared"
elif get_res["is_globus_connect"]:
endpoint_ty... | def endpoint_update(**kwargs) | Executor for `globus endpoint update` | 4.558435 | 4.116077 | 1.107471 |
try:
click.echo(message, nl=newline, err=write_to_stderr)
except IOError as err:
if err.errno is errno.EPIPE:
pass
else:
raise | def safeprint(message, write_to_stderr=False, newline=True) | Wrapper around click.echo used to encapsulate its functionality.
Also protects against EPIPE during click.echo calls, as this can happen
normally in piped commands when the consumer closes before the producer. | 2.590398 | 2.103129 | 1.231688 |
# if the key is a string, then the "keyfunc" is just a basic lookup
# operation -- return that
if isinstance(k, six.string_types):
def lookup(x):
return x[k]
return lookup
# otherwise, the key must be a function which is executed on the item
# to produce a value --... | def _key_to_keyfunc(k) | We allow for 'keys' which are functions that map columns onto value
types -- they may do formatting or inspect multiple values on the
object. In order to support this, wrap string keys in a simple function
that does the natural lookup operation, but return any functions we
receive as they are. | 6.577641 | 6.028026 | 1.091177 |
def _assert_fields():
if fields is None:
raise ValueError(
"Internal Error! Output format requires fields; none given. "
"You can workaround this error by using `--format JSON`"
)
def _print_as_json():
print_json_response(
... | def formatted_print(
response_data,
simple_text=None,
text_preamble=None,
text_epilog=None,
text_format=FORMAT_TEXT_TABLE,
json_converter=None,
fields=None,
response_key=None,
) | A generic output formatter. Consumes the following pieces of data:
``response_data`` is a dict or GlobusResponse object. It contains either an
API response or synthesized data for printing.
``simple_text`` is a text override -- normal printing is skipped and this
string is printed instead (text output... | 2.864578 | 2.799264 | 1.023333 |
def decorate(f, **kwargs):
f = version_option(f)
f = debug_option(f)
f = verbose_option(f)
f = click.help_option("-h", "--help")(f)
# if the format option is being allowed, it needs to be applied to `f`
if not kwargs.get("no_format_option"):
... | def common_options(*args, **kwargs) | This is a multi-purpose decorator for applying a "base" set of options
shared by all commands.
It can be applied either directly, or given keyword arguments.
Usage:
>>> @common_options
>>> def mycommand(abc, xyz):
>>> ...
or
>>> @common_options(no_format_option=True)
>>> def ... | 4.170046 | 4.051369 | 1.029293 |
def decorate(f, **kwargs):
metavar = kwargs.get("metavar", "ENDPOINT_ID")
f = click.argument("endpoint_id", metavar=metavar, type=click.UUID)(f)
return f
return detect_and_decorate(decorate, args, kwargs) | def endpoint_id_arg(*args, **kwargs) | This is the `ENDPOINT_ID` argument consumed by many Transfer endpoint
related operations. It accepts alternate metavars for cases when another
name is desirable (e.x. `SHARE_ID`, `HOST_ENDPOINT_ID`), but can also be
applied as a direct decorator if no specialized metavar is being passed.
Usage:
>>... | 4.671589 | 5.509002 | 0.847992 |
# options only allowed for GCS endpoints
if endpoint_type != "server":
# catch params with two option flags
if params["public"] is False:
raise click.UsageError(
"Option --private only allowed " "for Globus Connect Server endpoints"
)
# catch ... | def validate_endpoint_create_and_update_params(endpoint_type, managed, params) | Given an endpoint type of "shared" "server" or "personal" and option values
Confirms the option values are valid for the given endpoint | 4.043339 | 4.027906 | 1.003831 |
def inner_decorator(f, required=True):
f = click.argument("TASK_ID", required=required)(f)
return f
return detect_and_decorate(inner_decorator, args, kwargs) | def task_id_arg(*args, **kwargs) | This is the `TASK_ID` argument consumed by many Transfer Task operations.
It accept a toggle on whether or not it is required
Usage:
>>> @task_id_option
>>> def command_func(task_id):
>>> ...
or
>>> @task_id_option(required=False)
>>> def command_func(task_id):
>>> ...
... | 6.990679 | 6.66918 | 1.048207 |
def notify_opt_callback(ctx, param, value):
# if no value was set, don't set any explicit options
# the API default is "everything on"
if value is None:
return {}
value = value.lower()
value = [x.strip() for x in value.split(",")]
# [""] is... | def task_submission_options(f) | Options shared by both transfer and delete task submission | 4.466328 | 4.450453 | 1.003567 |
def inner_decorator(f, supports_batch=True, default_enable_globs=False):
f = click.option(
"--recursive", "-r", is_flag=True, help="Recursively delete dirs"
)(f)
f = click.option(
"--ignore-missing",
"-f",
is_flag=True,
help="... | def delete_and_rm_options(*args, **kwargs) | Options which apply both to `globus delete` and `globus rm` | 4.593109 | 4.54295 | 1.011041 |
def port_range_callback(ctx, param, value):
if not value:
return None
value = value.lower().strip()
if value == "unspecified":
return None, None
if value == "unrestricted":
return 1024, 65535
try:
lower, upper = map(int,... | def server_add_and_update_opts(*args, **kwargs) | shared collection of options for `globus transfer endpoint server add` and
`globus transfer endpoint server update`.
Accepts a toggle to know if it's being used as `add` or `update`.
usage:
>>> @server_add_and_update_opts
>>> def command_func(subject, port, scheme, hostname):
>>> ...
... | 3.291533 | 3.215663 | 1.023594 |
client = get_client()
res = client.endpoint_deactivate(endpoint_id)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | def endpoint_deactivate(endpoint_id) | Executor for `globus endpoint deactivate` | 4.090173 | 3.183329 | 1.284873 |
def callback(ctx, param, value):
# copied from click.decorators.version_option
# no idea what resilient_parsing means, but...
if not value or ctx.resilient_parsing:
return
print_version()
ctx.exit(0)
return click.option(
"--version",
is... | def version_option(f) | Largely a custom clone of click.version_option -- almost identical, but
prints our special output. | 3.578222 | 3.206261 | 1.116011 |
# import in the func (rather than top-level scope) so that at setup time,
# `requests` isn't required -- otherwise, setuptools will fail to run
# because requests isn't installed yet.
import requests
try:
version_data = requests.get(
"https://pypi.python.org/pypi/globus-cli... | def get_versions() | Wrap in a function to ensure that we don't run this every time a CLI
command runs (yuck!)
Also protects import of `requests` from issues when grabbed by setuptools.
More on that inline | 5.950274 | 5.707717 | 1.042496 |
id_batch_size = 100
# fetch in batches of 100, store in a dict
ac = get_auth_client()
self._resolved_map = {}
for i in range(0, len(self.identity_ids), id_batch_size):
chunk = self.identity_ids[i : i + id_batch_size]
resolved_result = ac.get_iden... | def _lookup_identity_names(self) | Batch resolve identities to usernames.
Returns a dict mapping IDs to Usernames | 3.784033 | 3.433033 | 1.102242 |
# deny rwx to Group and World -- don't bother storing the returned old mask
# value, since we'll never restore it in the CLI anyway
# do this on every call to ensure that we're always consistent about it
os.umask(0o077)
# FIXME: DRY violation with config_commands.helpers
conf = get_config_... | def write_option(option, value, section="cli", system=False) | Write an option to disk -- doesn't handle config reloading | 13.236044 | 12.638718 | 1.047262 |
client_id = lookup_option(CLIENT_ID_OPTNAME)
client_secret = lookup_option(CLIENT_SECRET_OPTNAME)
template_id = lookup_option(TEMPLATE_ID_OPTNAME) or DEFAULT_TEMPLATE_ID
template_client = internal_native_client()
existing = client_id and client_secret
# if we are forcing a new client, dele... | def internal_auth_client(requires_instance=False, force_new_client=False) | Looks up the values for this CLI's Instance Client in config
If none exists and requires_instance is True or force_new_client is True,
registers a new Instance Client with GLobus Auth
If none exists and requires_instance is false, defaults to a Native Client
for backwards compatibility
Returns ei... | 3.214451 | 3.214765 | 0.999902 |
# get the mapping by looking up the state and getting the mapping attr
mapping = click.get_current_context().ensure_object(CommandState).http_status_map
# if there is a mapped exit code, exit with that. Otherwise, exit 1
if http_status in mapping:
sys.exit(mapping[http_status])
else:
... | def exit_with_mapped_status(http_status) | Given an HTTP Status, exit with either an error status of 1 or the
status mapped by what we were given. | 5.880183 | 5.285963 | 1.112415 |
safeprint(
"The resource you are trying to access requires you to "
"re-authenticate with specific identities."
)
params = exception.raw_json["authorization_parameters"]
message = params.get("session_message")
if message:
safeprint("message: {}".format(message))
id... | def session_hook(exception) | Expects an exception with an authorization_paramaters field in its raw_json | 5.260465 | 4.456117 | 1.180504 |
exception_type, exception, traceback = exc_info
# check if we're in debug mode, and run the real excepthook if we are
ctx = click.get_current_context()
state = ctx.ensure_object(CommandState)
if state.debug:
sys.excepthook(exception_type, exception, traceback)
# we're not in debug... | def custom_except_hook(exc_info) | A custom excepthook to present python errors produced by the CLI.
We don't want to show end users big scary stacktraces if they aren't python
programmers, so slim it down to some basic info. We keep a "DEBUGMODE" env
variable kicking around to let us turn on stacktraces if we ever need them.
Additional... | 5.271544 | 5.082068 | 1.037283 |
client = get_client()
# cannot filter by both errors and non errors
if filter_errors and filter_non_errors:
raise click.UsageError("Cannot filter by both errors and non errors")
elif filter_errors:
filter_string = "is_error:1"
elif filter_non_errors:
filter_string = "... | def task_event_list(task_id, limit, filter_errors, filter_non_errors) | Executor for `globus task-event-list` | 2.874465 | 2.788492 | 1.030831 |
client = get_client()
res = client.delete_endpoint_role(endpoint_id, role_id)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | def role_delete(role_id, endpoint_id) | Executor for `globus endpoint role delete` | 4.187709 | 3.10657 | 1.348017 |
endpoint_id, path = endpoint_plus_path
# do autoactivation before the `ls` call so that recursive invocations
# won't do this repeatedly, and won't have to instantiate new clients
client = get_client()
autoactivate(client, endpoint_id, if_expires_in=60)
# create the query paramaters to se... | def ls_command(
endpoint_plus_path,
recursive_depth_limit,
recursive,
long_output,
show_hidden,
filter_val,
) | Executor for `globus ls` | 6.279738 | 6.214505 | 1.010497 |
client = get_client()
res = client.get_submission_id()
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="value") | def generate_submission_id() | Executor for `globus task generate-submission-id` | 7.339444 | 5.120077 | 1.433463 |
if not principal:
raise click.UsageError("A security principal is required for this command")
endpoint_id, path = endpoint_plus_path
principal_type, principal_val = principal
client = get_client()
if principal_type == "identity":
principal_val = maybe_lookup_identity_id(princ... | def create_command(
principal, permissions, endpoint_plus_path, notify_email, notify_message
) | Executor for `globus endpoint permission create` | 3.262208 | 3.053898 | 1.068211 |
# BFS is not done until the queue is empty
while self.queue:
logger.debug(
(
"recursive_operation_ls BFS queue not empty, "
"getting next path now."
)
)
# rate limit based on number of l... | def iterable_func(self) | An internal function which has generator semantics. Defined using the
`yield` syntax.
Used to grab the first element during class initialization, and
subsequently on calls to `next()` to get the remaining elements.
We rely on the implicit StopIteration built into this type of function
... | 4.587988 | 4.708798 | 0.974344 |
client = get_client()
res = resolve_id_or_name(client, bookmark_id_or_name)
formatted_print(
res,
text_format=FORMAT_TEXT_RECORD,
fields=(
("ID", "id"),
("Name", "name"),
("Endpoint ID", "endpoint_id"),
("Path", "path"),
),... | def bookmark_show(bookmark_id_or_name) | Executor for `globus bookmark show` | 4.405262 | 3.961389 | 1.11205 |
client = get_client()
roles = client.endpoint_role_list(endpoint_id)
resolved_ids = LazyIdentityMap(
x["principal"] for x in roles if x["principal_type"] == "identity"
)
def principal_str(role):
principal = role["principal"]
if role["principal_type"] == "identity":
... | def role_list(endpoint_id) | Executor for `globus access endpoint-role-list` | 3.461578 | 3.060762 | 1.130953 |
# get the public key from the activation requirements
for data in requirements_data["DATA"]:
if data["type"] == "delegate_proxy" and data["name"] == "public_key":
public_key = data["value"]
break
else:
raise ValueError(
(
"No public_ke... | def fill_delegate_proxy_activation_requirements(
requirements_data, cred_file, lifetime_hours=12
) | Given the activation requirements for an endpoint and a filename for
X.509 credentials, extracts the public key from the activation
requirements, uses the key and the credentials to make a proxy credential,
and returns the requirements data with the proxy chain filled in. | 3.016012 | 2.630142 | 1.146711 |
# parse the issuer credential
loaded_cert, loaded_private_key, issuer_chain = parse_issuer_cred(issuer_cred)
# load the public_key into a cryptography object
loaded_public_key = serialization.load_pem_public_key(
public_key.encode("ascii"), backend=default_backend()
)
# check that... | def create_proxy_credentials(issuer_cred, public_key, lifetime_hours) | Given an issuer credentials PEM file in the form of a string, a public_key
string from an activation requirements document, and an int for the
proxy lifetime, returns credentials as a unicode string in PEM format
containing a new proxy certificate and an extended proxy chain. | 3.885947 | 3.430442 | 1.132783 |
# get each section of the PEM file
sections = re.findall(
"-----BEGIN.*?-----.*?-----END.*?-----", issuer_cred, flags=re.DOTALL
)
try:
issuer_cert = sections[0]
issuer_private_key = sections[1]
issuer_chain_certs = sections[2:]
except IndexError:
raise Va... | def parse_issuer_cred(issuer_cred) | Given an X509 PEM file in the form of a string, parses it into sections
by the PEM delimiters of: -----BEGIN <label>----- and -----END <label>----
Confirms the sections can be decoded in the proxy credential order of:
issuer cert, issuer private key, proxy chain of 0 or more certs .
Returns the issuer c... | 2.611737 | 2.258517 | 1.156395 |
builder = x509.CertificateBuilder()
# create a serial number for the new proxy
# Under RFC 3820 there are many ways to generate the serial number. However
# making the number unpredictable has security benefits, e.g. it can make
# this style of attack more difficult:
# http://www.win.tue.n... | def create_proxy_cert(
loaded_cert, loaded_private_key, loaded_public_key, lifetime_hours
) | Given cryptography objects for an issuing certificate, a public_key,
a private_key, and an int for lifetime in hours, creates a proxy
cert from the issuer and public key signed by the private key. | 4.562558 | 4.502545 | 1.013329 |
# Examine the last CommonName to see if it looks like an old proxy.
last_cn = loaded_cert.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)[
-1
]
# if the last CN is 'proxy' or 'limited proxy' we are in an old proxy
if last_cn.value in ("proxy", "limited proxy"):
rais... | def confirm_not_old_proxy(loaded_cert) | Given a cryptography object for the issuer cert, checks if the cert is
an "old proxy" and raise an error if so. | 4.252095 | 3.903697 | 1.089248 |
try:
key_usage = loaded_cert.extensions.get_extension_for_oid(
x509.oid.ExtensionOID.KEY_USAGE
)
if not key_usage.value.digital_signature:
raise ValueError(
"Certificate is using the keyUsage extension, but has "
"not asserted the ... | def validate_key_usage(loaded_cert) | Given a cryptography object for the issuer cert, checks that if
the keyUsage extension is being used that the digital signature
bit has been asserted. (As specified in RFC 3820 section 3.1.) | 3.104031 | 2.286453 | 1.357575 |
client = get_client()
res = client.task_pause_info(task_id)
def _custom_text_format(res):
explicit_pauses = [
field
for field in EXPLICIT_PAUSE_MSG_FIELDS
# n.b. some keys are absent for completed tasks
if res.get(field[1])
]
effe... | def task_pause_info(task_id) | Executor for `globus task pause-info` | 3.701973 | 3.568372 | 1.03744 |
self.timer = t.Thread(target=self.report_spans)
self.timer.daemon = True
self.timer.name = "Instana Span Reporting"
self.timer.start() | def run(self) | Span a background thread to periodically report queued spans | 7.128895 | 3.587037 | 1.987405 |
logger.debug("Span reporting thread is now alive")
def span_work():
queue_size = self.queue.qsize()
if queue_size > 0 and instana.singletons.agent.can_send():
response = instana.singletons.agent.report_traces(self.queued_spans())
if respo... | def report_spans(self) | Periodically report the queued spans | 7.538554 | 7.020245 | 1.073831 |
spans = []
while True:
try:
s = self.queue.get(False)
except queue.Empty:
break
else:
spans.append(s)
return spans | def queued_spans(self) | Get all of the spans in the queue | 2.898771 | 2.637657 | 1.098995 |
if instana.singletons.agent.can_send() or "INSTANA_TEST" in os.environ:
json_span = None
if span.operation_name in self.registered_spans:
json_span = self.build_registered_span(span)
else:
json_span = self.build_sdk_span(span)
... | def record_span(self, span) | Convert the passed BasicSpan into an JsonSpan and
add it to the span queue | 5.634379 | 4.907694 | 1.148071 |
custom_data = CustomData(tags=span.tags,
logs=self.collect_logs(span))
sdk_data = SDKData(name=span.operation_name,
custom=custom_data,
Type=self.get_span_kind_as_string(span))
if "arguments" in sp... | def build_sdk_span(self, span) | Takes a BasicSpan and converts into an SDK type JsonSpan | 3.953432 | 3.830538 | 1.032083 |
kind = None
if "span.kind" in span.tags:
if span.tags["span.kind"] in self.entry_kind:
kind = "entry"
elif span.tags["span.kind"] in self.exit_kind:
kind = "exit"
else:
kind = "intermediate"
return kind | def get_span_kind_as_string(self, span) | Will retrieve the `span.kind` tag and return the appropriate string value for the Instana backend or
None if the tag is set to something we don't recognize.
:param span: The span to search for the `span.kind` tag
:return: String | 2.731447 | 3.093182 | 0.883054 |
kind = None
if "span.kind" in span.tags:
if span.tags["span.kind"] in self.entry_kind:
kind = 1
elif span.tags["span.kind"] in self.exit_kind:
kind = 2
else:
kind = 3
return kind | def get_span_kind_as_int(self, span) | Will retrieve the `span.kind` tag and return the appropriate integer value for the Instana backend or
None if the tag is set to something we don't recognize.
:param span: The span to search for the `span.kind` tag
:return: Integer | 2.706776 | 3.123036 | 0.866713 |
pid = None
if os.path.exists("/proc/"):
sched_file = "/proc/%d/sched" % os.getpid()
if os.path.isfile(sched_file):
try:
file = open(sched_file)
line = file.readline()
g = re.search(r'\((\d+),',... | def __get_real_pid(self) | Attempts to determine the true process ID by querying the
/proc/<pid>/sched file. This works on systems with a proc filesystem.
Otherwise default to os default. | 2.671402 | 2.380981 | 1.121975 |
host = AGENT_DEFAULT_HOST
port = AGENT_DEFAULT_PORT
if "INSTANA_AGENT_HOST" in os.environ:
host = os.environ["INSTANA_AGENT_HOST"]
if "INSTANA_AGENT_PORT" in os.environ:
port = int(os.environ["INSTANA_AGENT_PORT"])
elif "INSTANA_AGENT_IP... | def __get_agent_host_port(self) | Iterates the the various ways the host and port of the Instana host
agent may be configured: default, env vars, sensor options... | 1.985195 | 1.762099 | 1.126608 |
self.thr = threading.Thread(target=self.collect_and_report)
self.thr.daemon = True
self.thr.name = "Instana Metric Collection"
self.thr.start() | def run(self) | Spawns the metric reporting thread | 5.084456 | 3.756227 | 1.353607 |
self.last_usage = None
self.last_collect = None
self.last_metrics = None
self.snapshot_countdown = 0
self.run() | def reset(self) | Reset the state as new | 9.668193 | 9.731617 | 0.993483 |
logger.debug("Metric reporting thread is now alive")
def metric_work():
self.process()
if self.agent.is_timed_out():
logger.warn("Host agent offline for >1 min. Going to sit in a corner...")
self.agent.reset()
return Fals... | def collect_and_report(self) | Target function for the metric reporting thread. This is a simple loop to
collect and report entity data every 1 second. | 15.33654 | 12.268646 | 1.25006 |
if self.agent.machine.fsm.current is "wait4init":
# Test the host agent if we're ready to send data
if self.agent.is_agent_ready():
self.agent.machine.fsm.ready()
else:
return
if self.agent.can_send():
self.snapsho... | def process(self) | Collects, processes & reports metrics | 6.545646 | 6.515701 | 1.004596 |
logger.debug("Received agent request with messageId: %s" % task["messageId"])
if "action" in task:
if task["action"] == "python.source":
payload = get_py_source(task["args"]["file"])
else:
message = "Unrecognized action: %s. An newer Insta... | def handle_agent_tasks(self, task) | When request(s) are received by the host agent, it is sent here
for handling & processing. | 6.123086 | 5.948083 | 1.029422 |
try:
if "INSTANA_SERVICE_NAME" in os.environ:
appname = os.environ["INSTANA_SERVICE_NAME"]
elif "FLASK_APP" in os.environ:
appname = os.environ["FLASK_APP"]
elif "DJANGO_SETTINGS_MODULE" in os.environ:
appname = os.envi... | def collect_snapshot(self) | Collects snapshot related information to this process and environment | 2.757502 | 2.70367 | 1.019911 |
try:
res = {}
m = sys.modules
for k in m:
# Don't report submodules (e.g. django.x, django.y, django.z)
# Skip modules that begin with underscore
if ('.' in k) or k[0] == '_':
continue
... | def collect_modules(self) | Collect up the list of modules in use | 3.340011 | 3.262331 | 1.023811 |
try:
g = None
u = resource.getrusage(resource.RUSAGE_SELF)
if gc_.isenabled():
c = list(gc_.get_count())
th = list(gc_.get_threshold())
g = GC(collect0=c[0] if not self.last_collect else c[0] - self.last_collect[0],
... | def collect_metrics(self) | Collect up and return various metrics | 1.698228 | 1.680798 | 1.01037 |
logger.debug("Spawning metric & trace reporting threads")
self.sensor.meter.run()
instana.singletons.tracer.recorder.run() | def start(self, e) | Starts the agent and required threads | 39.417225 | 35.812862 | 1.100644 |
self.reset()
self.sensor.handle_fork()
instana.singletons.tracer.handle_fork() | def handle_fork(self) | Forks happen. Here we handle them. | 21.714096 | 19.621658 | 1.106639 |
try:
rv = False
url = "http://%s:%s/" % (host, port)
response = self.client.get(url, timeout=0.8)
server_header = response.headers["Server"]
if server_header == AGENT_HEADER:
logger.debug("Host agent found on %s:%d" % (host, p... | def is_agent_listening(self, host, port) | Check if the Instana Agent is listening on <host> and <port>. | 3.288184 | 3.020079 | 1.088774 |
try:
url = self.__discovery_url()
logger.debug("making announce request to %s" % (url))
response = None
response = self.client.put(url,
data=self.to_json(discovery),
headers={"C... | def announce(self, discovery) | With the passed in Discovery class, attempt to announce to the host agent. | 3.77399 | 3.717904 | 1.015085 |
try:
response = self.client.head(self.__data_url(), timeout=0.8)
if response.status_code is 200:
return True
return False
except (requests.ConnectTimeout, requests.ConnectionError):
logger.debug("is_agent_ready: host agent connect... | def is_agent_ready(self) | Used after making a successful announce to test when the agent is ready to accept data. | 5.407058 | 4.923094 | 1.098305 |
try:
response = None
response = self.client.post(self.__data_url(),
data=self.to_json(entity_data),
headers={"Content-Type": "application/json"},
timeout=0.8)
... | def report_data(self, entity_data) | Used to report entity data (metrics & snapshot) to the host agent. | 4.00562 | 3.494295 | 1.146331 |
try:
response = None
response = self.client.post(self.__traces_url(),
data=self.to_json(spans),
headers={"Content-Type": "application/json"},
timeout=0.8)
... | def report_traces(self, spans) | Used to report entity data (metrics & snapshot) to the host agent. | 3.953918 | 3.530027 | 1.120081 |
try:
response = None
payload = json.dumps(data)
logger.debug("Task response is %s: %s" % (self.__response_url(message_id), payload))
response = self.client.post(self.__response_url(message_id),
data=payload,
... | def task_response(self, message_id, data) | When the host agent passes us a task and we do it, this function is used to
respond with the results of the task. | 2.862347 | 2.940212 | 0.973517 |
port = self.sensor.options.agent_port
if port == 0:
port = AGENT_DEFAULT_PORT
return "http://%s:%s/%s" % (self.host, port, AGENT_DISCOVERY_PATH) | def __discovery_url(self) | URL for announcing to the host agent | 4.453141 | 3.86194 | 1.153084 |
path = AGENT_DATA_PATH % self.from_.pid
return "http://%s:%s/%s" % (self.host, self.port, path) | def __data_url(self) | URL for posting metrics to the host agent. Only valid when announced. | 7.677797 | 6.068283 | 1.265234 |
path = AGENT_TRACES_PATH % self.from_.pid
return "http://%s:%s/%s" % (self.host, self.port, path) | def __traces_url(self) | URL for posting traces to the host agent. Only valid when announced. | 6.608247 | 5.946089 | 1.11136 |
if self.from_.pid != 0:
path = AGENT_RESPONSE_PATH % (self.from_.pid, message_id)
return "http://%s:%s/%s" % (self.host, self.port, path) | def __response_url(self, message_id) | URL for responding to agent requests. | 5.504188 | 4.701364 | 1.170764 |
global _current_pid
pid = os.getpid()
if _current_pid != pid:
_current_pid = pid
_rnd.seed(int(1000000 * time.time()) ^ pid)
id = format(_rnd.randint(0, 18446744073709551615), '02x')
if len(id) < 16:
id = id.zfill(16)
return id | def generate_id() | Generate a 64bit base 16 ID for use as a Span or Trace ID | 2.873039 | 2.610588 | 1.100533 |
if not isinstance(header, string_types):
return BAD_ID
try:
# Test that header is truly a hexadecimal value before we try to convert
int(header, 16)
length = len(header)
if length < 16:
# Left pad ID with zeros
header = header.zfill(16)
... | def header_to_id(header) | We can receive headers in the following formats:
1. unsigned base 16 hex string of variable length
2. [eventual]
:param header: the header to analyze, validate and convert (if needed)
:return: a valid ID to be used internal to the tracer | 5.255786 | 5.22285 | 1.006306 |
try:
return json.dumps(obj, default=lambda obj: {k.lower(): v for k, v in obj.__dict__.items()},
sort_keys=False, separators=(',', ':')).encode()
except Exception as e:
logger.info("to_json: ", e, obj) | def to_json(obj) | Convert obj to json. Used mostly to convert the classes in json_span.py until we switch to nested
dicts (or something better)
:param obj: the object to serialize to json
:return: json string | 3.371022 | 3.423267 | 0.984738 |
version = ""
try:
version = pkg_resources.get_distribution('instana').version
except pkg_resources.DistributionNotFound:
version = 'unknown'
finally:
return version | def package_version() | Determine the version of this package.
:return: String representing known version | 3.23316 | 4.014108 | 0.805449 |
path = None
try:
if qp is None:
return ''
if type(kwlist) is not list:
logger.debug("strip_secrets: bad keyword list")
return qp
# If there are no key=values, then just return
if not '=' in qp:
return qp
if '?' in q... | def strip_secrets(qp, matcher, kwlist) | This function will scrub the secrets from a query param string based on the passed in matcher and kwlist.
blah=1&secret=password&valid=true will result in blah=1&secret=<redacted>&valid=true
You can even pass in path query combinations:
/signup?blah=1&secret=password&valid=true will result in /signup?bla... | 1.904169 | 1.827124 | 1.042167 |
try:
# The first line is the header line
# We look for the line where the Destination is 00000000 - that is the default route
# The Gateway IP is encoded backwards in hex.
with open("/proc/self/net/route") as routes:
for line in routes:
parts = line.s... | def get_default_gateway() | Attempts to read /proc/self/net/route to determine the default gateway in use.
:return: String - the ip address of the default gateway or None if not found/possible/non-existant | 3.913753 | 3.583852 | 1.092052 |
try:
response = None
pysource = ""
if regexp_py.search(file) is None:
response = {"error": "Only Python source files are allowed. (*.py)"}
else:
with open(file, 'r') as pyfile:
pysource = pyfile.read()
response = {"data": pys... | def get_py_source(file) | Retrieves and returns the source code for any Python
files requested by the UI via the host agent
@param file [String] The fully qualified path to a file | 3.655565 | 3.784013 | 0.966055 |
next_time = time.time() + delay
while True:
time.sleep(max(0, next_time - time.time()))
try:
if task() is False:
break
except Exception:
logger.debug("Problem while executing repetitive task: %s" % name, exc_info=True)
# skip tasks i... | def every(delay, task, name) | Executes a task every `delay` seconds
:param delay: the delay in seconds
:param task: the method to run. The method should return False if you want the loop to stop.
:return: None | 3.778513 | 4.068224 | 0.928787 |
app = iWSGIMiddleware(app, *args, **kw)
return app | def make_middleware(app=None, *args, **kw) | Given an app, return that app wrapped in iWSGIMiddleware | 6.124726 | 3.24954 | 1.884798 |
try:
eum_file = open(os.path.dirname(__file__) + '/eum.js')
eum_src = Template(eum_file.read())
# Prepare the standard required IDs
ids = {}
ids['meta_kvs'] = ''
parent_span = tracer.active_span
if trace_id or parent_span:
ids['trace_id'] =... | def eum_snippet(trace_id=None, eum_api_key=None, meta={}) | Return an EUM snippet for use in views, templates and layouts that reports
client side metrics to Instana that will automagically be linked to the
current trace.
@param trace_id [optional] the trace ID to insert into the EUM string
@param eum_api_key [optional] the EUM API key from your Instana dashboa... | 4.632429 | 4.414193 | 1.04944 |
"Taken from BasicTracer so we can override generate_id calls to ours"
start_time = time.time() if start_time is None else start_time
# See if we have a parent_ctx in `references`
parent_ctx = None
if child_of is not None:
parent_ctx = (
child_of if i... | def start_span(self,
operation_name=None,
child_of=None,
references=None,
tags=None,
start_time=None,
ignore_active_span=False) | Taken from BasicTracer so we can override generate_id calls to ours | 3.398655 | 2.954326 | 1.150399 |
span.stack = []
frame_count = 0
tb = traceback.extract_stack()
tb.reverse()
for frame in tb:
if limit is not None and frame_count >= limit:
break
# Exclude Instana frames unless we're in dev mode
if "INSTANA_DEV" not ... | def __add_stack(self, span, limit=None) | Adds a backtrace to this span | 3.832941 | 3.592273 | 1.066996 |
if "INSTANA_DEV" in os.environ:
print("==============================================================")
print("Instana: Running flask hook")
print("==============================================================")
wrapt.wrap_function_wrapper('flask', 'Flask.__init__', wrapper) | def hook(module) | Hook method to install the Instana middleware into Flask | 7.172227 | 5.352134 | 1.340069 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.