repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
gc3-uzh-ch/elasticluster | elasticluster/subcommands.py | Stop.execute | def execute(self):
"""
Stops the cluster if it's running.
"""
cluster_name = self.params.cluster
creator = make_creator(self.params.config,
storage_path=self.params.storage)
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as err:
log.error("Cannot stop cluster `%s`: %s", cluster_name, err)
return os.EX_NOINPUT
if not self.params.yes:
confirm_or_abort(
"Do you want really want to stop cluster `{cluster_name}`?"
.format(cluster_name=cluster_name),
msg="Aborting upon user request.")
print("Destroying cluster `%s` ..." % cluster_name)
cluster.stop(force=self.params.force, wait=self.params.wait) | python | def execute(self):
"""
Stops the cluster if it's running.
"""
cluster_name = self.params.cluster
creator = make_creator(self.params.config,
storage_path=self.params.storage)
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as err:
log.error("Cannot stop cluster `%s`: %s", cluster_name, err)
return os.EX_NOINPUT
if not self.params.yes:
confirm_or_abort(
"Do you want really want to stop cluster `{cluster_name}`?"
.format(cluster_name=cluster_name),
msg="Aborting upon user request.")
print("Destroying cluster `%s` ..." % cluster_name)
cluster.stop(force=self.params.force, wait=self.params.wait) | [
"def",
"execute",
"(",
"self",
")",
":",
"cluster_name",
"=",
"self",
".",
"params",
".",
"cluster",
"creator",
"=",
"make_creator",
"(",
"self",
".",
"params",
".",
"config",
",",
"storage_path",
"=",
"self",
".",
"params",
".",
"storage",
")",
"try",
... | Stops the cluster if it's running. | [
"Stops",
"the",
"cluster",
"if",
"it",
"s",
"running",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/subcommands.py#L263-L282 | train | 205,300 |
gc3-uzh-ch/elasticluster | elasticluster/subcommands.py | Pause.execute | def execute(self):
"""Pause the cluster if it is running."""
cluster_name = self.params.cluster
creator = make_creator(self.params.config,
storage_path=self.params.storage)
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as e:
log.error("Cannot load cluster `%s`: %s", cluster_name, e)
return os.EX_NOINPUT
if not self.params.yes:
confirm_or_abort(
"Do you want really want to pause cluster `{cluster_name}`?"
.format(cluster_name=cluster_name),
msg="Aborting upon user request.")
print("Pausing cluster `%s` ..." % cluster_name)
cluster.pause() | python | def execute(self):
"""Pause the cluster if it is running."""
cluster_name = self.params.cluster
creator = make_creator(self.params.config,
storage_path=self.params.storage)
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as e:
log.error("Cannot load cluster `%s`: %s", cluster_name, e)
return os.EX_NOINPUT
if not self.params.yes:
confirm_or_abort(
"Do you want really want to pause cluster `{cluster_name}`?"
.format(cluster_name=cluster_name),
msg="Aborting upon user request.")
print("Pausing cluster `%s` ..." % cluster_name)
cluster.pause() | [
"def",
"execute",
"(",
"self",
")",
":",
"cluster_name",
"=",
"self",
".",
"params",
".",
"cluster",
"creator",
"=",
"make_creator",
"(",
"self",
".",
"params",
".",
"config",
",",
"storage_path",
"=",
"self",
".",
"params",
".",
"storage",
")",
"try",
... | Pause the cluster if it is running. | [
"Pause",
"the",
"cluster",
"if",
"it",
"is",
"running",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/subcommands.py#L300-L316 | train | 205,301 |
gc3-uzh-ch/elasticluster | elasticluster/subcommands.py | Resume.execute | def execute(self):
"""Resume the cluster if it is paused."""
cluster_name = self.params.cluster
creator = make_creator(self.params.config,
storage_path=self.params.storage)
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as e:
log.error("Cannot load cluster `%s`: %s", cluster_name, e)
return os.EX_NOINPUT
print("Resuming cluster `%s` ..." % cluster_name)
cluster.resume() | python | def execute(self):
"""Resume the cluster if it is paused."""
cluster_name = self.params.cluster
creator = make_creator(self.params.config,
storage_path=self.params.storage)
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as e:
log.error("Cannot load cluster `%s`: %s", cluster_name, e)
return os.EX_NOINPUT
print("Resuming cluster `%s` ..." % cluster_name)
cluster.resume() | [
"def",
"execute",
"(",
"self",
")",
":",
"cluster_name",
"=",
"self",
".",
"params",
".",
"cluster",
"creator",
"=",
"make_creator",
"(",
"self",
".",
"params",
".",
"config",
",",
"storage_path",
"=",
"self",
".",
"params",
".",
"storage",
")",
"try",
... | Resume the cluster if it is paused. | [
"Resume",
"the",
"cluster",
"if",
"it",
"is",
"paused",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/subcommands.py#L331-L342 | train | 205,302 |
gc3-uzh-ch/elasticluster | elasticluster/subcommands.py | ListNodes.execute | def execute(self):
"""
Lists all nodes within the specified cluster with certain
information like id and ip.
"""
creator = make_creator(self.params.config,
storage_path=self.params.storage)
cluster_name = self.params.cluster
try:
cluster = creator.load_cluster(cluster_name)
if self.params.update:
cluster.update()
except (ClusterNotFound, ConfigurationError) as ex:
log.error("Listing nodes from cluster %s: %s", cluster_name, ex)
return
if self.params.pretty_json:
print(json.dumps(cluster, default=dict, indent=4))
elif self.params.json:
print(json.dumps(cluster, default=dict))
else:
print(cluster_summary(cluster))
for cls in cluster.nodes:
print("%s nodes:" % cls)
print("")
for node in cluster.nodes[cls]:
txt = [" " + i for i in node.pprint().splitlines()]
print(' - ' + "\n".join(txt)[4:])
print("") | python | def execute(self):
"""
Lists all nodes within the specified cluster with certain
information like id and ip.
"""
creator = make_creator(self.params.config,
storage_path=self.params.storage)
cluster_name = self.params.cluster
try:
cluster = creator.load_cluster(cluster_name)
if self.params.update:
cluster.update()
except (ClusterNotFound, ConfigurationError) as ex:
log.error("Listing nodes from cluster %s: %s", cluster_name, ex)
return
if self.params.pretty_json:
print(json.dumps(cluster, default=dict, indent=4))
elif self.params.json:
print(json.dumps(cluster, default=dict))
else:
print(cluster_summary(cluster))
for cls in cluster.nodes:
print("%s nodes:" % cls)
print("")
for node in cluster.nodes[cls]:
txt = [" " + i for i in node.pprint().splitlines()]
print(' - ' + "\n".join(txt)[4:])
print("") | [
"def",
"execute",
"(",
"self",
")",
":",
"creator",
"=",
"make_creator",
"(",
"self",
".",
"params",
".",
"config",
",",
"storage_path",
"=",
"self",
".",
"params",
".",
"storage",
")",
"cluster_name",
"=",
"self",
".",
"params",
".",
"cluster",
"try",
... | Lists all nodes within the specified cluster with certain
information like id and ip. | [
"Lists",
"all",
"nodes",
"within",
"the",
"specified",
"cluster",
"with",
"certain",
"information",
"like",
"id",
"and",
"ip",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/subcommands.py#L641-L669 | train | 205,303 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster.keys | def keys(self):
"""Only expose some of the attributes when using as a dictionary"""
keys = Struct.keys(self)
for key in (
'_cloud_provider',
'_naming_policy',
'_setup_provider',
'known_hosts_file',
'repository',
):
if key in keys:
keys.remove(key)
return keys | python | def keys(self):
"""Only expose some of the attributes when using as a dictionary"""
keys = Struct.keys(self)
for key in (
'_cloud_provider',
'_naming_policy',
'_setup_provider',
'known_hosts_file',
'repository',
):
if key in keys:
keys.remove(key)
return keys | [
"def",
"keys",
"(",
"self",
")",
":",
"keys",
"=",
"Struct",
".",
"keys",
"(",
"self",
")",
"for",
"key",
"in",
"(",
"'_cloud_provider'",
",",
"'_naming_policy'",
",",
"'_setup_provider'",
",",
"'known_hosts_file'",
",",
"'repository'",
",",
")",
":",
"if"... | Only expose some of the attributes when using as a dictionary | [
"Only",
"expose",
"some",
"of",
"the",
"attributes",
"when",
"using",
"as",
"a",
"dictionary"
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L252-L264 | train | 205,304 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster.add_node | def add_node(self, kind, image_id, image_user, flavor,
security_group, image_userdata='', name=None, **extra):
"""
Adds a new node to the cluster. This factory method provides an
easy way to add a new node to the cluster by specifying all relevant
parameters. The node does not get started nor setup automatically,
this has to be done manually afterwards.
:param str kind: kind of node to start. this refers to the
groups defined in the ansible setup provider
:py:class:`elasticluster.providers.AnsibleSetupProvider`
Please note that this can only contain
alphanumeric characters and hyphens (and must
not end with a digit), as it is used to build
a valid hostname
:param str image_id: image id to use for the cloud instance (e.g.
ami on amazon)
:param str image_user: user to login on given image
:param str flavor: machine type to use for cloud instance
:param str security_group: security group that defines firewall rules
to the instance
:param str image_userdata: commands to execute after instance starts
:param str name: name of this node, automatically generated if None
:raises: ValueError: `kind` argument is an invalid string.
:return: created :py:class:`Node`
"""
if not self._NODE_KIND_RE.match(kind):
raise ValueError(
"Invalid name `{kind}`. The `kind` argument may only contain"
" alphanumeric characters, and must not end with a digit."
.format(kind=kind))
if kind not in self.nodes:
self.nodes[kind] = []
# To ease json dump/load, use `extra` dictionary to
# instantiate Node class
extra.update(
cloud_provider=self._cloud_provider,
cluster_name=self.name,
flavor=flavor,
image_id=image_id,
image_user=image_user,
image_userdata=image_userdata,
kind=kind,
security_group=security_group,
)
for attr in (
'flavor',
'image_id',
'image_user',
'image_userdata',
'security_group',
'user_key_name',
'user_key_private',
'user_key_public',
):
if attr not in extra:
extra[attr] = getattr(self, attr)
if not name:
# `extra` contains key `kind` already
name = self._naming_policy.new(**extra)
else:
self._naming_policy.use(kind, name)
node = Node(name=name, **extra)
self.nodes[kind].append(node)
return node | python | def add_node(self, kind, image_id, image_user, flavor,
security_group, image_userdata='', name=None, **extra):
"""
Adds a new node to the cluster. This factory method provides an
easy way to add a new node to the cluster by specifying all relevant
parameters. The node does not get started nor setup automatically,
this has to be done manually afterwards.
:param str kind: kind of node to start. this refers to the
groups defined in the ansible setup provider
:py:class:`elasticluster.providers.AnsibleSetupProvider`
Please note that this can only contain
alphanumeric characters and hyphens (and must
not end with a digit), as it is used to build
a valid hostname
:param str image_id: image id to use for the cloud instance (e.g.
ami on amazon)
:param str image_user: user to login on given image
:param str flavor: machine type to use for cloud instance
:param str security_group: security group that defines firewall rules
to the instance
:param str image_userdata: commands to execute after instance starts
:param str name: name of this node, automatically generated if None
:raises: ValueError: `kind` argument is an invalid string.
:return: created :py:class:`Node`
"""
if not self._NODE_KIND_RE.match(kind):
raise ValueError(
"Invalid name `{kind}`. The `kind` argument may only contain"
" alphanumeric characters, and must not end with a digit."
.format(kind=kind))
if kind not in self.nodes:
self.nodes[kind] = []
# To ease json dump/load, use `extra` dictionary to
# instantiate Node class
extra.update(
cloud_provider=self._cloud_provider,
cluster_name=self.name,
flavor=flavor,
image_id=image_id,
image_user=image_user,
image_userdata=image_userdata,
kind=kind,
security_group=security_group,
)
for attr in (
'flavor',
'image_id',
'image_user',
'image_userdata',
'security_group',
'user_key_name',
'user_key_private',
'user_key_public',
):
if attr not in extra:
extra[attr] = getattr(self, attr)
if not name:
# `extra` contains key `kind` already
name = self._naming_policy.new(**extra)
else:
self._naming_policy.use(kind, name)
node = Node(name=name, **extra)
self.nodes[kind].append(node)
return node | [
"def",
"add_node",
"(",
"self",
",",
"kind",
",",
"image_id",
",",
"image_user",
",",
"flavor",
",",
"security_group",
",",
"image_userdata",
"=",
"''",
",",
"name",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"if",
"not",
"self",
".",
"_NODE_KIND_R... | Adds a new node to the cluster. This factory method provides an
easy way to add a new node to the cluster by specifying all relevant
parameters. The node does not get started nor setup automatically,
this has to be done manually afterwards.
:param str kind: kind of node to start. this refers to the
groups defined in the ansible setup provider
:py:class:`elasticluster.providers.AnsibleSetupProvider`
Please note that this can only contain
alphanumeric characters and hyphens (and must
not end with a digit), as it is used to build
a valid hostname
:param str image_id: image id to use for the cloud instance (e.g.
ami on amazon)
:param str image_user: user to login on given image
:param str flavor: machine type to use for cloud instance
:param str security_group: security group that defines firewall rules
to the instance
:param str image_userdata: commands to execute after instance starts
:param str name: name of this node, automatically generated if None
:raises: ValueError: `kind` argument is an invalid string.
:return: created :py:class:`Node` | [
"Adds",
"a",
"new",
"node",
"to",
"the",
"cluster",
".",
"This",
"factory",
"method",
"provides",
"an",
"easy",
"way",
"to",
"add",
"a",
"new",
"node",
"to",
"the",
"cluster",
"by",
"specifying",
"all",
"relevant",
"parameters",
".",
"The",
"node",
"does... | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L294-L370 | train | 205,305 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster.add_nodes | def add_nodes(self, kind, num, image_id, image_user, flavor,
security_group, image_userdata='', **extra):
"""Helper method to add multiple nodes of the same kind to a cluster.
:param str kind: kind of node to start. this refers to the groups
defined in the ansible setup provider
:py:class:`elasticluster.providers.AnsibleSetupProvider`
:param int num: number of nodes to add of this kind
:param str image_id: image id to use for the cloud instance (e.g.
ami on amazon)
:param str image_user: user to login on given image
:param str flavor: machine type to use for cloud instance
:param str security_group: security group that defines firewall rules
to the instance
:param str image_userdata: commands to execute after instance starts
"""
for i in range(num):
self.add_node(kind, image_id, image_user, flavor,
security_group, image_userdata=image_userdata, **extra) | python | def add_nodes(self, kind, num, image_id, image_user, flavor,
security_group, image_userdata='', **extra):
"""Helper method to add multiple nodes of the same kind to a cluster.
:param str kind: kind of node to start. this refers to the groups
defined in the ansible setup provider
:py:class:`elasticluster.providers.AnsibleSetupProvider`
:param int num: number of nodes to add of this kind
:param str image_id: image id to use for the cloud instance (e.g.
ami on amazon)
:param str image_user: user to login on given image
:param str flavor: machine type to use for cloud instance
:param str security_group: security group that defines firewall rules
to the instance
:param str image_userdata: commands to execute after instance starts
"""
for i in range(num):
self.add_node(kind, image_id, image_user, flavor,
security_group, image_userdata=image_userdata, **extra) | [
"def",
"add_nodes",
"(",
"self",
",",
"kind",
",",
"num",
",",
"image_id",
",",
"image_user",
",",
"flavor",
",",
"security_group",
",",
"image_userdata",
"=",
"''",
",",
"*",
"*",
"extra",
")",
":",
"for",
"i",
"in",
"range",
"(",
"num",
")",
":",
... | Helper method to add multiple nodes of the same kind to a cluster.
:param str kind: kind of node to start. this refers to the groups
defined in the ansible setup provider
:py:class:`elasticluster.providers.AnsibleSetupProvider`
:param int num: number of nodes to add of this kind
:param str image_id: image id to use for the cloud instance (e.g.
ami on amazon)
:param str image_user: user to login on given image
:param str flavor: machine type to use for cloud instance
:param str security_group: security group that defines firewall rules
to the instance
:param str image_userdata: commands to execute after instance starts | [
"Helper",
"method",
"to",
"add",
"multiple",
"nodes",
"of",
"the",
"same",
"kind",
"to",
"a",
"cluster",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L372-L396 | train | 205,306 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster._check_starting_nodes | def _check_starting_nodes(self, nodes, lapse):
"""
Wait until all given nodes are alive, for max `lapse` seconds.
"""
with timeout(lapse, raise_timeout_error):
try:
while nodes:
nodes = set(node for node in nodes
if not node.is_alive())
if nodes:
log.debug("Waiting for %d more nodes to come up ...", len(nodes))
time.sleep(self.polling_interval)
except TimeoutError:
log.error("Some nodes did not start correctly"
" within the given %d-seconds timeout: %s",
lapse, ', '.join(node.name for node in nodes))
# return list of not-yet-started nodes,
# so we can exclude them from coming rounds
return nodes | python | def _check_starting_nodes(self, nodes, lapse):
"""
Wait until all given nodes are alive, for max `lapse` seconds.
"""
with timeout(lapse, raise_timeout_error):
try:
while nodes:
nodes = set(node for node in nodes
if not node.is_alive())
if nodes:
log.debug("Waiting for %d more nodes to come up ...", len(nodes))
time.sleep(self.polling_interval)
except TimeoutError:
log.error("Some nodes did not start correctly"
" within the given %d-seconds timeout: %s",
lapse, ', '.join(node.name for node in nodes))
# return list of not-yet-started nodes,
# so we can exclude them from coming rounds
return nodes | [
"def",
"_check_starting_nodes",
"(",
"self",
",",
"nodes",
",",
"lapse",
")",
":",
"with",
"timeout",
"(",
"lapse",
",",
"raise_timeout_error",
")",
":",
"try",
":",
"while",
"nodes",
":",
"nodes",
"=",
"set",
"(",
"node",
"for",
"node",
"in",
"nodes",
... | Wait until all given nodes are alive, for max `lapse` seconds. | [
"Wait",
"until",
"all",
"given",
"nodes",
"are",
"alive",
"for",
"max",
"lapse",
"seconds",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L588-L606 | train | 205,307 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster._gather_node_ip_addresses | def _gather_node_ip_addresses(self, nodes, lapse, ssh_timeout, remake=False):
"""
Connect via SSH to each node.
Return set of nodes that could not be reached with `lapse` seconds.
"""
# for convenience, we might set this to ``None`` if the file cannot
# be opened -- but we do not want to forget the cluster-wide
# setting in case the error is transient
known_hosts_path = self.known_hosts_file
# If run with remake=True, deletes known_hosts_file so that it will
# be recreated. Prevents "Invalid host key" errors
if remake and os.path.isfile(known_hosts_path):
os.remove(known_hosts_path)
# Create the file if it's not present, otherwise the
# following lines will raise an error
try:
fd = open(known_hosts_path, 'a')
fd.close()
except IOError as err:
log.warning("Error opening SSH 'known hosts' file `%s`: %s",
known_hosts_path, err)
known_hosts_path = None
keys = paramiko.hostkeys.HostKeys(known_hosts_path)
with timeout(lapse, raise_timeout_error):
try:
while nodes:
for node in copy(nodes):
ssh = node.connect(
keyfile=known_hosts_path,
timeout=ssh_timeout)
if ssh:
log.info("Connection to node `%s` successful,"
" using IP address %s to connect.",
node.name, node.connection_ip())
# Add host keys to the keys object.
for host, key in ssh.get_host_keys().items():
for keytype, keydata in key.items():
keys.add(host, keytype, keydata)
self._save_keys_to_known_hosts_file(keys)
nodes.remove(node)
if nodes:
time.sleep(self.polling_interval)
except TimeoutError:
log.error(
"Some nodes of the cluster were unreachable"
" within the given %d-seconds timeout: %s",
lapse, ', '.join(node.name for node in nodes))
# return list of nodes
return nodes | python | def _gather_node_ip_addresses(self, nodes, lapse, ssh_timeout, remake=False):
"""
Connect via SSH to each node.
Return set of nodes that could not be reached with `lapse` seconds.
"""
# for convenience, we might set this to ``None`` if the file cannot
# be opened -- but we do not want to forget the cluster-wide
# setting in case the error is transient
known_hosts_path = self.known_hosts_file
# If run with remake=True, deletes known_hosts_file so that it will
# be recreated. Prevents "Invalid host key" errors
if remake and os.path.isfile(known_hosts_path):
os.remove(known_hosts_path)
# Create the file if it's not present, otherwise the
# following lines will raise an error
try:
fd = open(known_hosts_path, 'a')
fd.close()
except IOError as err:
log.warning("Error opening SSH 'known hosts' file `%s`: %s",
known_hosts_path, err)
known_hosts_path = None
keys = paramiko.hostkeys.HostKeys(known_hosts_path)
with timeout(lapse, raise_timeout_error):
try:
while nodes:
for node in copy(nodes):
ssh = node.connect(
keyfile=known_hosts_path,
timeout=ssh_timeout)
if ssh:
log.info("Connection to node `%s` successful,"
" using IP address %s to connect.",
node.name, node.connection_ip())
# Add host keys to the keys object.
for host, key in ssh.get_host_keys().items():
for keytype, keydata in key.items():
keys.add(host, keytype, keydata)
self._save_keys_to_known_hosts_file(keys)
nodes.remove(node)
if nodes:
time.sleep(self.polling_interval)
except TimeoutError:
log.error(
"Some nodes of the cluster were unreachable"
" within the given %d-seconds timeout: %s",
lapse, ', '.join(node.name for node in nodes))
# return list of nodes
return nodes | [
"def",
"_gather_node_ip_addresses",
"(",
"self",
",",
"nodes",
",",
"lapse",
",",
"ssh_timeout",
",",
"remake",
"=",
"False",
")",
":",
"# for convenience, we might set this to ``None`` if the file cannot",
"# be opened -- but we do not want to forget the cluster-wide",
"# settin... | Connect via SSH to each node.
Return set of nodes that could not be reached with `lapse` seconds. | [
"Connect",
"via",
"SSH",
"to",
"each",
"node",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L608-L663 | train | 205,308 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster.stop | def stop(self, force=False, wait=False):
"""
Terminate all VMs in this cluster and delete its repository.
:param bool force:
remove cluster from storage even if not all nodes could be stopped.
"""
log.debug("Stopping cluster `%s` ...", self.name)
failed = self._stop_all_nodes(wait)
if failed:
if force:
self._delete_saved_data()
log.warning(
"Not all cluster nodes have been terminated."
" However, as requested, data about the cluster"
" has been removed from local storage.")
else:
self.repository.save_or_update(self)
log.warning(
"Not all cluster nodes have been terminated."
" Fix errors above and re-run `elasticluster stop %s`",
self.name)
else:
self._delete_saved_data() | python | def stop(self, force=False, wait=False):
"""
Terminate all VMs in this cluster and delete its repository.
:param bool force:
remove cluster from storage even if not all nodes could be stopped.
"""
log.debug("Stopping cluster `%s` ...", self.name)
failed = self._stop_all_nodes(wait)
if failed:
if force:
self._delete_saved_data()
log.warning(
"Not all cluster nodes have been terminated."
" However, as requested, data about the cluster"
" has been removed from local storage.")
else:
self.repository.save_or_update(self)
log.warning(
"Not all cluster nodes have been terminated."
" Fix errors above and re-run `elasticluster stop %s`",
self.name)
else:
self._delete_saved_data() | [
"def",
"stop",
"(",
"self",
",",
"force",
"=",
"False",
",",
"wait",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"\"Stopping cluster `%s` ...\"",
",",
"self",
".",
"name",
")",
"failed",
"=",
"self",
".",
"_stop_all_nodes",
"(",
"wait",
")",
"if"... | Terminate all VMs in this cluster and delete its repository.
:param bool force:
remove cluster from storage even if not all nodes could be stopped. | [
"Terminate",
"all",
"VMs",
"in",
"this",
"cluster",
"and",
"delete",
"its",
"repository",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L732-L757 | train | 205,309 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster.pause | def pause(self):
"""Pause all VMs in this cluster and store data so that they
can be restarted later.
"""
log.info("Pausing cluster `%s` ...", self.name)
failed = self._pause_all_nodes()
if os.path.exists(self.known_hosts_file):
os.remove(self.known_hosts_file)
self.repository.save_or_update(self)
if failed:
log.warning(
"Not all cluster nodes have been successfully "
"stopped. Some nodes may still be running - "
"check error messages above and consider "
"re-running `elasticluster pause %s` if "
"necessary.", self.name) | python | def pause(self):
"""Pause all VMs in this cluster and store data so that they
can be restarted later.
"""
log.info("Pausing cluster `%s` ...", self.name)
failed = self._pause_all_nodes()
if os.path.exists(self.known_hosts_file):
os.remove(self.known_hosts_file)
self.repository.save_or_update(self)
if failed:
log.warning(
"Not all cluster nodes have been successfully "
"stopped. Some nodes may still be running - "
"check error messages above and consider "
"re-running `elasticluster pause %s` if "
"necessary.", self.name) | [
"def",
"pause",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Pausing cluster `%s` ...\"",
",",
"self",
".",
"name",
")",
"failed",
"=",
"self",
".",
"_pause_all_nodes",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"known_ho... | Pause all VMs in this cluster and store data so that they
can be restarted later. | [
"Pause",
"all",
"VMs",
"in",
"this",
"cluster",
"and",
"store",
"data",
"so",
"that",
"they",
"can",
"be",
"restarted",
"later",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L759-L774 | train | 205,310 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster.resume | def resume(self):
"""
Resume all paused VMs in this cluster.
"""
log.info("Resuming cluster `%s` ...", self.name)
failed = self._resume_all_nodes()
for node in self.get_all_nodes():
node.update_ips()
self._gather_node_ip_addresses(
self.get_all_nodes(), self.start_timeout, self.ssh_probe_timeout)
self.repository.save_or_update(self)
if failed:
log.warning(
"Not all cluster nodes have been successfully "
"restarted. Check error messages above and consider "
"re-running `elasticluster resume %s` if "
"necessary.", self.name)
return
if not self._setup_provider.resume_cluster(self):
log.warning("Elasticluster was not able to guarantee that the "
"cluster restarted correctly - check the errors "
"above and check your config.") | python | def resume(self):
"""
Resume all paused VMs in this cluster.
"""
log.info("Resuming cluster `%s` ...", self.name)
failed = self._resume_all_nodes()
for node in self.get_all_nodes():
node.update_ips()
self._gather_node_ip_addresses(
self.get_all_nodes(), self.start_timeout, self.ssh_probe_timeout)
self.repository.save_or_update(self)
if failed:
log.warning(
"Not all cluster nodes have been successfully "
"restarted. Check error messages above and consider "
"re-running `elasticluster resume %s` if "
"necessary.", self.name)
return
if not self._setup_provider.resume_cluster(self):
log.warning("Elasticluster was not able to guarantee that the "
"cluster restarted correctly - check the errors "
"above and check your config.") | [
"def",
"resume",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Resuming cluster `%s` ...\"",
",",
"self",
".",
"name",
")",
"failed",
"=",
"self",
".",
"_resume_all_nodes",
"(",
")",
"for",
"node",
"in",
"self",
".",
"get_all_nodes",
"(",
")",
":",
... | Resume all paused VMs in this cluster. | [
"Resume",
"all",
"paused",
"VMs",
"in",
"this",
"cluster",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L776-L797 | train | 205,311 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster._stop_all_nodes | def _stop_all_nodes(self, wait=False):
"""
Terminate all cluster nodes. Return number of failures.
"""
failed = 0
for node in self.get_all_nodes():
if not node.instance_id:
log.warning(
"Node `%s` has no instance ID."
" Assuming it did not start correctly,"
" so removing it anyway from the cluster.", node.name)
self.nodes[node.kind].remove(node)
continue
# try and stop node
try:
# wait and pause for and recheck.
node.stop(wait)
self.nodes[node.kind].remove(node)
log.debug(
"Removed node `%s` from cluster `%s`", node.name, self.name)
except InstanceNotFoundError as err:
log.info(
"Node `%s` (instance ID `%s`) was not found;"
" assuming it has already been terminated.",
node.name, node.instance_id)
except Exception as err:
failed += 1
log.error(
"Could not stop node `%s` (instance ID `%s`): %s %s",
node.name, node.instance_id, err, err.__class__)
return failed | python | def _stop_all_nodes(self, wait=False):
"""
Terminate all cluster nodes. Return number of failures.
"""
failed = 0
for node in self.get_all_nodes():
if not node.instance_id:
log.warning(
"Node `%s` has no instance ID."
" Assuming it did not start correctly,"
" so removing it anyway from the cluster.", node.name)
self.nodes[node.kind].remove(node)
continue
# try and stop node
try:
# wait and pause for and recheck.
node.stop(wait)
self.nodes[node.kind].remove(node)
log.debug(
"Removed node `%s` from cluster `%s`", node.name, self.name)
except InstanceNotFoundError as err:
log.info(
"Node `%s` (instance ID `%s`) was not found;"
" assuming it has already been terminated.",
node.name, node.instance_id)
except Exception as err:
failed += 1
log.error(
"Could not stop node `%s` (instance ID `%s`): %s %s",
node.name, node.instance_id, err, err.__class__)
return failed | [
"def",
"_stop_all_nodes",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"failed",
"=",
"0",
"for",
"node",
"in",
"self",
".",
"get_all_nodes",
"(",
")",
":",
"if",
"not",
"node",
".",
"instance_id",
":",
"log",
".",
"warning",
"(",
"\"Node `%s` has... | Terminate all cluster nodes. Return number of failures. | [
"Terminate",
"all",
"cluster",
"nodes",
".",
"Return",
"number",
"of",
"failures",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L805-L836 | train | 205,312 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster._pause_all_nodes | def _pause_all_nodes(self, max_thread_pool_size=0):
"""Pause all cluster nodes - ensure that we store data so that in
the future the nodes can be restarted.
:return: int - number of failures.
"""
failed = 0
def _pause_specific_node(node):
if not node.instance_id:
log.warning("Node `%s` has no instance id."
" It is either already stopped, or"
" never created properly. Not attempting"
" to stop it again.", node.name)
return None
try:
return node.pause()
except Exception as err:
log.error(
"Could not stop node `%s` (instance ID `%s`): %s %s",
node.name, node.instance_id, err, err.__class__)
node.update_ips()
return None
nodes = self.get_all_nodes()
thread_pool = self._make_thread_pool(max_thread_pool_size)
for node, state in zip(nodes, thread_pool.map(_pause_specific_node, nodes)):
if state is None:
failed += 1
else:
self.paused_nodes[node.name] = state
return failed | python | def _pause_all_nodes(self, max_thread_pool_size=0):
"""Pause all cluster nodes - ensure that we store data so that in
the future the nodes can be restarted.
:return: int - number of failures.
"""
failed = 0
def _pause_specific_node(node):
if not node.instance_id:
log.warning("Node `%s` has no instance id."
" It is either already stopped, or"
" never created properly. Not attempting"
" to stop it again.", node.name)
return None
try:
return node.pause()
except Exception as err:
log.error(
"Could not stop node `%s` (instance ID `%s`): %s %s",
node.name, node.instance_id, err, err.__class__)
node.update_ips()
return None
nodes = self.get_all_nodes()
thread_pool = self._make_thread_pool(max_thread_pool_size)
for node, state in zip(nodes, thread_pool.map(_pause_specific_node, nodes)):
if state is None:
failed += 1
else:
self.paused_nodes[node.name] = state
return failed | [
"def",
"_pause_all_nodes",
"(",
"self",
",",
"max_thread_pool_size",
"=",
"0",
")",
":",
"failed",
"=",
"0",
"def",
"_pause_specific_node",
"(",
"node",
")",
":",
"if",
"not",
"node",
".",
"instance_id",
":",
"log",
".",
"warning",
"(",
"\"Node `%s` has no i... | Pause all cluster nodes - ensure that we store data so that in
the future the nodes can be restarted.
:return: int - number of failures. | [
"Pause",
"all",
"cluster",
"nodes",
"-",
"ensure",
"that",
"we",
"store",
"data",
"so",
"that",
"in",
"the",
"future",
"the",
"nodes",
"can",
"be",
"restarted",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L850-L882 | train | 205,313 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster.setup | def setup(self, extra_args=tuple()):
"""
Configure the cluster nodes.
Actual action is delegated to the
:py:class:`elasticluster.providers.AbstractSetupProvider` that
was provided at construction time.
:param list extra_args:
List of additional command-line arguments
that are appended to each invocation of the setup program.
:return: bool - True on success, False otherwise
"""
try:
# setup the cluster using the setup provider
ret = self._setup_provider.setup_cluster(self, extra_args)
except Exception as err:
log.error(
"The cluster hosts are up and running,"
" but %s failed to set the cluster up: %s",
self._setup_provider.HUMAN_READABLE_NAME, err)
ret = False
if not ret:
log.warning(
"Cluster `%s` not yet configured. Please, re-run "
"`elasticluster setup %s` and/or check your configuration",
self.name, self.name)
return ret | python | def setup(self, extra_args=tuple()):
"""
Configure the cluster nodes.
Actual action is delegated to the
:py:class:`elasticluster.providers.AbstractSetupProvider` that
was provided at construction time.
:param list extra_args:
List of additional command-line arguments
that are appended to each invocation of the setup program.
:return: bool - True on success, False otherwise
"""
try:
# setup the cluster using the setup provider
ret = self._setup_provider.setup_cluster(self, extra_args)
except Exception as err:
log.error(
"The cluster hosts are up and running,"
" but %s failed to set the cluster up: %s",
self._setup_provider.HUMAN_READABLE_NAME, err)
ret = False
if not ret:
log.warning(
"Cluster `%s` not yet configured. Please, re-run "
"`elasticluster setup %s` and/or check your configuration",
self.name, self.name)
return ret | [
"def",
"setup",
"(",
"self",
",",
"extra_args",
"=",
"tuple",
"(",
")",
")",
":",
"try",
":",
"# setup the cluster using the setup provider",
"ret",
"=",
"self",
".",
"_setup_provider",
".",
"setup_cluster",
"(",
"self",
",",
"extra_args",
")",
"except",
"Exce... | Configure the cluster nodes.
Actual action is delegated to the
:py:class:`elasticluster.providers.AbstractSetupProvider` that
was provided at construction time.
:param list extra_args:
List of additional command-line arguments
that are appended to each invocation of the setup program.
:return: bool - True on success, False otherwise | [
"Configure",
"the",
"cluster",
"nodes",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L984-L1014 | train | 205,314 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Cluster.update | def update(self):
"""
Update connection information of all nodes in this cluster.
It happens, for example, that public ip's are not available
immediately, therefore calling this method might help.
"""
for node in self.get_all_nodes():
try:
node.update_ips()
# If we previously did not have a preferred_ip or the
# preferred_ip is not in the current list, then try to connect
# to one of the node ips and update the preferred_ip.
if node.ips and \
not (node.preferred_ip and \
node.preferred_ip in node.ips):
node.connect()
except InstanceError as ex:
log.warning("Ignoring error updating information on node %s: %s",
node, ex)
self.repository.save_or_update(self) | python | def update(self):
"""
Update connection information of all nodes in this cluster.
It happens, for example, that public ip's are not available
immediately, therefore calling this method might help.
"""
for node in self.get_all_nodes():
try:
node.update_ips()
# If we previously did not have a preferred_ip or the
# preferred_ip is not in the current list, then try to connect
# to one of the node ips and update the preferred_ip.
if node.ips and \
not (node.preferred_ip and \
node.preferred_ip in node.ips):
node.connect()
except InstanceError as ex:
log.warning("Ignoring error updating information on node %s: %s",
node, ex)
self.repository.save_or_update(self) | [
"def",
"update",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"get_all_nodes",
"(",
")",
":",
"try",
":",
"node",
".",
"update_ips",
"(",
")",
"# If we previously did not have a preferred_ip or the",
"# preferred_ip is not in the current list, then try to co... | Update connection information of all nodes in this cluster.
It happens, for example, that public ip's are not available
immediately, therefore calling this method might help. | [
"Update",
"connection",
"information",
"of",
"all",
"nodes",
"in",
"this",
"cluster",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L1016-L1037 | train | 205,315 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Node.start | def start(self):
"""
Start the node on the cloud using the given instance properties.
This method is non-blocking: as soon as the node id is returned from
the cloud provider, it will return. The `is_alive`:meth: and
`update_ips`:meth: methods should be used to further gather details
about the state of the node.
"""
log.info("Starting node `%s` from image `%s` with flavor %s ...",
self.name, self.image_id, self.flavor)
self.instance_id = self._cloud_provider.start_instance(
self.user_key_name, self.user_key_public, self.user_key_private,
self.security_group,
self.flavor, self.image_id, self.image_userdata,
username=self.image_user,
node_name=("%s-%s" % (self.cluster_name, self.name)),
**self.extra)
log.debug("Node `%s` has instance ID `%s`", self.name, self.instance_id) | python | def start(self):
"""
Start the node on the cloud using the given instance properties.
This method is non-blocking: as soon as the node id is returned from
the cloud provider, it will return. The `is_alive`:meth: and
`update_ips`:meth: methods should be used to further gather details
about the state of the node.
"""
log.info("Starting node `%s` from image `%s` with flavor %s ...",
self.name, self.image_id, self.flavor)
self.instance_id = self._cloud_provider.start_instance(
self.user_key_name, self.user_key_public, self.user_key_private,
self.security_group,
self.flavor, self.image_id, self.image_userdata,
username=self.image_user,
node_name=("%s-%s" % (self.cluster_name, self.name)),
**self.extra)
log.debug("Node `%s` has instance ID `%s`", self.name, self.instance_id) | [
"def",
"start",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Starting node `%s` from image `%s` with flavor %s ...\"",
",",
"self",
".",
"name",
",",
"self",
".",
"image_id",
",",
"self",
".",
"flavor",
")",
"self",
".",
"instance_id",
"=",
"self",
"."... | Start the node on the cloud using the given instance properties.
This method is non-blocking: as soon as the node id is returned from
the cloud provider, it will return. The `is_alive`:meth: and
`update_ips`:meth: methods should be used to further gather details
about the state of the node. | [
"Start",
"the",
"node",
"on",
"the",
"cloud",
"using",
"the",
"given",
"instance",
"properties",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L1301-L1319 | train | 205,316 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Node.stop | def stop(self, wait=False):
"""
Terminate the VM instance launched on the cloud for this specific node.
"""
if self.instance_id is not None:
log.info("Shutting down node `%s` (VM instance `%s`) ...",
self.name, self.instance_id)
self._cloud_provider.stop_instance(self.instance_id)
if wait:
while self.is_alive():
time.sleep(1)
# When an instance is terminated, the EC2 cloud provider will
# basically return it as "running" state. Setting the
# `instance_id` attribute to None will force `is_alive()`
# method not to check with the cloud provider, and forever
# forgetting about the instance id.
self.instance_id = None | python | def stop(self, wait=False):
"""
Terminate the VM instance launched on the cloud for this specific node.
"""
if self.instance_id is not None:
log.info("Shutting down node `%s` (VM instance `%s`) ...",
self.name, self.instance_id)
self._cloud_provider.stop_instance(self.instance_id)
if wait:
while self.is_alive():
time.sleep(1)
# When an instance is terminated, the EC2 cloud provider will
# basically return it as "running" state. Setting the
# `instance_id` attribute to None will force `is_alive()`
# method not to check with the cloud provider, and forever
# forgetting about the instance id.
self.instance_id = None | [
"def",
"stop",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"if",
"self",
".",
"instance_id",
"is",
"not",
"None",
":",
"log",
".",
"info",
"(",
"\"Shutting down node `%s` (VM instance `%s`) ...\"",
",",
"self",
".",
"name",
",",
"self",
".",
"instanc... | Terminate the VM instance launched on the cloud for this specific node. | [
"Terminate",
"the",
"VM",
"instance",
"launched",
"on",
"the",
"cloud",
"for",
"this",
"specific",
"node",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L1321-L1338 | train | 205,317 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Node.pause | def pause(self):
"""
Pause the VM instance and return the info needed to restart it.
"""
if self.instance_id is None:
raise ValueError("Trying to stop unstarted node.")
resp = self._cloud_provider.pause_instance(self.instance_id)
self.preferred_ip = None
return resp | python | def pause(self):
"""
Pause the VM instance and return the info needed to restart it.
"""
if self.instance_id is None:
raise ValueError("Trying to stop unstarted node.")
resp = self._cloud_provider.pause_instance(self.instance_id)
self.preferred_ip = None
return resp | [
"def",
"pause",
"(",
"self",
")",
":",
"if",
"self",
".",
"instance_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Trying to stop unstarted node.\"",
")",
"resp",
"=",
"self",
".",
"_cloud_provider",
".",
"pause_instance",
"(",
"self",
".",
"instance_i... | Pause the VM instance and return the info needed to restart it. | [
"Pause",
"the",
"VM",
"instance",
"and",
"return",
"the",
"info",
"needed",
"to",
"restart",
"it",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L1340-L1348 | train | 205,318 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | Node.connect | def connect(self, keyfile=None, timeout=5):
"""
Connect to the node via SSH.
:param keyfile: Path to the SSH host key.
:param timeout: Maximum time to wait (in seconds) for the TCP
connection to be established.
:return: :py:class:`paramiko.SSHClient` - ssh connection or None on
failure
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if keyfile and os.path.exists(keyfile):
ssh.load_host_keys(keyfile)
# Try connecting using the `preferred_ip`, if
# present. Otherwise, try all of them and set `preferred_ip`
# using the first that is working.
ips = self.ips[:]
# This is done in order to "sort" the IPs and put the preferred_ip first.
if self.preferred_ip:
if self.preferred_ip in ips:
ips.remove(self.preferred_ip)
else:
# Preferred is changed?
log.debug(
"IP address %s does not seem to belong to %s anymore."
" Ignoring it.", self.preferred_ip, self.name)
self.preferred_ip = ips[0]
for ip in itertools.chain([self.preferred_ip], ips):
if not ip:
continue
log.debug(
"Trying to connect to host %s using IP address %s ...",
self.name, ip)
try:
addr, port = parse_ip_address_and_port(ip, SSH_PORT)
extra = {
'allow_agent': True,
'key_filename': self.user_key_private,
'look_for_keys': False,
'timeout': timeout,
'username': self.image_user,
}
if self.ssh_proxy_command:
proxy_command = expand_ssh_proxy_command(
self.ssh_proxy_command,
self.image_user, addr, port)
from paramiko.proxy import ProxyCommand
extra['sock'] = ProxyCommand(proxy_command)
log.debug("Using proxy command `%s`.", proxy_command)
ssh.connect(str(addr), port=port, **extra)
log.debug(
"Connection to %s succeeded on port %d,"
" will use this IP address for future connections.",
ip, port)
if ip != self.preferred_ip:
self.preferred_ip = ip
# Connection successful.
return ssh
except socket.error as ex:
log.debug(
"Host %s (%s) not reachable within %d seconds: %s -- %r",
self.name, ip, timeout, ex, type(ex))
except paramiko.BadHostKeyException as ex:
log.error(
"Invalid SSH host key for %s (%s): %s.",
self.name, ip, ex)
except paramiko.SSHException as ex:
log.debug(
"Ignoring error connecting to %s: %s -- %r",
self.name, ex, type(ex))
return None | python | def connect(self, keyfile=None, timeout=5):
"""
Connect to the node via SSH.
:param keyfile: Path to the SSH host key.
:param timeout: Maximum time to wait (in seconds) for the TCP
connection to be established.
:return: :py:class:`paramiko.SSHClient` - ssh connection or None on
failure
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if keyfile and os.path.exists(keyfile):
ssh.load_host_keys(keyfile)
# Try connecting using the `preferred_ip`, if
# present. Otherwise, try all of them and set `preferred_ip`
# using the first that is working.
ips = self.ips[:]
# This is done in order to "sort" the IPs and put the preferred_ip first.
if self.preferred_ip:
if self.preferred_ip in ips:
ips.remove(self.preferred_ip)
else:
# Preferred is changed?
log.debug(
"IP address %s does not seem to belong to %s anymore."
" Ignoring it.", self.preferred_ip, self.name)
self.preferred_ip = ips[0]
for ip in itertools.chain([self.preferred_ip], ips):
if not ip:
continue
log.debug(
"Trying to connect to host %s using IP address %s ...",
self.name, ip)
try:
addr, port = parse_ip_address_and_port(ip, SSH_PORT)
extra = {
'allow_agent': True,
'key_filename': self.user_key_private,
'look_for_keys': False,
'timeout': timeout,
'username': self.image_user,
}
if self.ssh_proxy_command:
proxy_command = expand_ssh_proxy_command(
self.ssh_proxy_command,
self.image_user, addr, port)
from paramiko.proxy import ProxyCommand
extra['sock'] = ProxyCommand(proxy_command)
log.debug("Using proxy command `%s`.", proxy_command)
ssh.connect(str(addr), port=port, **extra)
log.debug(
"Connection to %s succeeded on port %d,"
" will use this IP address for future connections.",
ip, port)
if ip != self.preferred_ip:
self.preferred_ip = ip
# Connection successful.
return ssh
except socket.error as ex:
log.debug(
"Host %s (%s) not reachable within %d seconds: %s -- %r",
self.name, ip, timeout, ex, type(ex))
except paramiko.BadHostKeyException as ex:
log.error(
"Invalid SSH host key for %s (%s): %s.",
self.name, ip, ex)
except paramiko.SSHException as ex:
log.debug(
"Ignoring error connecting to %s: %s -- %r",
self.name, ex, type(ex))
return None | [
"def",
"connect",
"(",
"self",
",",
"keyfile",
"=",
"None",
",",
"timeout",
"=",
"5",
")",
":",
"ssh",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"ssh",
".",
"set_missing_host_key_policy",
"(",
"paramiko",
".",
"AutoAddPolicy",
"(",
")",
")",
"if",
"... | Connect to the node via SSH.
:param keyfile: Path to the SSH host key.
:param timeout: Maximum time to wait (in seconds) for the TCP
connection to be established.
:return: :py:class:`paramiko.SSHClient` - ssh connection or None on
failure | [
"Connect",
"to",
"the",
"node",
"via",
"SSH",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L1384-L1459 | train | 205,319 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | BotoCloudProvider._connect | def _connect(self):
"""
Connect to the EC2 cloud provider.
:return: :py:class:`boto.ec2.connection.EC2Connection`
:raises: Generic exception on error
"""
# check for existing connection
if self._ec2_connection:
return self._ec2_connection
try:
log.debug("Connecting to EC2 endpoint %s", self._ec2host)
# connect to webservice
ec2_connection = boto.ec2.connect_to_region(
self._region_name,
aws_access_key_id=self._access_key,
aws_secret_access_key=self._secret_key,
is_secure=self._secure,
host=self._ec2host,
port=self._ec2port,
path=self._ec2path,
)
# With the loose setting `BOTO_USE_ENDPOINT_HEURISTICS`
# which is necessary to work around issue #592, Boto will
# now accept *any* string as an AWS region name;
# furthermore, it *always* returns a connection object --
# so the only way to check that we are not going to run
# into trouble is to check that there *is* a valid host
# name on the other end of the connection.
if ec2_connection.host:
log.debug("EC2 connection has been successful.")
else:
raise CloudProviderError(
"Cannot establish connection to EC2 region {0}"
.format(self._region_name))
if not self._vpc:
vpc_connection = None
self._vpc_id = None
else:
vpc_connection, self._vpc_id = self._find_vpc_by_name(self._vpc)
except Exception as err:
log.error("Error connecting to EC2: %s", err)
raise
self._ec2_connection, self._vpc_connection = (
ec2_connection, vpc_connection)
return self._ec2_connection | python | def _connect(self):
"""
Connect to the EC2 cloud provider.
:return: :py:class:`boto.ec2.connection.EC2Connection`
:raises: Generic exception on error
"""
# check for existing connection
if self._ec2_connection:
return self._ec2_connection
try:
log.debug("Connecting to EC2 endpoint %s", self._ec2host)
# connect to webservice
ec2_connection = boto.ec2.connect_to_region(
self._region_name,
aws_access_key_id=self._access_key,
aws_secret_access_key=self._secret_key,
is_secure=self._secure,
host=self._ec2host,
port=self._ec2port,
path=self._ec2path,
)
# With the loose setting `BOTO_USE_ENDPOINT_HEURISTICS`
# which is necessary to work around issue #592, Boto will
# now accept *any* string as an AWS region name;
# furthermore, it *always* returns a connection object --
# so the only way to check that we are not going to run
# into trouble is to check that there *is* a valid host
# name on the other end of the connection.
if ec2_connection.host:
log.debug("EC2 connection has been successful.")
else:
raise CloudProviderError(
"Cannot establish connection to EC2 region {0}"
.format(self._region_name))
if not self._vpc:
vpc_connection = None
self._vpc_id = None
else:
vpc_connection, self._vpc_id = self._find_vpc_by_name(self._vpc)
except Exception as err:
log.error("Error connecting to EC2: %s", err)
raise
self._ec2_connection, self._vpc_connection = (
ec2_connection, vpc_connection)
return self._ec2_connection | [
"def",
"_connect",
"(",
"self",
")",
":",
"# check for existing connection",
"if",
"self",
".",
"_ec2_connection",
":",
"return",
"self",
".",
"_ec2_connection",
"try",
":",
"log",
".",
"debug",
"(",
"\"Connecting to EC2 endpoint %s\"",
",",
"self",
".",
"_ec2host... | Connect to the EC2 cloud provider.
:return: :py:class:`boto.ec2.connection.EC2Connection`
:raises: Generic exception on error | [
"Connect",
"to",
"the",
"EC2",
"cloud",
"provider",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L156-L206 | train | 205,320 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | BotoCloudProvider.get_ips | def get_ips(self, instance_id):
"""Retrieves the private and public ip addresses for a given instance.
:return: list (ips)
"""
self._load_instance(instance_id)
instance = self._load_instance(instance_id)
IPs = [ip for ip in (instance.private_ip_address, instance.ip_address) if ip]
# We also need to check if there is any floating IP associated
if self.request_floating_ip and not self._vpc:
# We need to list the floating IPs for this instance
floating_ips = [ip for ip in self._ec2_connection.get_all_addresses() if ip.instance_id == instance.id]
if not floating_ips:
log.debug("Public ip address has to be assigned through "
"elasticluster.")
ip = self._allocate_address(instance)
# This is probably the preferred IP we want to use
IPs.insert(0, ip)
else:
IPs = [ip.public_ip for ip in floating_ips] + IPs
return list(set(IPs)) | python | def get_ips(self, instance_id):
"""Retrieves the private and public ip addresses for a given instance.
:return: list (ips)
"""
self._load_instance(instance_id)
instance = self._load_instance(instance_id)
IPs = [ip for ip in (instance.private_ip_address, instance.ip_address) if ip]
# We also need to check if there is any floating IP associated
if self.request_floating_ip and not self._vpc:
# We need to list the floating IPs for this instance
floating_ips = [ip for ip in self._ec2_connection.get_all_addresses() if ip.instance_id == instance.id]
if not floating_ips:
log.debug("Public ip address has to be assigned through "
"elasticluster.")
ip = self._allocate_address(instance)
# This is probably the preferred IP we want to use
IPs.insert(0, ip)
else:
IPs = [ip.public_ip for ip in floating_ips] + IPs
return list(set(IPs)) | [
"def",
"get_ips",
"(",
"self",
",",
"instance_id",
")",
":",
"self",
".",
"_load_instance",
"(",
"instance_id",
")",
"instance",
"=",
"self",
".",
"_load_instance",
"(",
"instance_id",
")",
"IPs",
"=",
"[",
"ip",
"for",
"ip",
"in",
"(",
"instance",
".",
... | Retrieves the private and public ip addresses for a given instance.
:return: list (ips) | [
"Retrieves",
"the",
"private",
"and",
"public",
"ip",
"addresses",
"for",
"a",
"given",
"instance",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L391-L413 | train | 205,321 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | BotoCloudProvider._allocate_address | def _allocate_address(self, instance):
"""Allocates a free public ip address to the given instance
:param instance: instance to assign address to
:type instance: py:class:`boto.ec2.instance.Reservation`
:return: public ip address
"""
connection = self._connect()
free_addresses = [ ip for ip in connection.get_all_addresses() if not ip.instance_id]
if not free_addresses:
try:
address = connection.allocate_address()
except Exception as ex:
log.error("Unable to allocate a public IP address to instance `%s`",
instance.id)
return None
try:
address = free_addresses.pop()
instance.use_ip(address)
return address.public_ip
except Exception as ex:
log.error("Unable to associate IP address %s to instance `%s`",
address, instance.id)
return None | python | def _allocate_address(self, instance):
"""Allocates a free public ip address to the given instance
:param instance: instance to assign address to
:type instance: py:class:`boto.ec2.instance.Reservation`
:return: public ip address
"""
connection = self._connect()
free_addresses = [ ip for ip in connection.get_all_addresses() if not ip.instance_id]
if not free_addresses:
try:
address = connection.allocate_address()
except Exception as ex:
log.error("Unable to allocate a public IP address to instance `%s`",
instance.id)
return None
try:
address = free_addresses.pop()
instance.use_ip(address)
return address.public_ip
except Exception as ex:
log.error("Unable to associate IP address %s to instance `%s`",
address, instance.id)
return None | [
"def",
"_allocate_address",
"(",
"self",
",",
"instance",
")",
":",
"connection",
"=",
"self",
".",
"_connect",
"(",
")",
"free_addresses",
"=",
"[",
"ip",
"for",
"ip",
"in",
"connection",
".",
"get_all_addresses",
"(",
")",
"if",
"not",
"ip",
".",
"inst... | Allocates a free public ip address to the given instance
:param instance: instance to assign address to
:type instance: py:class:`boto.ec2.instance.Reservation`
:return: public ip address | [
"Allocates",
"a",
"free",
"public",
"ip",
"address",
"to",
"the",
"given",
"instance"
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L436-L461 | train | 205,322 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | BotoCloudProvider._build_cached_instances | def _build_cached_instances(self):
"""
Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object.
"""
connection = self._connect()
reservations = connection.get_all_reservations()
cached_instances = {}
for rs in reservations:
for vm in rs.instances:
cached_instances[vm.id] = vm
return cached_instances | python | def _build_cached_instances(self):
"""
Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object.
"""
connection = self._connect()
reservations = connection.get_all_reservations()
cached_instances = {}
for rs in reservations:
for vm in rs.instances:
cached_instances[vm.id] = vm
return cached_instances | [
"def",
"_build_cached_instances",
"(",
"self",
")",
":",
"connection",
"=",
"self",
".",
"_connect",
"(",
")",
"reservations",
"=",
"connection",
".",
"get_all_reservations",
"(",
")",
"cached_instances",
"=",
"{",
"}",
"for",
"rs",
"in",
"reservations",
":",
... | Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object. | [
"Build",
"lookup",
"table",
"of",
"VM",
"instances",
"known",
"to",
"the",
"cloud",
"provider",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L498-L510 | train | 205,323 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | BotoCloudProvider._check_security_group | def _check_security_group(self, name):
"""Checks if the security group exists.
:param str name: name of the security group
:return: str - security group id of the security group
:raises: `SecurityGroupError` if group does not exist
"""
connection = self._connect()
filters = {}
if self._vpc:
filters = {'vpc-id': self._vpc_id}
security_groups = connection.get_all_security_groups(filters=filters)
matching_groups = [
group
for group
in security_groups
if name in [group.name, group.id]
]
if len(matching_groups) == 0:
raise SecurityGroupError(
"the specified security group %s does not exist" % name)
elif len(matching_groups) == 1:
return matching_groups[0].id
elif self._vpc and len(matching_groups) > 1:
raise SecurityGroupError(
"the specified security group name %s matches "
"more than one security group" % name) | python | def _check_security_group(self, name):
"""Checks if the security group exists.
:param str name: name of the security group
:return: str - security group id of the security group
:raises: `SecurityGroupError` if group does not exist
"""
connection = self._connect()
filters = {}
if self._vpc:
filters = {'vpc-id': self._vpc_id}
security_groups = connection.get_all_security_groups(filters=filters)
matching_groups = [
group
for group
in security_groups
if name in [group.name, group.id]
]
if len(matching_groups) == 0:
raise SecurityGroupError(
"the specified security group %s does not exist" % name)
elif len(matching_groups) == 1:
return matching_groups[0].id
elif self._vpc and len(matching_groups) > 1:
raise SecurityGroupError(
"the specified security group name %s matches "
"more than one security group" % name) | [
"def",
"_check_security_group",
"(",
"self",
",",
"name",
")",
":",
"connection",
"=",
"self",
".",
"_connect",
"(",
")",
"filters",
"=",
"{",
"}",
"if",
"self",
".",
"_vpc",
":",
"filters",
"=",
"{",
"'vpc-id'",
":",
"self",
".",
"_vpc_id",
"}",
"se... | Checks if the security group exists.
:param str name: name of the security group
:return: str - security group id of the security group
:raises: `SecurityGroupError` if group does not exist | [
"Checks",
"if",
"the",
"security",
"group",
"exists",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L609-L638 | train | 205,324 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | BotoCloudProvider._check_subnet | def _check_subnet(self, name):
"""Checks if the subnet exists.
:param str name: name of the subnet
:return: str - subnet id of the subnet
:raises: `SubnetError` if group does not exist
"""
# Subnets only exist in VPCs, so we don't need to worry about
# the EC2 Classic case here.
subnets = self._vpc_connection.get_all_subnets(
filters={'vpcId': self._vpc_id})
matching_subnets = [
subnet
for subnet
in subnets
if name in [subnet.tags.get('Name'), subnet.id]
]
if len(matching_subnets) == 0:
raise SubnetError(
"the specified subnet %s does not exist" % name)
elif len(matching_subnets) == 1:
return matching_subnets[0].id
else:
raise SubnetError(
"the specified subnet name %s matches more than "
"one subnet" % name) | python | def _check_subnet(self, name):
"""Checks if the subnet exists.
:param str name: name of the subnet
:return: str - subnet id of the subnet
:raises: `SubnetError` if group does not exist
"""
# Subnets only exist in VPCs, so we don't need to worry about
# the EC2 Classic case here.
subnets = self._vpc_connection.get_all_subnets(
filters={'vpcId': self._vpc_id})
matching_subnets = [
subnet
for subnet
in subnets
if name in [subnet.tags.get('Name'), subnet.id]
]
if len(matching_subnets) == 0:
raise SubnetError(
"the specified subnet %s does not exist" % name)
elif len(matching_subnets) == 1:
return matching_subnets[0].id
else:
raise SubnetError(
"the specified subnet name %s matches more than "
"one subnet" % name) | [
"def",
"_check_subnet",
"(",
"self",
",",
"name",
")",
":",
"# Subnets only exist in VPCs, so we don't need to worry about",
"# the EC2 Classic case here.",
"subnets",
"=",
"self",
".",
"_vpc_connection",
".",
"get_all_subnets",
"(",
"filters",
"=",
"{",
"'vpcId'",
":",
... | Checks if the subnet exists.
:param str name: name of the subnet
:return: str - subnet id of the subnet
:raises: `SubnetError` if group does not exist | [
"Checks",
"if",
"the",
"subnet",
"exists",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L640-L666 | train | 205,325 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | BotoCloudProvider._find_image_id | def _find_image_id(self, image_id):
"""Finds an image id to a given id or name.
:param str image_id: name or id of image
:return: str - identifier of image
"""
if not self._images:
connection = self._connect()
self._images = connection.get_all_images()
image_id_cloud = None
for i in self._images:
if i.id == image_id or i.name == image_id:
image_id_cloud = i.id
break
if image_id_cloud:
return image_id_cloud
else:
raise ImageError(
"Could not find given image id `%s`" % image_id) | python | def _find_image_id(self, image_id):
"""Finds an image id to a given id or name.
:param str image_id: name or id of image
:return: str - identifier of image
"""
if not self._images:
connection = self._connect()
self._images = connection.get_all_images()
image_id_cloud = None
for i in self._images:
if i.id == image_id or i.name == image_id:
image_id_cloud = i.id
break
if image_id_cloud:
return image_id_cloud
else:
raise ImageError(
"Could not find given image id `%s`" % image_id) | [
"def",
"_find_image_id",
"(",
"self",
",",
"image_id",
")",
":",
"if",
"not",
"self",
".",
"_images",
":",
"connection",
"=",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"_images",
"=",
"connection",
".",
"get_all_images",
"(",
")",
"image_id_cloud",
... | Finds an image id to a given id or name.
:param str image_id: name or id of image
:return: str - identifier of image | [
"Finds",
"an",
"image",
"id",
"to",
"a",
"given",
"id",
"or",
"name",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L668-L688 | train | 205,326 |
gc3-uzh-ch/elasticluster | elasticluster/repository.py | migrate_cluster | def migrate_cluster(cluster):
"""Called when loading a cluster when it comes from an older version
of elasticluster"""
for old, new in [('_user_key_public', 'user_key_public'),
('_user_key_private', 'user_key_private'),
('_user_key_name', 'user_key_name'),]:
if hasattr(cluster, old):
setattr(cluster, new, getattr(cluster, old))
delattr(cluster, old)
for kind, nodes in cluster.nodes.items():
for node in nodes:
if hasattr(node, 'image'):
image_id = getattr(node, 'image_id', None) or node.image
setattr(node, 'image_id', image_id)
delattr(node, 'image')
# Possibly related to issue #129
if not hasattr(cluster, 'thread_pool_max_size'):
cluster.thread_pool_max_size = 10
return cluster | python | def migrate_cluster(cluster):
"""Called when loading a cluster when it comes from an older version
of elasticluster"""
for old, new in [('_user_key_public', 'user_key_public'),
('_user_key_private', 'user_key_private'),
('_user_key_name', 'user_key_name'),]:
if hasattr(cluster, old):
setattr(cluster, new, getattr(cluster, old))
delattr(cluster, old)
for kind, nodes in cluster.nodes.items():
for node in nodes:
if hasattr(node, 'image'):
image_id = getattr(node, 'image_id', None) or node.image
setattr(node, 'image_id', image_id)
delattr(node, 'image')
# Possibly related to issue #129
if not hasattr(cluster, 'thread_pool_max_size'):
cluster.thread_pool_max_size = 10
return cluster | [
"def",
"migrate_cluster",
"(",
"cluster",
")",
":",
"for",
"old",
",",
"new",
"in",
"[",
"(",
"'_user_key_public'",
",",
"'user_key_public'",
")",
",",
"(",
"'_user_key_private'",
",",
"'user_key_private'",
")",
",",
"(",
"'_user_key_name'",
",",
"'user_key_name... | Called when loading a cluster when it comes from an older version
of elasticluster | [
"Called",
"when",
"loading",
"a",
"cluster",
"when",
"it",
"comes",
"from",
"an",
"older",
"version",
"of",
"elasticluster"
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/repository.py#L37-L57 | train | 205,327 |
gc3-uzh-ch/elasticluster | elasticluster/repository.py | MemRepository.get | def get(self, name):
"""Retrieves the cluster by the given name.
:param str name: name of the cluster (identifier)
:return: instance of :py:class:`elasticluster.cluster.Cluster` that
matches the given name
"""
if name not in self.clusters:
raise ClusterNotFound("Cluster %s not found." % name)
return self.clusters.get(name) | python | def get(self, name):
"""Retrieves the cluster by the given name.
:param str name: name of the cluster (identifier)
:return: instance of :py:class:`elasticluster.cluster.Cluster` that
matches the given name
"""
if name not in self.clusters:
raise ClusterNotFound("Cluster %s not found." % name)
return self.clusters.get(name) | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"clusters",
":",
"raise",
"ClusterNotFound",
"(",
"\"Cluster %s not found.\"",
"%",
"name",
")",
"return",
"self",
".",
"clusters",
".",
"get",
"(",
"name",
")"
] | Retrieves the cluster by the given name.
:param str name: name of the cluster (identifier)
:return: instance of :py:class:`elasticluster.cluster.Cluster` that
matches the given name | [
"Retrieves",
"the",
"cluster",
"by",
"the",
"given",
"name",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/repository.py#L121-L130 | train | 205,328 |
gc3-uzh-ch/elasticluster | elasticluster/repository.py | MemRepository.delete | def delete(self, cluster):
"""Deletes the cluster from memory.
:param cluster: cluster to delete
:type cluster: :py:class:`elasticluster.cluster.Cluster`
"""
if cluster.name not in self.clusters:
raise ClusterNotFound(
"Unable to delete non-existent cluster %s" % cluster.name)
del self.clusters[cluster.name] | python | def delete(self, cluster):
"""Deletes the cluster from memory.
:param cluster: cluster to delete
:type cluster: :py:class:`elasticluster.cluster.Cluster`
"""
if cluster.name not in self.clusters:
raise ClusterNotFound(
"Unable to delete non-existent cluster %s" % cluster.name)
del self.clusters[cluster.name] | [
"def",
"delete",
"(",
"self",
",",
"cluster",
")",
":",
"if",
"cluster",
".",
"name",
"not",
"in",
"self",
".",
"clusters",
":",
"raise",
"ClusterNotFound",
"(",
"\"Unable to delete non-existent cluster %s\"",
"%",
"cluster",
".",
"name",
")",
"del",
"self",
... | Deletes the cluster from memory.
:param cluster: cluster to delete
:type cluster: :py:class:`elasticluster.cluster.Cluster` | [
"Deletes",
"the",
"cluster",
"from",
"memory",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/repository.py#L139-L148 | train | 205,329 |
gc3-uzh-ch/elasticluster | elasticluster/repository.py | DiskRepository.get_all | def get_all(self):
"""Retrieves all clusters from the persistent state.
:return: list of :py:class:`elasticluster.cluster.Cluster`
"""
clusters = []
cluster_files = glob.glob("%s/*.%s" % (self.storage_path, self.file_ending))
for fname in cluster_files:
try:
name = fname[:-len(self.file_ending)-1]
clusters.append(self.get(name))
except (ImportError, AttributeError) as ex:
log.error("Unable to load cluster %s: `%s`", fname, ex)
log.error("If cluster %s was created with a previous version of elasticluster, you may need to run `elasticluster migrate %s %s` to update it.", cluster_file, self.storage_path, fname)
return clusters | python | def get_all(self):
"""Retrieves all clusters from the persistent state.
:return: list of :py:class:`elasticluster.cluster.Cluster`
"""
clusters = []
cluster_files = glob.glob("%s/*.%s" % (self.storage_path, self.file_ending))
for fname in cluster_files:
try:
name = fname[:-len(self.file_ending)-1]
clusters.append(self.get(name))
except (ImportError, AttributeError) as ex:
log.error("Unable to load cluster %s: `%s`", fname, ex)
log.error("If cluster %s was created with a previous version of elasticluster, you may need to run `elasticluster migrate %s %s` to update it.", cluster_file, self.storage_path, fname)
return clusters | [
"def",
"get_all",
"(",
"self",
")",
":",
"clusters",
"=",
"[",
"]",
"cluster_files",
"=",
"glob",
".",
"glob",
"(",
"\"%s/*.%s\"",
"%",
"(",
"self",
".",
"storage_path",
",",
"self",
".",
"file_ending",
")",
")",
"for",
"fname",
"in",
"cluster_files",
... | Retrieves all clusters from the persistent state.
:return: list of :py:class:`elasticluster.cluster.Cluster` | [
"Retrieves",
"all",
"clusters",
"from",
"the",
"persistent",
"state",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/repository.py#L162-L177 | train | 205,330 |
gc3-uzh-ch/elasticluster | elasticluster/repository.py | DiskRepository.delete | def delete(self, cluster):
"""Deletes the cluster from persistent state.
:param cluster: cluster to delete from persistent state
:type cluster: :py:class:`elasticluster.cluster.Cluster`
"""
path = self._get_cluster_storage_path(cluster.name)
if os.path.exists(path):
os.unlink(path) | python | def delete(self, cluster):
"""Deletes the cluster from persistent state.
:param cluster: cluster to delete from persistent state
:type cluster: :py:class:`elasticluster.cluster.Cluster`
"""
path = self._get_cluster_storage_path(cluster.name)
if os.path.exists(path):
os.unlink(path) | [
"def",
"delete",
"(",
"self",
",",
"cluster",
")",
":",
"path",
"=",
"self",
".",
"_get_cluster_storage_path",
"(",
"cluster",
".",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"unlink",
"(",
"path",
")"
] | Deletes the cluster from persistent state.
:param cluster: cluster to delete from persistent state
:type cluster: :py:class:`elasticluster.cluster.Cluster` | [
"Deletes",
"the",
"cluster",
"from",
"persistent",
"state",
"."
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/repository.py#L220-L228 | train | 205,331 |
gc3-uzh-ch/elasticluster | elasticluster/repository.py | PickleRepository.load | def load(self, fp):
"""Load cluster from file descriptor fp"""
cluster = pickle.load(fp)
cluster.repository = self
return cluster | python | def load(self, fp):
"""Load cluster from file descriptor fp"""
cluster = pickle.load(fp)
cluster.repository = self
return cluster | [
"def",
"load",
"(",
"self",
",",
"fp",
")",
":",
"cluster",
"=",
"pickle",
".",
"load",
"(",
"fp",
")",
"cluster",
".",
"repository",
"=",
"self",
"return",
"cluster"
] | Load cluster from file descriptor fp | [
"Load",
"cluster",
"from",
"file",
"descriptor",
"fp"
] | e6345633308c76de13b889417df572815aabe744 | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/repository.py#L248-L252 | train | 205,332 |
Pegase745/sqlalchemy-datatables | examples/flask_tut/flask_tut/__init__.py | initdb | def initdb():
"""Initialize the database."""
click.echo('Init the db...')
db.create_all()
for i in range(30):
click.echo("Creating user/address combo #{}...".format(i))
address = Address(description='Address#2' + str(i).rjust(2, "0"))
db.session.add(address)
user = User(name='User#1' + str(i).rjust(2, "0"))
user.address = address
db.session.add(user)
sleep(1)
db.session.commit() | python | def initdb():
"""Initialize the database."""
click.echo('Init the db...')
db.create_all()
for i in range(30):
click.echo("Creating user/address combo #{}...".format(i))
address = Address(description='Address#2' + str(i).rjust(2, "0"))
db.session.add(address)
user = User(name='User#1' + str(i).rjust(2, "0"))
user.address = address
db.session.add(user)
sleep(1)
db.session.commit() | [
"def",
"initdb",
"(",
")",
":",
"click",
".",
"echo",
"(",
"'Init the db...'",
")",
"db",
".",
"create_all",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"30",
")",
":",
"click",
".",
"echo",
"(",
"\"Creating user/address combo #{}...\"",
".",
"format",
"("... | Initialize the database. | [
"Initialize",
"the",
"database",
"."
] | 049ab5f98f20ad37926fe86d5528da0c91cd462d | https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/examples/flask_tut/flask_tut/__init__.py#L14-L27 | train | 205,333 |
Pegase745/sqlalchemy-datatables | datatables/clean_regex.py | clean_regex | def clean_regex(regex):
"""
Escape any regex special characters other than alternation.
:param regex: regex from datatables interface
:type regex: str
:rtype: str with regex to use with database
"""
# copy for return
ret_regex = regex
# these characters are escaped (all except alternation | and escape \)
# see http://www.regular-expressions.info/refquick.html
escape_chars = '[^$.?*+(){}'
# remove any escape chars
ret_regex = ret_regex.replace('\\', '')
# escape any characters which are used by regex
# could probably concoct something incomprehensible using re.sub() but
# prefer to write clear code with this loop
# note expectation that no characters have already been escaped
for c in escape_chars:
ret_regex = ret_regex.replace(c, '\\' + c)
# remove any double alternations until these don't exist any more
while True:
old_regex = ret_regex
ret_regex = ret_regex.replace('||', '|')
if old_regex == ret_regex:
break
# if last char is alternation | remove it because this
# will cause operational error
# this can happen as user is typing in global search box
while len(ret_regex) >= 1 and ret_regex[-1] == '|':
ret_regex = ret_regex[:-1]
# and back to the caller
return ret_regex | python | def clean_regex(regex):
"""
Escape any regex special characters other than alternation.
:param regex: regex from datatables interface
:type regex: str
:rtype: str with regex to use with database
"""
# copy for return
ret_regex = regex
# these characters are escaped (all except alternation | and escape \)
# see http://www.regular-expressions.info/refquick.html
escape_chars = '[^$.?*+(){}'
# remove any escape chars
ret_regex = ret_regex.replace('\\', '')
# escape any characters which are used by regex
# could probably concoct something incomprehensible using re.sub() but
# prefer to write clear code with this loop
# note expectation that no characters have already been escaped
for c in escape_chars:
ret_regex = ret_regex.replace(c, '\\' + c)
# remove any double alternations until these don't exist any more
while True:
old_regex = ret_regex
ret_regex = ret_regex.replace('||', '|')
if old_regex == ret_regex:
break
# if last char is alternation | remove it because this
# will cause operational error
# this can happen as user is typing in global search box
while len(ret_regex) >= 1 and ret_regex[-1] == '|':
ret_regex = ret_regex[:-1]
# and back to the caller
return ret_regex | [
"def",
"clean_regex",
"(",
"regex",
")",
":",
"# copy for return",
"ret_regex",
"=",
"regex",
"# these characters are escaped (all except alternation | and escape \\)",
"# see http://www.regular-expressions.info/refquick.html",
"escape_chars",
"=",
"'[^$.?*+(){}'",
"# remove any escape... | Escape any regex special characters other than alternation.
:param regex: regex from datatables interface
:type regex: str
:rtype: str with regex to use with database | [
"Escape",
"any",
"regex",
"special",
"characters",
"other",
"than",
"alternation",
"."
] | 049ab5f98f20ad37926fe86d5528da0c91cd462d | https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/datatables/clean_regex.py#L1-L40 | train | 205,334 |
Pegase745/sqlalchemy-datatables | datatables/datatables.py | DataTables.output_result | def output_result(self):
"""Output results in the format needed by DataTables."""
output = {}
output['draw'] = str(int(self.params.get('draw', 1)))
output['recordsTotal'] = str(self.cardinality)
output['recordsFiltered'] = str(self.cardinality_filtered)
if self.error:
output['error'] = self.error
return output
output['data'] = self.results
for k, v in self.yadcf_params:
output[k] = v
return output | python | def output_result(self):
"""Output results in the format needed by DataTables."""
output = {}
output['draw'] = str(int(self.params.get('draw', 1)))
output['recordsTotal'] = str(self.cardinality)
output['recordsFiltered'] = str(self.cardinality_filtered)
if self.error:
output['error'] = self.error
return output
output['data'] = self.results
for k, v in self.yadcf_params:
output[k] = v
return output | [
"def",
"output_result",
"(",
"self",
")",
":",
"output",
"=",
"{",
"}",
"output",
"[",
"'draw'",
"]",
"=",
"str",
"(",
"int",
"(",
"self",
".",
"params",
".",
"get",
"(",
"'draw'",
",",
"1",
")",
")",
")",
"output",
"[",
"'recordsTotal'",
"]",
"=... | Output results in the format needed by DataTables. | [
"Output",
"results",
"in",
"the",
"format",
"needed",
"by",
"DataTables",
"."
] | 049ab5f98f20ad37926fe86d5528da0c91cd462d | https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/datatables/datatables.py#L51-L64 | train | 205,335 |
Pegase745/sqlalchemy-datatables | datatables/datatables.py | DataTables.run | def run(self):
"""Launch filtering, sorting and paging to output results."""
query = self.query
# count before filtering
self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()
self._set_column_filter_expressions()
self._set_global_filter_expression()
self._set_sort_expressions()
self._set_yadcf_data(query)
# apply filters
query = query.filter(
*[e for e in self.filter_expressions if e is not None])
self.cardinality_filtered = query.add_columns(
self.columns[0].sqla_expr).count()
# apply sorts
query = query.order_by(
*[e for e in self.sort_expressions if e is not None])
# add paging options
length = int(self.params.get('length'))
if length >= 0:
query = query.limit(length)
elif length == -1:
pass
else:
raise (ValueError(
'Length should be a positive integer or -1 to disable'))
query = query.offset(int(self.params.get('start')))
# add columns to query
query = query.add_columns(*[c.sqla_expr for c in self.columns])
# fetch the result of the queries
column_names = [
col.mData if col.mData else str(i)
for i, col in enumerate(self.columns)
]
self.results = [{k: v
for k, v in zip(column_names, row)}
for row in query.all()] | python | def run(self):
"""Launch filtering, sorting and paging to output results."""
query = self.query
# count before filtering
self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()
self._set_column_filter_expressions()
self._set_global_filter_expression()
self._set_sort_expressions()
self._set_yadcf_data(query)
# apply filters
query = query.filter(
*[e for e in self.filter_expressions if e is not None])
self.cardinality_filtered = query.add_columns(
self.columns[0].sqla_expr).count()
# apply sorts
query = query.order_by(
*[e for e in self.sort_expressions if e is not None])
# add paging options
length = int(self.params.get('length'))
if length >= 0:
query = query.limit(length)
elif length == -1:
pass
else:
raise (ValueError(
'Length should be a positive integer or -1 to disable'))
query = query.offset(int(self.params.get('start')))
# add columns to query
query = query.add_columns(*[c.sqla_expr for c in self.columns])
# fetch the result of the queries
column_names = [
col.mData if col.mData else str(i)
for i, col in enumerate(self.columns)
]
self.results = [{k: v
for k, v in zip(column_names, row)}
for row in query.all()] | [
"def",
"run",
"(",
"self",
")",
":",
"query",
"=",
"self",
".",
"query",
"# count before filtering",
"self",
".",
"cardinality",
"=",
"query",
".",
"add_columns",
"(",
"self",
".",
"columns",
"[",
"0",
"]",
".",
"sqla_expr",
")",
".",
"count",
"(",
")"... | Launch filtering, sorting and paging to output results. | [
"Launch",
"filtering",
"sorting",
"and",
"paging",
"to",
"output",
"results",
"."
] | 049ab5f98f20ad37926fe86d5528da0c91cd462d | https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/datatables/datatables.py#L89-L133 | train | 205,336 |
Pegase745/sqlalchemy-datatables | datatables/search_methods.py | parse_query_value | def parse_query_value(combined_value):
"""Parse value in form of '>value' to a lambda and a value."""
split = len(combined_value) - len(combined_value.lstrip('<>='))
operator = combined_value[:split]
if operator == '':
operator = '='
try:
operator_func = search_operators[operator]
except KeyError:
raise ValueError(
'Numeric query should start with operator, choose from %s' %
', '.join(search_operators.keys()))
value = combined_value[split:].strip()
return operator_func, value | python | def parse_query_value(combined_value):
"""Parse value in form of '>value' to a lambda and a value."""
split = len(combined_value) - len(combined_value.lstrip('<>='))
operator = combined_value[:split]
if operator == '':
operator = '='
try:
operator_func = search_operators[operator]
except KeyError:
raise ValueError(
'Numeric query should start with operator, choose from %s' %
', '.join(search_operators.keys()))
value = combined_value[split:].strip()
return operator_func, value | [
"def",
"parse_query_value",
"(",
"combined_value",
")",
":",
"split",
"=",
"len",
"(",
"combined_value",
")",
"-",
"len",
"(",
"combined_value",
".",
"lstrip",
"(",
"'<>='",
")",
")",
"operator",
"=",
"combined_value",
"[",
":",
"split",
"]",
"if",
"operat... | Parse value in form of '>value' to a lambda and a value. | [
"Parse",
"value",
"in",
"form",
"of",
">",
"value",
"to",
"a",
"lambda",
"and",
"a",
"value",
"."
] | 049ab5f98f20ad37926fe86d5528da0c91cd462d | https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/datatables/search_methods.py#L18-L31 | train | 205,337 |
Pegase745/sqlalchemy-datatables | examples/pyramid_tut/pyramid_tut/views.py | home | def home(request):
"""Try to connect to database, and list available examples."""
try:
DBSession.query(User).first()
except DBAPIError:
return Response(
conn_err_msg,
content_type="text/plain",
status_int=500,
)
return {"project": "pyramid_tut"} | python | def home(request):
"""Try to connect to database, and list available examples."""
try:
DBSession.query(User).first()
except DBAPIError:
return Response(
conn_err_msg,
content_type="text/plain",
status_int=500,
)
return {"project": "pyramid_tut"} | [
"def",
"home",
"(",
"request",
")",
":",
"try",
":",
"DBSession",
".",
"query",
"(",
"User",
")",
".",
"first",
"(",
")",
"except",
"DBAPIError",
":",
"return",
"Response",
"(",
"conn_err_msg",
",",
"content_type",
"=",
"\"text/plain\"",
",",
"status_int",... | Try to connect to database, and list available examples. | [
"Try",
"to",
"connect",
"to",
"database",
"and",
"list",
"available",
"examples",
"."
] | 049ab5f98f20ad37926fe86d5528da0c91cd462d | https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/examples/pyramid_tut/pyramid_tut/views.py#L12-L23 | train | 205,338 |
Pegase745/sqlalchemy-datatables | examples/pyramid_tut/pyramid_tut/__init__.py | main | def main(global_config, **settings):
"""Return a Pyramid WSGI application."""
engine = engine_from_config(settings, "sqlalchemy.")
DBSession.configure(bind=engine)
Base.metadata.bind = engine
config = Configurator(settings=settings)
config.include("pyramid_jinja2")
config.include("pyramid_debugtoolbar")
config.add_route("home", "/")
config.add_route("data", "/data")
config.add_route("data_advanced", "/data_advanced")
config.add_route("data_yadcf", "/data_yadcf")
config.add_route("dt_110x", "/dt_110x")
config.add_route("dt_110x_custom_column", "/dt_110x_custom_column")
config.add_route("dt_110x_basic_column_search",
"/dt_110x_basic_column_search")
config.add_route("dt_110x_advanced_column_search",
"/dt_110x_advanced_column_search")
config.add_route("dt_110x_yadcf", "/dt_110x_yadcf")
config.scan()
json_renderer = JSON()
json_renderer.add_adapter(date, date_adapter)
config.add_renderer("json_with_dates", json_renderer)
config.add_jinja2_renderer('.html')
return config.make_wsgi_app() | python | def main(global_config, **settings):
"""Return a Pyramid WSGI application."""
engine = engine_from_config(settings, "sqlalchemy.")
DBSession.configure(bind=engine)
Base.metadata.bind = engine
config = Configurator(settings=settings)
config.include("pyramid_jinja2")
config.include("pyramid_debugtoolbar")
config.add_route("home", "/")
config.add_route("data", "/data")
config.add_route("data_advanced", "/data_advanced")
config.add_route("data_yadcf", "/data_yadcf")
config.add_route("dt_110x", "/dt_110x")
config.add_route("dt_110x_custom_column", "/dt_110x_custom_column")
config.add_route("dt_110x_basic_column_search",
"/dt_110x_basic_column_search")
config.add_route("dt_110x_advanced_column_search",
"/dt_110x_advanced_column_search")
config.add_route("dt_110x_yadcf", "/dt_110x_yadcf")
config.scan()
json_renderer = JSON()
json_renderer.add_adapter(date, date_adapter)
config.add_renderer("json_with_dates", json_renderer)
config.add_jinja2_renderer('.html')
return config.make_wsgi_app() | [
"def",
"main",
"(",
"global_config",
",",
"*",
"*",
"settings",
")",
":",
"engine",
"=",
"engine_from_config",
"(",
"settings",
",",
"\"sqlalchemy.\"",
")",
"DBSession",
".",
"configure",
"(",
"bind",
"=",
"engine",
")",
"Base",
".",
"metadata",
".",
"bind... | Return a Pyramid WSGI application. | [
"Return",
"a",
"Pyramid",
"WSGI",
"application",
"."
] | 049ab5f98f20ad37926fe86d5528da0c91cd462d | https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/examples/pyramid_tut/pyramid_tut/__init__.py#L14-L58 | train | 205,339 |
Pegase745/sqlalchemy-datatables | examples/pyramid_tut/pyramid_tut/scripts/initializedb.py | main | def main(argv=sys.argv):
"""Populate database with 30 users."""
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, "sqlalchemy.")
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
for i in range(30):
with transaction.manager:
address = Address(description="Address#2" + str(i).rjust(2, "0"))
DBSession.add(address)
user = User(
name="User#1" + str(i).rjust(2, "0"),
birthday=date(1980 + i % 8, i % 12 + 1, i % 10 + 1))
user.address = address
DBSession.add(user) | python | def main(argv=sys.argv):
"""Populate database with 30 users."""
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, "sqlalchemy.")
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
for i in range(30):
with transaction.manager:
address = Address(description="Address#2" + str(i).rjust(2, "0"))
DBSession.add(address)
user = User(
name="User#1" + str(i).rjust(2, "0"),
birthday=date(1980 + i % 8, i % 12 + 1, i % 10 + 1))
user.address = address
DBSession.add(user) | [
"def",
"main",
"(",
"argv",
"=",
"sys",
".",
"argv",
")",
":",
"if",
"len",
"(",
"argv",
")",
"<",
"2",
":",
"usage",
"(",
"argv",
")",
"config_uri",
"=",
"argv",
"[",
"1",
"]",
"setup_logging",
"(",
"config_uri",
")",
"settings",
"=",
"get_appsett... | Populate database with 30 users. | [
"Populate",
"database",
"with",
"30",
"users",
"."
] | 049ab5f98f20ad37926fe86d5528da0c91cd462d | https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/examples/pyramid_tut/pyramid_tut/scripts/initializedb.py#L21-L50 | train | 205,340 |
google/mobly | mobly/logger.py | _parse_logline_timestamp | def _parse_logline_timestamp(t):
"""Parses a logline timestamp into a tuple.
Args:
t: Timestamp in logline format.
Returns:
An iterable of date and time elements in the order of month, day, hour,
minute, second, microsecond.
"""
date, time = t.split(' ')
month, day = date.split('-')
h, m, s = time.split(':')
s, ms = s.split('.')
return (month, day, h, m, s, ms) | python | def _parse_logline_timestamp(t):
"""Parses a logline timestamp into a tuple.
Args:
t: Timestamp in logline format.
Returns:
An iterable of date and time elements in the order of month, day, hour,
minute, second, microsecond.
"""
date, time = t.split(' ')
month, day = date.split('-')
h, m, s = time.split(':')
s, ms = s.split('.')
return (month, day, h, m, s, ms) | [
"def",
"_parse_logline_timestamp",
"(",
"t",
")",
":",
"date",
",",
"time",
"=",
"t",
".",
"split",
"(",
"' '",
")",
"month",
",",
"day",
"=",
"date",
".",
"split",
"(",
"'-'",
")",
"h",
",",
"m",
",",
"s",
"=",
"time",
".",
"split",
"(",
"':'"... | Parses a logline timestamp into a tuple.
Args:
t: Timestamp in logline format.
Returns:
An iterable of date and time elements in the order of month, day, hour,
minute, second, microsecond. | [
"Parses",
"a",
"logline",
"timestamp",
"into",
"a",
"tuple",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/logger.py#L35-L49 | train | 205,341 |
google/mobly | mobly/logger.py | logline_timestamp_comparator | def logline_timestamp_comparator(t1, t2):
"""Comparator for timestamps in logline format.
Args:
t1: Timestamp in logline format.
t2: Timestamp in logline format.
Returns:
-1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2.
"""
dt1 = _parse_logline_timestamp(t1)
dt2 = _parse_logline_timestamp(t2)
for u1, u2 in zip(dt1, dt2):
if u1 < u2:
return -1
elif u1 > u2:
return 1
return 0 | python | def logline_timestamp_comparator(t1, t2):
"""Comparator for timestamps in logline format.
Args:
t1: Timestamp in logline format.
t2: Timestamp in logline format.
Returns:
-1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2.
"""
dt1 = _parse_logline_timestamp(t1)
dt2 = _parse_logline_timestamp(t2)
for u1, u2 in zip(dt1, dt2):
if u1 < u2:
return -1
elif u1 > u2:
return 1
return 0 | [
"def",
"logline_timestamp_comparator",
"(",
"t1",
",",
"t2",
")",
":",
"dt1",
"=",
"_parse_logline_timestamp",
"(",
"t1",
")",
"dt2",
"=",
"_parse_logline_timestamp",
"(",
"t2",
")",
"for",
"u1",
",",
"u2",
"in",
"zip",
"(",
"dt1",
",",
"dt2",
")",
":",
... | Comparator for timestamps in logline format.
Args:
t1: Timestamp in logline format.
t2: Timestamp in logline format.
Returns:
-1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2. | [
"Comparator",
"for",
"timestamps",
"in",
"logline",
"format",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/logger.py#L59-L76 | train | 205,342 |
google/mobly | mobly/logger.py | epoch_to_log_line_timestamp | def epoch_to_log_line_timestamp(epoch_time, time_zone=None):
"""Converts an epoch timestamp in ms to log line timestamp format, which
is readible for humans.
Args:
epoch_time: integer, an epoch timestamp in ms.
time_zone: instance of tzinfo, time zone information.
Using pytz rather than python 3.2 time_zone implementation for
python 2 compatibility reasons.
Returns:
A string that is the corresponding timestamp in log line timestamp
format.
"""
s, ms = divmod(epoch_time, 1000)
d = datetime.datetime.fromtimestamp(s, tz=time_zone)
return d.strftime('%m-%d %H:%M:%S.') + str(ms) | python | def epoch_to_log_line_timestamp(epoch_time, time_zone=None):
"""Converts an epoch timestamp in ms to log line timestamp format, which
is readible for humans.
Args:
epoch_time: integer, an epoch timestamp in ms.
time_zone: instance of tzinfo, time zone information.
Using pytz rather than python 3.2 time_zone implementation for
python 2 compatibility reasons.
Returns:
A string that is the corresponding timestamp in log line timestamp
format.
"""
s, ms = divmod(epoch_time, 1000)
d = datetime.datetime.fromtimestamp(s, tz=time_zone)
return d.strftime('%m-%d %H:%M:%S.') + str(ms) | [
"def",
"epoch_to_log_line_timestamp",
"(",
"epoch_time",
",",
"time_zone",
"=",
"None",
")",
":",
"s",
",",
"ms",
"=",
"divmod",
"(",
"epoch_time",
",",
"1000",
")",
"d",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"s",
",",
"tz",
"=",
... | Converts an epoch timestamp in ms to log line timestamp format, which
is readible for humans.
Args:
epoch_time: integer, an epoch timestamp in ms.
time_zone: instance of tzinfo, time zone information.
Using pytz rather than python 3.2 time_zone implementation for
python 2 compatibility reasons.
Returns:
A string that is the corresponding timestamp in log line timestamp
format. | [
"Converts",
"an",
"epoch",
"timestamp",
"in",
"ms",
"to",
"log",
"line",
"timestamp",
"format",
"which",
"is",
"readible",
"for",
"humans",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/logger.py#L86-L102 | train | 205,343 |
google/mobly | mobly/suite_runner.py | run_suite | def run_suite(test_classes, argv=None):
"""Executes multiple test classes as a suite.
This is the default entry point for running a test suite script file
directly.
Args:
test_classes: List of python classes containing Mobly tests.
argv: A list that is then parsed as cli args. If None, defaults to cli
input.
"""
# Parse cli args.
parser = argparse.ArgumentParser(description='Mobly Suite Executable.')
parser.add_argument(
'-c',
'--config',
nargs=1,
type=str,
required=True,
metavar='<PATH>',
help='Path to the test configuration file.')
parser.add_argument(
'--tests',
'--test_case',
nargs='+',
type=str,
metavar='[ClassA[.test_a] ClassB[.test_b] ...]',
help='A list of test classes and optional tests to execute.')
if not argv:
argv = sys.argv[1:]
args = parser.parse_args(argv)
# Load test config file.
test_configs = config_parser.load_test_config_file(args.config[0])
# Check the classes that were passed in
for test_class in test_classes:
if not issubclass(test_class, base_test.BaseTestClass):
logging.error('Test class %s does not extend '
'mobly.base_test.BaseTestClass', test_class)
sys.exit(1)
# Find the full list of tests to execute
selected_tests = compute_selected_tests(test_classes, args.tests)
# Execute the suite
ok = True
for config in test_configs:
runner = test_runner.TestRunner(config.log_path, config.test_bed_name)
for (test_class, tests) in selected_tests.items():
runner.add_test_class(config, test_class, tests)
try:
runner.run()
ok = runner.results.is_all_pass and ok
except signals.TestAbortAll:
pass
except:
logging.exception('Exception when executing %s.',
config.test_bed_name)
ok = False
if not ok:
sys.exit(1) | python | def run_suite(test_classes, argv=None):
"""Executes multiple test classes as a suite.
This is the default entry point for running a test suite script file
directly.
Args:
test_classes: List of python classes containing Mobly tests.
argv: A list that is then parsed as cli args. If None, defaults to cli
input.
"""
# Parse cli args.
parser = argparse.ArgumentParser(description='Mobly Suite Executable.')
parser.add_argument(
'-c',
'--config',
nargs=1,
type=str,
required=True,
metavar='<PATH>',
help='Path to the test configuration file.')
parser.add_argument(
'--tests',
'--test_case',
nargs='+',
type=str,
metavar='[ClassA[.test_a] ClassB[.test_b] ...]',
help='A list of test classes and optional tests to execute.')
if not argv:
argv = sys.argv[1:]
args = parser.parse_args(argv)
# Load test config file.
test_configs = config_parser.load_test_config_file(args.config[0])
# Check the classes that were passed in
for test_class in test_classes:
if not issubclass(test_class, base_test.BaseTestClass):
logging.error('Test class %s does not extend '
'mobly.base_test.BaseTestClass', test_class)
sys.exit(1)
# Find the full list of tests to execute
selected_tests = compute_selected_tests(test_classes, args.tests)
# Execute the suite
ok = True
for config in test_configs:
runner = test_runner.TestRunner(config.log_path, config.test_bed_name)
for (test_class, tests) in selected_tests.items():
runner.add_test_class(config, test_class, tests)
try:
runner.run()
ok = runner.results.is_all_pass and ok
except signals.TestAbortAll:
pass
except:
logging.exception('Exception when executing %s.',
config.test_bed_name)
ok = False
if not ok:
sys.exit(1) | [
"def",
"run_suite",
"(",
"test_classes",
",",
"argv",
"=",
"None",
")",
":",
"# Parse cli args.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Mobly Suite Executable.'",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--co... | Executes multiple test classes as a suite.
This is the default entry point for running a test suite script file
directly.
Args:
test_classes: List of python classes containing Mobly tests.
argv: A list that is then parsed as cli args. If None, defaults to cli
input. | [
"Executes",
"multiple",
"test",
"classes",
"as",
"a",
"suite",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/suite_runner.py#L45-L105 | train | 205,344 |
google/mobly | mobly/controllers/android_device_lib/jsonrpc_shell_base.py | JsonRpcShellBase.load_device | def load_device(self, serial=None):
"""Creates an AndroidDevice for the given serial number.
If no serial is given, it will read from the ANDROID_SERIAL
environmental variable. If the environmental variable is not set, then
it will read from 'adb devices' if there is only one.
"""
serials = android_device.list_adb_devices()
if not serials:
raise Error('No adb device found!')
# No serial provided, try to pick up the device automatically.
if not serial:
env_serial = os.environ.get('ANDROID_SERIAL', None)
if env_serial is not None:
serial = env_serial
elif len(serials) == 1:
serial = serials[0]
else:
raise Error(
'Expected one phone, but %d found. Use the -s flag or '
'specify ANDROID_SERIAL.' % len(serials))
if serial not in serials:
raise Error('Device "%s" is not found by adb.' % serial)
ads = android_device.get_instances([serial])
assert len(ads) == 1
self._ad = ads[0] | python | def load_device(self, serial=None):
"""Creates an AndroidDevice for the given serial number.
If no serial is given, it will read from the ANDROID_SERIAL
environmental variable. If the environmental variable is not set, then
it will read from 'adb devices' if there is only one.
"""
serials = android_device.list_adb_devices()
if not serials:
raise Error('No adb device found!')
# No serial provided, try to pick up the device automatically.
if not serial:
env_serial = os.environ.get('ANDROID_SERIAL', None)
if env_serial is not None:
serial = env_serial
elif len(serials) == 1:
serial = serials[0]
else:
raise Error(
'Expected one phone, but %d found. Use the -s flag or '
'specify ANDROID_SERIAL.' % len(serials))
if serial not in serials:
raise Error('Device "%s" is not found by adb.' % serial)
ads = android_device.get_instances([serial])
assert len(ads) == 1
self._ad = ads[0] | [
"def",
"load_device",
"(",
"self",
",",
"serial",
"=",
"None",
")",
":",
"serials",
"=",
"android_device",
".",
"list_adb_devices",
"(",
")",
"if",
"not",
"serials",
":",
"raise",
"Error",
"(",
"'No adb device found!'",
")",
"# No serial provided, try to pick up t... | Creates an AndroidDevice for the given serial number.
If no serial is given, it will read from the ANDROID_SERIAL
environmental variable. If the environmental variable is not set, then
it will read from 'adb devices' if there is only one. | [
"Creates",
"an",
"AndroidDevice",
"for",
"the",
"given",
"serial",
"number",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/jsonrpc_shell_base.py#L44-L69 | train | 205,345 |
google/mobly | mobly/controllers/attenuator_lib/minicircuits.py | AttenuatorDevice.open | def open(self, host, port=23):
"""Opens a telnet connection to the desired AttenuatorDevice and
queries basic information.
Args:
host: A valid hostname (IP address or DNS-resolvable name) to an
MC-DAT attenuator instrument.
port: An optional port number (defaults to telnet default 23)
"""
self._telnet_client.open(host, port)
config_str = self._telnet_client.cmd("MN?")
if config_str.startswith("MN="):
config_str = config_str[len("MN="):]
self.properties = dict(
zip(['model', 'max_freq', 'max_atten'], config_str.split("-", 2)))
self.max_atten = float(self.properties['max_atten']) | python | def open(self, host, port=23):
"""Opens a telnet connection to the desired AttenuatorDevice and
queries basic information.
Args:
host: A valid hostname (IP address or DNS-resolvable name) to an
MC-DAT attenuator instrument.
port: An optional port number (defaults to telnet default 23)
"""
self._telnet_client.open(host, port)
config_str = self._telnet_client.cmd("MN?")
if config_str.startswith("MN="):
config_str = config_str[len("MN="):]
self.properties = dict(
zip(['model', 'max_freq', 'max_atten'], config_str.split("-", 2)))
self.max_atten = float(self.properties['max_atten']) | [
"def",
"open",
"(",
"self",
",",
"host",
",",
"port",
"=",
"23",
")",
":",
"self",
".",
"_telnet_client",
".",
"open",
"(",
"host",
",",
"port",
")",
"config_str",
"=",
"self",
".",
"_telnet_client",
".",
"cmd",
"(",
"\"MN?\"",
")",
"if",
"config_str... | Opens a telnet connection to the desired AttenuatorDevice and
queries basic information.
Args:
host: A valid hostname (IP address or DNS-resolvable name) to an
MC-DAT attenuator instrument.
port: An optional port number (defaults to telnet default 23) | [
"Opens",
"a",
"telnet",
"connection",
"to",
"the",
"desired",
"AttenuatorDevice",
"and",
"queries",
"basic",
"information",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/attenuator_lib/minicircuits.py#L50-L65 | train | 205,346 |
google/mobly | mobly/controllers/attenuator_lib/minicircuits.py | AttenuatorDevice.set_atten | def set_atten(self, idx, value):
"""Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by the device.
value: A float that is the attenuation value to set.
Raises:
Error: The underlying telnet connection to the instrument is not
open.
IndexError: The index of the attenuator is greater than the maximum
index of the underlying instrument.
ValueError: The requested set value is greater than the maximum
attenuation value.
"""
if not self.is_open:
raise attenuator.Error(
"Connection to attenuator at %s is not open!" %
self._telnet_client.host)
if idx + 1 > self.path_count:
raise IndexError("Attenuator index out of range!", self.path_count,
idx)
if value > self.max_atten:
raise ValueError("Attenuator value out of range!", self.max_atten,
value)
# The actual device uses one-based index for channel numbers.
self._telnet_client.cmd("CHAN:%s:SETATT:%s" % (idx + 1, value)) | python | def set_atten(self, idx, value):
"""Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by the device.
value: A float that is the attenuation value to set.
Raises:
Error: The underlying telnet connection to the instrument is not
open.
IndexError: The index of the attenuator is greater than the maximum
index of the underlying instrument.
ValueError: The requested set value is greater than the maximum
attenuation value.
"""
if not self.is_open:
raise attenuator.Error(
"Connection to attenuator at %s is not open!" %
self._telnet_client.host)
if idx + 1 > self.path_count:
raise IndexError("Attenuator index out of range!", self.path_count,
idx)
if value > self.max_atten:
raise ValueError("Attenuator value out of range!", self.max_atten,
value)
# The actual device uses one-based index for channel numbers.
self._telnet_client.cmd("CHAN:%s:SETATT:%s" % (idx + 1, value)) | [
"def",
"set_atten",
"(",
"self",
",",
"idx",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"attenuator",
".",
"Error",
"(",
"\"Connection to attenuator at %s is not open!\"",
"%",
"self",
".",
"_telnet_client",
".",
"host",
")",
... | Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by the device.
value: A float that is the attenuation value to set.
Raises:
Error: The underlying telnet connection to the instrument is not
open.
IndexError: The index of the attenuator is greater than the maximum
index of the underlying instrument.
ValueError: The requested set value is greater than the maximum
attenuation value. | [
"Sets",
"the",
"attenuation",
"value",
"for",
"a",
"particular",
"signal",
"path",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/attenuator_lib/minicircuits.py#L76-L104 | train | 205,347 |
google/mobly | mobly/controllers/attenuator_lib/minicircuits.py | AttenuatorDevice.get_atten | def get_atten(self, idx=0):
"""This function returns the current attenuation from an attenuator at a
given index in the instrument.
Args:
idx: This zero-based index is the identifier for a particular
attenuator in an instrument.
Raises:
Error: The underlying telnet connection to the instrument is not
open.
Returns:
A float that is the current attenuation value.
"""
if not self.is_open:
raise attenuator.Error(
"Connection to attenuator at %s is not open!" %
self._telnet_client.host)
if idx + 1 > self.path_count or idx < 0:
raise IndexError("Attenuator index out of range!", self.path_count,
idx)
atten_val_str = self._telnet_client.cmd("CHAN:%s:ATT?" % (idx + 1))
atten_val = float(atten_val_str)
return atten_val | python | def get_atten(self, idx=0):
"""This function returns the current attenuation from an attenuator at a
given index in the instrument.
Args:
idx: This zero-based index is the identifier for a particular
attenuator in an instrument.
Raises:
Error: The underlying telnet connection to the instrument is not
open.
Returns:
A float that is the current attenuation value.
"""
if not self.is_open:
raise attenuator.Error(
"Connection to attenuator at %s is not open!" %
self._telnet_client.host)
if idx + 1 > self.path_count or idx < 0:
raise IndexError("Attenuator index out of range!", self.path_count,
idx)
atten_val_str = self._telnet_client.cmd("CHAN:%s:ATT?" % (idx + 1))
atten_val = float(atten_val_str)
return atten_val | [
"def",
"get_atten",
"(",
"self",
",",
"idx",
"=",
"0",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"attenuator",
".",
"Error",
"(",
"\"Connection to attenuator at %s is not open!\"",
"%",
"self",
".",
"_telnet_client",
".",
"host",
")",
"if"... | This function returns the current attenuation from an attenuator at a
given index in the instrument.
Args:
idx: This zero-based index is the identifier for a particular
attenuator in an instrument.
Raises:
Error: The underlying telnet connection to the instrument is not
open.
Returns:
A float that is the current attenuation value. | [
"This",
"function",
"returns",
"the",
"current",
"attenuation",
"from",
"an",
"attenuator",
"at",
"a",
"given",
"index",
"in",
"the",
"instrument",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/attenuator_lib/minicircuits.py#L106-L130 | train | 205,348 |
google/mobly | mobly/controllers/android_device_lib/sl4a_client.py | Sl4aClient.restore_app_connection | def restore_app_connection(self, port=None):
"""Restores the sl4a after device got disconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the host port from which to connect to remote
device port. If not provided, find a new available port as host
port.
Raises:
AppRestoreConnectionError: When the app was not able to be started.
"""
self.host_port = port or utils.get_available_host_port()
self._retry_connect()
self.ed = self._start_event_client() | python | def restore_app_connection(self, port=None):
"""Restores the sl4a after device got disconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the host port from which to connect to remote
device port. If not provided, find a new available port as host
port.
Raises:
AppRestoreConnectionError: When the app was not able to be started.
"""
self.host_port = port or utils.get_available_host_port()
self._retry_connect()
self.ed = self._start_event_client() | [
"def",
"restore_app_connection",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"self",
".",
"host_port",
"=",
"port",
"or",
"utils",
".",
"get_available_host_port",
"(",
")",
"self",
".",
"_retry_connect",
"(",
")",
"self",
".",
"ed",
"=",
"self",
"."... | Restores the sl4a after device got disconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the host port from which to connect to remote
device port. If not provided, find a new available port as host
port.
Raises:
AppRestoreConnectionError: When the app was not able to be started. | [
"Restores",
"the",
"sl4a",
"after",
"device",
"got",
"disconnected",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/sl4a_client.py#L84-L102 | train | 205,349 |
google/mobly | mobly/controllers/android_device_lib/snippet_client.py | SnippetClient.restore_app_connection | def restore_app_connection(self, port=None):
"""Restores the app after device got reconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the host port from which to connect to remote
device port. If not provided, find a new available port as host
port.
Raises:
AppRestoreConnectionError: When the app was not able to be started.
"""
self.host_port = port or utils.get_available_host_port()
self._adb.forward(
['tcp:%d' % self.host_port,
'tcp:%d' % self.device_port])
try:
self.connect()
except:
# Log the original error and raise AppRestoreConnectionError.
self.log.exception('Failed to re-connect to app.')
raise jsonrpc_client_base.AppRestoreConnectionError(
self._ad,
('Failed to restore app connection for %s at host port %s, '
'device port %s') % (self.package, self.host_port,
self.device_port))
# Because the previous connection was lost, update self._proc
self._proc = None
self._restore_event_client() | python | def restore_app_connection(self, port=None):
"""Restores the app after device got reconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the host port from which to connect to remote
device port. If not provided, find a new available port as host
port.
Raises:
AppRestoreConnectionError: When the app was not able to be started.
"""
self.host_port = port or utils.get_available_host_port()
self._adb.forward(
['tcp:%d' % self.host_port,
'tcp:%d' % self.device_port])
try:
self.connect()
except:
# Log the original error and raise AppRestoreConnectionError.
self.log.exception('Failed to re-connect to app.')
raise jsonrpc_client_base.AppRestoreConnectionError(
self._ad,
('Failed to restore app connection for %s at host port %s, '
'device port %s') % (self.package, self.host_port,
self.device_port))
# Because the previous connection was lost, update self._proc
self._proc = None
self._restore_event_client() | [
"def",
"restore_app_connection",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"self",
".",
"host_port",
"=",
"port",
"or",
"utils",
".",
"get_available_host_port",
"(",
")",
"self",
".",
"_adb",
".",
"forward",
"(",
"[",
"'tcp:%d'",
"%",
"self",
".",... | Restores the app after device got reconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the host port from which to connect to remote
device port. If not provided, find a new available port as host
port.
Raises:
AppRestoreConnectionError: When the app was not able to be started. | [
"Restores",
"the",
"app",
"after",
"device",
"got",
"reconnected",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/snippet_client.py#L185-L218 | train | 205,350 |
google/mobly | mobly/controllers/android_device_lib/snippet_client.py | SnippetClient._restore_event_client | def _restore_event_client(self):
"""Restores previously created event client."""
if not self._event_client:
self._event_client = self._start_event_client()
return
self._event_client.host_port = self.host_port
self._event_client.device_port = self.device_port
self._event_client.connect() | python | def _restore_event_client(self):
"""Restores previously created event client."""
if not self._event_client:
self._event_client = self._start_event_client()
return
self._event_client.host_port = self.host_port
self._event_client.device_port = self.device_port
self._event_client.connect() | [
"def",
"_restore_event_client",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_event_client",
":",
"self",
".",
"_event_client",
"=",
"self",
".",
"_start_event_client",
"(",
")",
"return",
"self",
".",
"_event_client",
".",
"host_port",
"=",
"self",
"."... | Restores previously created event client. | [
"Restores",
"previously",
"created",
"event",
"client",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/snippet_client.py#L251-L258 | train | 205,351 |
google/mobly | mobly/controllers/android_device_lib/snippet_client.py | SnippetClient._read_protocol_line | def _read_protocol_line(self):
"""Reads the next line of instrumentation output relevant to snippets.
This method will skip over lines that don't start with 'SNIPPET' or
'INSTRUMENTATION_RESULT'.
Returns:
(str) Next line of snippet-related instrumentation output, stripped.
Raises:
jsonrpc_client_base.AppStartError: If EOF is reached without any
protocol lines being read.
"""
while True:
line = self._proc.stdout.readline().decode('utf-8')
if not line:
raise jsonrpc_client_base.AppStartError(
self._ad, 'Unexpected EOF waiting for app to start')
# readline() uses an empty string to mark EOF, and a single newline
# to mark regular empty lines in the output. Don't move the strip()
# call above the truthiness check, or this method will start
# considering any blank output line to be EOF.
line = line.strip()
if (line.startswith('INSTRUMENTATION_RESULT:')
or line.startswith('SNIPPET ')):
self.log.debug(
'Accepted line from instrumentation output: "%s"', line)
return line
self.log.debug('Discarded line from instrumentation output: "%s"',
line) | python | def _read_protocol_line(self):
"""Reads the next line of instrumentation output relevant to snippets.
This method will skip over lines that don't start with 'SNIPPET' or
'INSTRUMENTATION_RESULT'.
Returns:
(str) Next line of snippet-related instrumentation output, stripped.
Raises:
jsonrpc_client_base.AppStartError: If EOF is reached without any
protocol lines being read.
"""
while True:
line = self._proc.stdout.readline().decode('utf-8')
if not line:
raise jsonrpc_client_base.AppStartError(
self._ad, 'Unexpected EOF waiting for app to start')
# readline() uses an empty string to mark EOF, and a single newline
# to mark regular empty lines in the output. Don't move the strip()
# call above the truthiness check, or this method will start
# considering any blank output line to be EOF.
line = line.strip()
if (line.startswith('INSTRUMENTATION_RESULT:')
or line.startswith('SNIPPET ')):
self.log.debug(
'Accepted line from instrumentation output: "%s"', line)
return line
self.log.debug('Discarded line from instrumentation output: "%s"',
line) | [
"def",
"_read_protocol_line",
"(",
"self",
")",
":",
"while",
"True",
":",
"line",
"=",
"self",
".",
"_proc",
".",
"stdout",
".",
"readline",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"not",
"line",
":",
"raise",
"jsonrpc_client_base",
".",
"... | Reads the next line of instrumentation output relevant to snippets.
This method will skip over lines that don't start with 'SNIPPET' or
'INSTRUMENTATION_RESULT'.
Returns:
(str) Next line of snippet-related instrumentation output, stripped.
Raises:
jsonrpc_client_base.AppStartError: If EOF is reached without any
protocol lines being read. | [
"Reads",
"the",
"next",
"line",
"of",
"instrumentation",
"output",
"relevant",
"to",
"snippets",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/snippet_client.py#L294-L323 | train | 205,352 |
google/mobly | mobly/controllers/android_device_lib/snippet_client.py | SnippetClient._get_persist_command | def _get_persist_command(self):
"""Check availability and return path of command if available."""
for command in [_SETSID_COMMAND, _NOHUP_COMMAND]:
try:
if command in self._adb.shell(['which',
command]).decode('utf-8'):
return command
except adb.AdbError:
continue
self.log.warning(
'No %s and %s commands available to launch instrument '
'persistently, tests that depend on UiAutomator and '
'at the same time performs USB disconnection may fail',
_SETSID_COMMAND, _NOHUP_COMMAND)
return '' | python | def _get_persist_command(self):
"""Check availability and return path of command if available."""
for command in [_SETSID_COMMAND, _NOHUP_COMMAND]:
try:
if command in self._adb.shell(['which',
command]).decode('utf-8'):
return command
except adb.AdbError:
continue
self.log.warning(
'No %s and %s commands available to launch instrument '
'persistently, tests that depend on UiAutomator and '
'at the same time performs USB disconnection may fail',
_SETSID_COMMAND, _NOHUP_COMMAND)
return '' | [
"def",
"_get_persist_command",
"(",
"self",
")",
":",
"for",
"command",
"in",
"[",
"_SETSID_COMMAND",
",",
"_NOHUP_COMMAND",
"]",
":",
"try",
":",
"if",
"command",
"in",
"self",
".",
"_adb",
".",
"shell",
"(",
"[",
"'which'",
",",
"command",
"]",
")",
... | Check availability and return path of command if available. | [
"Check",
"availability",
"and",
"return",
"path",
"of",
"command",
"if",
"available",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/snippet_client.py#L325-L339 | train | 205,353 |
google/mobly | mobly/controllers/android_device_lib/snippet_client.py | SnippetClient.help | def help(self, print_output=True):
"""Calls the help RPC, which returns the list of RPC calls available.
This RPC should normally be used in an interactive console environment
where the output should be printed instead of returned. Otherwise,
newlines will be escaped, which will make the output difficult to read.
Args:
print_output: A bool for whether the output should be printed.
Returns:
A str containing the help output otherwise None if print_output
wasn't set.
"""
help_text = self._rpc('help')
if print_output:
print(help_text)
else:
return help_text | python | def help(self, print_output=True):
"""Calls the help RPC, which returns the list of RPC calls available.
This RPC should normally be used in an interactive console environment
where the output should be printed instead of returned. Otherwise,
newlines will be escaped, which will make the output difficult to read.
Args:
print_output: A bool for whether the output should be printed.
Returns:
A str containing the help output otherwise None if print_output
wasn't set.
"""
help_text = self._rpc('help')
if print_output:
print(help_text)
else:
return help_text | [
"def",
"help",
"(",
"self",
",",
"print_output",
"=",
"True",
")",
":",
"help_text",
"=",
"self",
".",
"_rpc",
"(",
"'help'",
")",
"if",
"print_output",
":",
"print",
"(",
"help_text",
")",
"else",
":",
"return",
"help_text"
] | Calls the help RPC, which returns the list of RPC calls available.
This RPC should normally be used in an interactive console environment
where the output should be printed instead of returned. Otherwise,
newlines will be escaped, which will make the output difficult to read.
Args:
print_output: A bool for whether the output should be printed.
Returns:
A str containing the help output otherwise None if print_output
wasn't set. | [
"Calls",
"the",
"help",
"RPC",
"which",
"returns",
"the",
"list",
"of",
"RPC",
"calls",
"available",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/snippet_client.py#L341-L359 | train | 205,354 |
google/mobly | mobly/controllers/android_device_lib/service_manager.py | ServiceManager.is_any_alive | def is_any_alive(self):
"""True if any service is alive; False otherwise."""
for service in self._service_objects.values():
if service.is_alive:
return True
return False | python | def is_any_alive(self):
"""True if any service is alive; False otherwise."""
for service in self._service_objects.values():
if service.is_alive:
return True
return False | [
"def",
"is_any_alive",
"(",
"self",
")",
":",
"for",
"service",
"in",
"self",
".",
"_service_objects",
".",
"values",
"(",
")",
":",
"if",
"service",
".",
"is_alive",
":",
"return",
"True",
"return",
"False"
] | True if any service is alive; False otherwise. | [
"True",
"if",
"any",
"service",
"is",
"alive",
";",
"False",
"otherwise",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/service_manager.py#L52-L57 | train | 205,355 |
google/mobly | mobly/controllers/android_device_lib/service_manager.py | ServiceManager.unregister | def unregister(self, alias):
"""Unregisters a service instance.
Stops a service and removes it from the manager.
Args:
alias: string, the alias of the service instance to unregister.
"""
if alias not in self._service_objects:
raise Error(self._device,
'No service is registered with alias "%s".' % alias)
service_obj = self._service_objects.pop(alias)
if service_obj.is_alive:
with expects.expect_no_raises(
'Failed to stop service instance "%s".' % alias):
service_obj.stop() | python | def unregister(self, alias):
"""Unregisters a service instance.
Stops a service and removes it from the manager.
Args:
alias: string, the alias of the service instance to unregister.
"""
if alias not in self._service_objects:
raise Error(self._device,
'No service is registered with alias "%s".' % alias)
service_obj = self._service_objects.pop(alias)
if service_obj.is_alive:
with expects.expect_no_raises(
'Failed to stop service instance "%s".' % alias):
service_obj.stop() | [
"def",
"unregister",
"(",
"self",
",",
"alias",
")",
":",
"if",
"alias",
"not",
"in",
"self",
".",
"_service_objects",
":",
"raise",
"Error",
"(",
"self",
".",
"_device",
",",
"'No service is registered with alias \"%s\".'",
"%",
"alias",
")",
"service_obj",
"... | Unregisters a service instance.
Stops a service and removes it from the manager.
Args:
alias: string, the alias of the service instance to unregister. | [
"Unregisters",
"a",
"service",
"instance",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/service_manager.py#L88-L103 | train | 205,356 |
google/mobly | mobly/controllers/android_device_lib/service_manager.py | ServiceManager.unregister_all | def unregister_all(self):
"""Safely unregisters all active instances.
Errors occurred here will be recorded but not raised.
"""
aliases = list(self._service_objects.keys())
for alias in aliases:
self.unregister(alias) | python | def unregister_all(self):
"""Safely unregisters all active instances.
Errors occurred here will be recorded but not raised.
"""
aliases = list(self._service_objects.keys())
for alias in aliases:
self.unregister(alias) | [
"def",
"unregister_all",
"(",
"self",
")",
":",
"aliases",
"=",
"list",
"(",
"self",
".",
"_service_objects",
".",
"keys",
"(",
")",
")",
"for",
"alias",
"in",
"aliases",
":",
"self",
".",
"unregister",
"(",
"alias",
")"
] | Safely unregisters all active instances.
Errors occurred here will be recorded but not raised. | [
"Safely",
"unregisters",
"all",
"active",
"instances",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/service_manager.py#L105-L112 | train | 205,357 |
google/mobly | mobly/controllers/android_device_lib/service_manager.py | ServiceManager.start_all | def start_all(self):
"""Starts all inactive service instances."""
for alias, service in self._service_objects.items():
if not service.is_alive:
with expects.expect_no_raises(
'Failed to start service "%s".' % alias):
service.start() | python | def start_all(self):
"""Starts all inactive service instances."""
for alias, service in self._service_objects.items():
if not service.is_alive:
with expects.expect_no_raises(
'Failed to start service "%s".' % alias):
service.start() | [
"def",
"start_all",
"(",
"self",
")",
":",
"for",
"alias",
",",
"service",
"in",
"self",
".",
"_service_objects",
".",
"items",
"(",
")",
":",
"if",
"not",
"service",
".",
"is_alive",
":",
"with",
"expects",
".",
"expect_no_raises",
"(",
"'Failed to start ... | Starts all inactive service instances. | [
"Starts",
"all",
"inactive",
"service",
"instances",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/service_manager.py#L114-L120 | train | 205,358 |
google/mobly | mobly/controllers/android_device_lib/service_manager.py | ServiceManager.stop_all | def stop_all(self):
"""Stops all active service instances."""
for alias, service in self._service_objects.items():
if service.is_alive:
with expects.expect_no_raises(
'Failed to stop service "%s".' % alias):
service.stop() | python | def stop_all(self):
"""Stops all active service instances."""
for alias, service in self._service_objects.items():
if service.is_alive:
with expects.expect_no_raises(
'Failed to stop service "%s".' % alias):
service.stop() | [
"def",
"stop_all",
"(",
"self",
")",
":",
"for",
"alias",
",",
"service",
"in",
"self",
".",
"_service_objects",
".",
"items",
"(",
")",
":",
"if",
"service",
".",
"is_alive",
":",
"with",
"expects",
".",
"expect_no_raises",
"(",
"'Failed to stop service \"%... | Stops all active service instances. | [
"Stops",
"all",
"active",
"service",
"instances",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/service_manager.py#L122-L128 | train | 205,359 |
google/mobly | mobly/controllers/android_device_lib/service_manager.py | ServiceManager.pause_all | def pause_all(self):
"""Pauses all service instances."""
for alias, service in self._service_objects.items():
with expects.expect_no_raises(
'Failed to pause service "%s".' % alias):
service.pause() | python | def pause_all(self):
"""Pauses all service instances."""
for alias, service in self._service_objects.items():
with expects.expect_no_raises(
'Failed to pause service "%s".' % alias):
service.pause() | [
"def",
"pause_all",
"(",
"self",
")",
":",
"for",
"alias",
",",
"service",
"in",
"self",
".",
"_service_objects",
".",
"items",
"(",
")",
":",
"with",
"expects",
".",
"expect_no_raises",
"(",
"'Failed to pause service \"%s\".'",
"%",
"alias",
")",
":",
"serv... | Pauses all service instances. | [
"Pauses",
"all",
"service",
"instances",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/service_manager.py#L130-L135 | train | 205,360 |
google/mobly | mobly/controllers/android_device_lib/service_manager.py | ServiceManager.resume_all | def resume_all(self):
"""Resumes all service instances."""
for alias, service in self._service_objects.items():
with expects.expect_no_raises(
'Failed to pause service "%s".' % alias):
service.resume() | python | def resume_all(self):
"""Resumes all service instances."""
for alias, service in self._service_objects.items():
with expects.expect_no_raises(
'Failed to pause service "%s".' % alias):
service.resume() | [
"def",
"resume_all",
"(",
"self",
")",
":",
"for",
"alias",
",",
"service",
"in",
"self",
".",
"_service_objects",
".",
"items",
"(",
")",
":",
"with",
"expects",
".",
"expect_no_raises",
"(",
"'Failed to pause service \"%s\".'",
"%",
"alias",
")",
":",
"ser... | Resumes all service instances. | [
"Resumes",
"all",
"service",
"instances",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/service_manager.py#L137-L142 | train | 205,361 |
google/mobly | mobly/controllers/android_device.py | create | def create(configs):
"""Creates AndroidDevice controller objects.
Args:
configs: A list of dicts, each representing a configuration for an
Android device.
Returns:
A list of AndroidDevice objects.
"""
if not configs:
raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG)
elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN:
ads = get_all_instances()
elif not isinstance(configs, list):
raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)
elif isinstance(configs[0], dict):
# Configs is a list of dicts.
ads = get_instances_with_configs(configs)
elif isinstance(configs[0], basestring):
# Configs is a list of strings representing serials.
ads = get_instances(configs)
else:
raise Error('No valid config found in: %s' % configs)
valid_ad_identifiers = list_adb_devices() + list_adb_devices_by_usb_id()
for ad in ads:
if ad.serial not in valid_ad_identifiers:
raise DeviceError(ad, 'Android device is specified in config but'
' is not attached.')
_start_services_on_ads(ads)
return ads | python | def create(configs):
"""Creates AndroidDevice controller objects.
Args:
configs: A list of dicts, each representing a configuration for an
Android device.
Returns:
A list of AndroidDevice objects.
"""
if not configs:
raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG)
elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN:
ads = get_all_instances()
elif not isinstance(configs, list):
raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)
elif isinstance(configs[0], dict):
# Configs is a list of dicts.
ads = get_instances_with_configs(configs)
elif isinstance(configs[0], basestring):
# Configs is a list of strings representing serials.
ads = get_instances(configs)
else:
raise Error('No valid config found in: %s' % configs)
valid_ad_identifiers = list_adb_devices() + list_adb_devices_by_usb_id()
for ad in ads:
if ad.serial not in valid_ad_identifiers:
raise DeviceError(ad, 'Android device is specified in config but'
' is not attached.')
_start_services_on_ads(ads)
return ads | [
"def",
"create",
"(",
"configs",
")",
":",
"if",
"not",
"configs",
":",
"raise",
"Error",
"(",
"ANDROID_DEVICE_EMPTY_CONFIG_MSG",
")",
"elif",
"configs",
"==",
"ANDROID_DEVICE_PICK_ALL_TOKEN",
":",
"ads",
"=",
"get_all_instances",
"(",
")",
"elif",
"not",
"isins... | Creates AndroidDevice controller objects.
Args:
configs: A list of dicts, each representing a configuration for an
Android device.
Returns:
A list of AndroidDevice objects. | [
"Creates",
"AndroidDevice",
"controller",
"objects",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L67-L98 | train | 205,362 |
google/mobly | mobly/controllers/android_device.py | destroy | def destroy(ads):
"""Cleans up AndroidDevice objects.
Args:
ads: A list of AndroidDevice objects.
"""
for ad in ads:
try:
ad.services.stop_all()
except:
ad.log.exception('Failed to clean up properly.') | python | def destroy(ads):
"""Cleans up AndroidDevice objects.
Args:
ads: A list of AndroidDevice objects.
"""
for ad in ads:
try:
ad.services.stop_all()
except:
ad.log.exception('Failed to clean up properly.') | [
"def",
"destroy",
"(",
"ads",
")",
":",
"for",
"ad",
"in",
"ads",
":",
"try",
":",
"ad",
".",
"services",
".",
"stop_all",
"(",
")",
"except",
":",
"ad",
".",
"log",
".",
"exception",
"(",
"'Failed to clean up properly.'",
")"
] | Cleans up AndroidDevice objects.
Args:
ads: A list of AndroidDevice objects. | [
"Cleans",
"up",
"AndroidDevice",
"objects",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L101-L111 | train | 205,363 |
google/mobly | mobly/controllers/android_device.py | _start_services_on_ads | def _start_services_on_ads(ads):
"""Starts long running services on multiple AndroidDevice objects.
If any one AndroidDevice object fails to start services, cleans up all
existing AndroidDevice objects and their services.
Args:
ads: A list of AndroidDevice objects whose services to start.
"""
running_ads = []
for ad in ads:
running_ads.append(ad)
start_logcat = not getattr(ad, KEY_SKIP_LOGCAT,
DEFAULT_VALUE_SKIP_LOGCAT)
try:
ad.services.register(
SERVICE_NAME_LOGCAT, logcat.Logcat, start_service=start_logcat)
except Exception:
is_required = getattr(ad, KEY_DEVICE_REQUIRED,
DEFAULT_VALUE_DEVICE_REQUIRED)
if is_required:
ad.log.exception('Failed to start some services, abort!')
destroy(running_ads)
raise
else:
ad.log.exception('Skipping this optional device because some '
'services failed to start.') | python | def _start_services_on_ads(ads):
"""Starts long running services on multiple AndroidDevice objects.
If any one AndroidDevice object fails to start services, cleans up all
existing AndroidDevice objects and their services.
Args:
ads: A list of AndroidDevice objects whose services to start.
"""
running_ads = []
for ad in ads:
running_ads.append(ad)
start_logcat = not getattr(ad, KEY_SKIP_LOGCAT,
DEFAULT_VALUE_SKIP_LOGCAT)
try:
ad.services.register(
SERVICE_NAME_LOGCAT, logcat.Logcat, start_service=start_logcat)
except Exception:
is_required = getattr(ad, KEY_DEVICE_REQUIRED,
DEFAULT_VALUE_DEVICE_REQUIRED)
if is_required:
ad.log.exception('Failed to start some services, abort!')
destroy(running_ads)
raise
else:
ad.log.exception('Skipping this optional device because some '
'services failed to start.') | [
"def",
"_start_services_on_ads",
"(",
"ads",
")",
":",
"running_ads",
"=",
"[",
"]",
"for",
"ad",
"in",
"ads",
":",
"running_ads",
".",
"append",
"(",
"ad",
")",
"start_logcat",
"=",
"not",
"getattr",
"(",
"ad",
",",
"KEY_SKIP_LOGCAT",
",",
"DEFAULT_VALUE_... | Starts long running services on multiple AndroidDevice objects.
If any one AndroidDevice object fails to start services, cleans up all
existing AndroidDevice objects and their services.
Args:
ads: A list of AndroidDevice objects whose services to start. | [
"Starts",
"long",
"running",
"services",
"on",
"multiple",
"AndroidDevice",
"objects",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L126-L152 | train | 205,364 |
google/mobly | mobly/controllers/android_device.py | parse_device_list | def parse_device_list(device_list_str, key):
"""Parses a byte string representing a list of devices.
The string is generated by calling either adb or fastboot. The tokens in
each string is tab-separated.
Args:
device_list_str: Output of adb or fastboot.
key: The token that signifies a device in device_list_str.
Returns:
A list of android device serial numbers.
"""
clean_lines = new_str(device_list_str, 'utf-8').strip().split('\n')
results = []
for line in clean_lines:
tokens = line.strip().split('\t')
if len(tokens) == 2 and tokens[1] == key:
results.append(tokens[0])
return results | python | def parse_device_list(device_list_str, key):
"""Parses a byte string representing a list of devices.
The string is generated by calling either adb or fastboot. The tokens in
each string is tab-separated.
Args:
device_list_str: Output of adb or fastboot.
key: The token that signifies a device in device_list_str.
Returns:
A list of android device serial numbers.
"""
clean_lines = new_str(device_list_str, 'utf-8').strip().split('\n')
results = []
for line in clean_lines:
tokens = line.strip().split('\t')
if len(tokens) == 2 and tokens[1] == key:
results.append(tokens[0])
return results | [
"def",
"parse_device_list",
"(",
"device_list_str",
",",
"key",
")",
":",
"clean_lines",
"=",
"new_str",
"(",
"device_list_str",
",",
"'utf-8'",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"results",
"=",
"[",
"]",
"for",
"line",
"in",
... | Parses a byte string representing a list of devices.
The string is generated by calling either adb or fastboot. The tokens in
each string is tab-separated.
Args:
device_list_str: Output of adb or fastboot.
key: The token that signifies a device in device_list_str.
Returns:
A list of android device serial numbers. | [
"Parses",
"a",
"byte",
"string",
"representing",
"a",
"list",
"of",
"devices",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L164-L183 | train | 205,365 |
google/mobly | mobly/controllers/android_device.py | list_adb_devices_by_usb_id | def list_adb_devices_by_usb_id():
"""List the usb id of all android devices connected to the computer that
are detected by adb.
Returns:
A list of strings that are android device usb ids. Empty if there's
none.
"""
out = adb.AdbProxy().devices(['-l'])
clean_lines = new_str(out, 'utf-8').strip().split('\n')
results = []
for line in clean_lines:
tokens = line.strip().split()
if len(tokens) > 2 and tokens[1] == 'device':
results.append(tokens[2])
return results | python | def list_adb_devices_by_usb_id():
"""List the usb id of all android devices connected to the computer that
are detected by adb.
Returns:
A list of strings that are android device usb ids. Empty if there's
none.
"""
out = adb.AdbProxy().devices(['-l'])
clean_lines = new_str(out, 'utf-8').strip().split('\n')
results = []
for line in clean_lines:
tokens = line.strip().split()
if len(tokens) > 2 and tokens[1] == 'device':
results.append(tokens[2])
return results | [
"def",
"list_adb_devices_by_usb_id",
"(",
")",
":",
"out",
"=",
"adb",
".",
"AdbProxy",
"(",
")",
".",
"devices",
"(",
"[",
"'-l'",
"]",
")",
"clean_lines",
"=",
"new_str",
"(",
"out",
",",
"'utf-8'",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
... | List the usb id of all android devices connected to the computer that
are detected by adb.
Returns:
A list of strings that are android device usb ids. Empty if there's
none. | [
"List",
"the",
"usb",
"id",
"of",
"all",
"android",
"devices",
"connected",
"to",
"the",
"computer",
"that",
"are",
"detected",
"by",
"adb",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L197-L212 | train | 205,366 |
google/mobly | mobly/controllers/android_device.py | get_instances | def get_instances(serials):
"""Create AndroidDevice instances from a list of serials.
Args:
serials: A list of android device serials.
Returns:
A list of AndroidDevice objects.
"""
results = []
for s in serials:
results.append(AndroidDevice(s))
return results | python | def get_instances(serials):
"""Create AndroidDevice instances from a list of serials.
Args:
serials: A list of android device serials.
Returns:
A list of AndroidDevice objects.
"""
results = []
for s in serials:
results.append(AndroidDevice(s))
return results | [
"def",
"get_instances",
"(",
"serials",
")",
":",
"results",
"=",
"[",
"]",
"for",
"s",
"in",
"serials",
":",
"results",
".",
"append",
"(",
"AndroidDevice",
"(",
"s",
")",
")",
"return",
"results"
] | Create AndroidDevice instances from a list of serials.
Args:
serials: A list of android device serials.
Returns:
A list of AndroidDevice objects. | [
"Create",
"AndroidDevice",
"instances",
"from",
"a",
"list",
"of",
"serials",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L226-L238 | train | 205,367 |
google/mobly | mobly/controllers/android_device.py | get_instances_with_configs | def get_instances_with_configs(configs):
"""Create AndroidDevice instances from a list of dict configs.
Each config should have the required key-value pair 'serial'.
Args:
configs: A list of dicts each representing the configuration of one
android device.
Returns:
A list of AndroidDevice objects.
"""
results = []
for c in configs:
try:
serial = c.pop('serial')
except KeyError:
raise Error(
'Required value "serial" is missing in AndroidDevice config %s.'
% c)
is_required = c.get(KEY_DEVICE_REQUIRED, True)
try:
ad = AndroidDevice(serial)
ad.load_config(c)
except Exception:
if is_required:
raise
ad.log.exception('Skipping this optional device due to error.')
continue
results.append(ad)
return results | python | def get_instances_with_configs(configs):
"""Create AndroidDevice instances from a list of dict configs.
Each config should have the required key-value pair 'serial'.
Args:
configs: A list of dicts each representing the configuration of one
android device.
Returns:
A list of AndroidDevice objects.
"""
results = []
for c in configs:
try:
serial = c.pop('serial')
except KeyError:
raise Error(
'Required value "serial" is missing in AndroidDevice config %s.'
% c)
is_required = c.get(KEY_DEVICE_REQUIRED, True)
try:
ad = AndroidDevice(serial)
ad.load_config(c)
except Exception:
if is_required:
raise
ad.log.exception('Skipping this optional device due to error.')
continue
results.append(ad)
return results | [
"def",
"get_instances_with_configs",
"(",
"configs",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"configs",
":",
"try",
":",
"serial",
"=",
"c",
".",
"pop",
"(",
"'serial'",
")",
"except",
"KeyError",
":",
"raise",
"Error",
"(",
"'Required valu... | Create AndroidDevice instances from a list of dict configs.
Each config should have the required key-value pair 'serial'.
Args:
configs: A list of dicts each representing the configuration of one
android device.
Returns:
A list of AndroidDevice objects. | [
"Create",
"AndroidDevice",
"instances",
"from",
"a",
"list",
"of",
"dict",
"configs",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L241-L271 | train | 205,368 |
google/mobly | mobly/controllers/android_device.py | get_all_instances | def get_all_instances(include_fastboot=False):
"""Create AndroidDevice instances for all attached android devices.
Args:
include_fastboot: Whether to include devices in bootloader mode or not.
Returns:
A list of AndroidDevice objects each representing an android device
attached to the computer.
"""
if include_fastboot:
serial_list = list_adb_devices() + list_fastboot_devices()
return get_instances(serial_list)
return get_instances(list_adb_devices()) | python | def get_all_instances(include_fastboot=False):
"""Create AndroidDevice instances for all attached android devices.
Args:
include_fastboot: Whether to include devices in bootloader mode or not.
Returns:
A list of AndroidDevice objects each representing an android device
attached to the computer.
"""
if include_fastboot:
serial_list = list_adb_devices() + list_fastboot_devices()
return get_instances(serial_list)
return get_instances(list_adb_devices()) | [
"def",
"get_all_instances",
"(",
"include_fastboot",
"=",
"False",
")",
":",
"if",
"include_fastboot",
":",
"serial_list",
"=",
"list_adb_devices",
"(",
")",
"+",
"list_fastboot_devices",
"(",
")",
"return",
"get_instances",
"(",
"serial_list",
")",
"return",
"get... | Create AndroidDevice instances for all attached android devices.
Args:
include_fastboot: Whether to include devices in bootloader mode or not.
Returns:
A list of AndroidDevice objects each representing an android device
attached to the computer. | [
"Create",
"AndroidDevice",
"instances",
"for",
"all",
"attached",
"android",
"devices",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L274-L287 | train | 205,369 |
google/mobly | mobly/controllers/android_device.py | filter_devices | def filter_devices(ads, func):
"""Finds the AndroidDevice instances from a list that match certain
conditions.
Args:
ads: A list of AndroidDevice instances.
func: A function that takes an AndroidDevice object and returns True
if the device satisfies the filter condition.
Returns:
A list of AndroidDevice instances that satisfy the filter condition.
"""
results = []
for ad in ads:
if func(ad):
results.append(ad)
return results | python | def filter_devices(ads, func):
"""Finds the AndroidDevice instances from a list that match certain
conditions.
Args:
ads: A list of AndroidDevice instances.
func: A function that takes an AndroidDevice object and returns True
if the device satisfies the filter condition.
Returns:
A list of AndroidDevice instances that satisfy the filter condition.
"""
results = []
for ad in ads:
if func(ad):
results.append(ad)
return results | [
"def",
"filter_devices",
"(",
"ads",
",",
"func",
")",
":",
"results",
"=",
"[",
"]",
"for",
"ad",
"in",
"ads",
":",
"if",
"func",
"(",
"ad",
")",
":",
"results",
".",
"append",
"(",
"ad",
")",
"return",
"results"
] | Finds the AndroidDevice instances from a list that match certain
conditions.
Args:
ads: A list of AndroidDevice instances.
func: A function that takes an AndroidDevice object and returns True
if the device satisfies the filter condition.
Returns:
A list of AndroidDevice instances that satisfy the filter condition. | [
"Finds",
"the",
"AndroidDevice",
"instances",
"from",
"a",
"list",
"that",
"match",
"certain",
"conditions",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L290-L306 | train | 205,370 |
google/mobly | mobly/controllers/android_device.py | get_devices | def get_devices(ads, **kwargs):
"""Finds a list of AndroidDevice instance from a list that has specific
attributes of certain values.
Example:
get_devices(android_devices, label='foo', phone_number='1234567890')
get_devices(android_devices, model='angler')
Args:
ads: A list of AndroidDevice instances.
kwargs: keyword arguments used to filter AndroidDevice instances.
Returns:
A list of target AndroidDevice instances.
Raises:
Error: No devices are matched.
"""
def _get_device_filter(ad):
for k, v in kwargs.items():
if not hasattr(ad, k):
return False
elif getattr(ad, k) != v:
return False
return True
filtered = filter_devices(ads, _get_device_filter)
if not filtered:
raise Error(
'Could not find a target device that matches condition: %s.' %
kwargs)
else:
return filtered | python | def get_devices(ads, **kwargs):
"""Finds a list of AndroidDevice instance from a list that has specific
attributes of certain values.
Example:
get_devices(android_devices, label='foo', phone_number='1234567890')
get_devices(android_devices, model='angler')
Args:
ads: A list of AndroidDevice instances.
kwargs: keyword arguments used to filter AndroidDevice instances.
Returns:
A list of target AndroidDevice instances.
Raises:
Error: No devices are matched.
"""
def _get_device_filter(ad):
for k, v in kwargs.items():
if not hasattr(ad, k):
return False
elif getattr(ad, k) != v:
return False
return True
filtered = filter_devices(ads, _get_device_filter)
if not filtered:
raise Error(
'Could not find a target device that matches condition: %s.' %
kwargs)
else:
return filtered | [
"def",
"get_devices",
"(",
"ads",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_get_device_filter",
"(",
"ad",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"ad",
",",
"k",
")",
":",
"re... | Finds a list of AndroidDevice instance from a list that has specific
attributes of certain values.
Example:
get_devices(android_devices, label='foo', phone_number='1234567890')
get_devices(android_devices, model='angler')
Args:
ads: A list of AndroidDevice instances.
kwargs: keyword arguments used to filter AndroidDevice instances.
Returns:
A list of target AndroidDevice instances.
Raises:
Error: No devices are matched. | [
"Finds",
"a",
"list",
"of",
"AndroidDevice",
"instance",
"from",
"a",
"list",
"that",
"has",
"specific",
"attributes",
"of",
"certain",
"values",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L309-L342 | train | 205,371 |
google/mobly | mobly/controllers/android_device.py | get_device | def get_device(ads, **kwargs):
"""Finds a unique AndroidDevice instance from a list that has specific
attributes of certain values.
Deprecated, use `get_devices(ads, **kwargs)[0]` instead.
This method will be removed in 1.8.
Example:
get_device(android_devices, label='foo', phone_number='1234567890')
get_device(android_devices, model='angler')
Args:
ads: A list of AndroidDevice instances.
kwargs: keyword arguments used to filter AndroidDevice instances.
Returns:
The target AndroidDevice instance.
Raises:
Error: None or more than one device is matched.
"""
filtered = get_devices(ads, **kwargs)
if len(filtered) == 1:
return filtered[0]
else:
serials = [ad.serial for ad in filtered]
raise Error('More than one device matched: %s' % serials) | python | def get_device(ads, **kwargs):
"""Finds a unique AndroidDevice instance from a list that has specific
attributes of certain values.
Deprecated, use `get_devices(ads, **kwargs)[0]` instead.
This method will be removed in 1.8.
Example:
get_device(android_devices, label='foo', phone_number='1234567890')
get_device(android_devices, model='angler')
Args:
ads: A list of AndroidDevice instances.
kwargs: keyword arguments used to filter AndroidDevice instances.
Returns:
The target AndroidDevice instance.
Raises:
Error: None or more than one device is matched.
"""
filtered = get_devices(ads, **kwargs)
if len(filtered) == 1:
return filtered[0]
else:
serials = [ad.serial for ad in filtered]
raise Error('More than one device matched: %s' % serials) | [
"def",
"get_device",
"(",
"ads",
",",
"*",
"*",
"kwargs",
")",
":",
"filtered",
"=",
"get_devices",
"(",
"ads",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"filtered",
")",
"==",
"1",
":",
"return",
"filtered",
"[",
"0",
"]",
"else",
":",
"se... | Finds a unique AndroidDevice instance from a list that has specific
attributes of certain values.
Deprecated, use `get_devices(ads, **kwargs)[0]` instead.
This method will be removed in 1.8.
Example:
get_device(android_devices, label='foo', phone_number='1234567890')
get_device(android_devices, model='angler')
Args:
ads: A list of AndroidDevice instances.
kwargs: keyword arguments used to filter AndroidDevice instances.
Returns:
The target AndroidDevice instance.
Raises:
Error: None or more than one device is matched. | [
"Finds",
"a",
"unique",
"AndroidDevice",
"instance",
"from",
"a",
"list",
"that",
"has",
"specific",
"attributes",
"of",
"certain",
"values",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L345-L372 | train | 205,372 |
google/mobly | mobly/controllers/android_device.py | take_bug_reports | def take_bug_reports(ads, test_name, begin_time, destination=None):
"""Takes bug reports on a list of android devices.
If you want to take a bug report, call this function with a list of
android_device objects in on_fail. But reports will be taken on all the
devices in the list concurrently. Bug report takes a relative long
time to take, so use this cautiously.
Args:
ads: A list of AndroidDevice instances.
test_name: Name of the test method that triggered this bug report.
begin_time: timestamp taken when the test started, can be either
string or int.
destination: string, path to the directory where the bugreport
should be saved.
"""
begin_time = mobly_logger.normalize_log_line_timestamp(str(begin_time))
def take_br(test_name, begin_time, ad, destination):
ad.take_bug_report(test_name, begin_time, destination=destination)
args = [(test_name, begin_time, ad, destination) for ad in ads]
utils.concurrent_exec(take_br, args) | python | def take_bug_reports(ads, test_name, begin_time, destination=None):
"""Takes bug reports on a list of android devices.
If you want to take a bug report, call this function with a list of
android_device objects in on_fail. But reports will be taken on all the
devices in the list concurrently. Bug report takes a relative long
time to take, so use this cautiously.
Args:
ads: A list of AndroidDevice instances.
test_name: Name of the test method that triggered this bug report.
begin_time: timestamp taken when the test started, can be either
string or int.
destination: string, path to the directory where the bugreport
should be saved.
"""
begin_time = mobly_logger.normalize_log_line_timestamp(str(begin_time))
def take_br(test_name, begin_time, ad, destination):
ad.take_bug_report(test_name, begin_time, destination=destination)
args = [(test_name, begin_time, ad, destination) for ad in ads]
utils.concurrent_exec(take_br, args) | [
"def",
"take_bug_reports",
"(",
"ads",
",",
"test_name",
",",
"begin_time",
",",
"destination",
"=",
"None",
")",
":",
"begin_time",
"=",
"mobly_logger",
".",
"normalize_log_line_timestamp",
"(",
"str",
"(",
"begin_time",
")",
")",
"def",
"take_br",
"(",
"test... | Takes bug reports on a list of android devices.
If you want to take a bug report, call this function with a list of
android_device objects in on_fail. But reports will be taken on all the
devices in the list concurrently. Bug report takes a relative long
time to take, so use this cautiously.
Args:
ads: A list of AndroidDevice instances.
test_name: Name of the test method that triggered this bug report.
begin_time: timestamp taken when the test started, can be either
string or int.
destination: string, path to the directory where the bugreport
should be saved. | [
"Takes",
"bug",
"reports",
"on",
"a",
"list",
"of",
"android",
"devices",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L375-L397 | train | 205,373 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice._normalized_serial | def _normalized_serial(self):
"""Normalized serial name for usage in log filename.
Some Android emulators use ip:port as their serial names, while on
Windows `:` is not valid in filename, it should be sanitized first.
"""
if self._serial is None:
return None
normalized_serial = self._serial.replace(' ', '_')
normalized_serial = normalized_serial.replace(':', '-')
return normalized_serial | python | def _normalized_serial(self):
"""Normalized serial name for usage in log filename.
Some Android emulators use ip:port as their serial names, while on
Windows `:` is not valid in filename, it should be sanitized first.
"""
if self._serial is None:
return None
normalized_serial = self._serial.replace(' ', '_')
normalized_serial = normalized_serial.replace(':', '-')
return normalized_serial | [
"def",
"_normalized_serial",
"(",
"self",
")",
":",
"if",
"self",
".",
"_serial",
"is",
"None",
":",
"return",
"None",
"normalized_serial",
"=",
"self",
".",
"_serial",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"normalized_serial",
"=",
"normalized_serial... | Normalized serial name for usage in log filename.
Some Android emulators use ip:port as their serial names, while on
Windows `:` is not valid in filename, it should be sanitized first. | [
"Normalized",
"serial",
"name",
"for",
"usage",
"in",
"log",
"filename",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L456-L466 | train | 205,374 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.device_info | def device_info(self):
"""Information to be pulled into controller info.
The latest serial, model, and build_info are included. Additional info
can be added via `add_device_info`.
"""
info = {
'serial': self.serial,
'model': self.model,
'build_info': self.build_info,
'user_added_info': self._user_added_device_info
}
return info | python | def device_info(self):
"""Information to be pulled into controller info.
The latest serial, model, and build_info are included. Additional info
can be added via `add_device_info`.
"""
info = {
'serial': self.serial,
'model': self.model,
'build_info': self.build_info,
'user_added_info': self._user_added_device_info
}
return info | [
"def",
"device_info",
"(",
"self",
")",
":",
"info",
"=",
"{",
"'serial'",
":",
"self",
".",
"serial",
",",
"'model'",
":",
"self",
".",
"model",
",",
"'build_info'",
":",
"self",
".",
"build_info",
",",
"'user_added_info'",
":",
"self",
".",
"_user_adde... | Information to be pulled into controller info.
The latest serial, model, and build_info are included. Additional info
can be added via `add_device_info`. | [
"Information",
"to",
"be",
"pulled",
"into",
"controller",
"info",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L469-L481 | train | 205,375 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.debug_tag | def debug_tag(self, tag):
"""Setter for the debug tag.
By default, the tag is the serial of the device, but sometimes it may
be more descriptive to use a different tag of the user's choice.
Changing debug tag changes part of the prefix of debug info emitted by
this object, like log lines and the message of DeviceError.
Example:
By default, the device's serial number is used:
'INFO [AndroidDevice|abcdefg12345] One pending call ringing.'
The tag can be customized with `ad.debug_tag = 'Caller'`:
'INFO [AndroidDevice|Caller] One pending call ringing.'
"""
self.log.info('Logging debug tag set to "%s"', tag)
self._debug_tag = tag
self.log.extra['tag'] = tag | python | def debug_tag(self, tag):
"""Setter for the debug tag.
By default, the tag is the serial of the device, but sometimes it may
be more descriptive to use a different tag of the user's choice.
Changing debug tag changes part of the prefix of debug info emitted by
this object, like log lines and the message of DeviceError.
Example:
By default, the device's serial number is used:
'INFO [AndroidDevice|abcdefg12345] One pending call ringing.'
The tag can be customized with `ad.debug_tag = 'Caller'`:
'INFO [AndroidDevice|Caller] One pending call ringing.'
"""
self.log.info('Logging debug tag set to "%s"', tag)
self._debug_tag = tag
self.log.extra['tag'] = tag | [
"def",
"debug_tag",
"(",
"self",
",",
"tag",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Logging debug tag set to \"%s\"'",
",",
"tag",
")",
"self",
".",
"_debug_tag",
"=",
"tag",
"self",
".",
"log",
".",
"extra",
"[",
"'tag'",
"]",
"=",
"tag"
] | Setter for the debug tag.
By default, the tag is the serial of the device, but sometimes it may
be more descriptive to use a different tag of the user's choice.
Changing debug tag changes part of the prefix of debug info emitted by
this object, like log lines and the message of DeviceError.
Example:
By default, the device's serial number is used:
'INFO [AndroidDevice|abcdefg12345] One pending call ringing.'
The tag can be customized with `ad.debug_tag = 'Caller'`:
'INFO [AndroidDevice|Caller] One pending call ringing.' | [
"Setter",
"for",
"the",
"debug",
"tag",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L527-L544 | train | 205,376 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.log_path | def log_path(self, new_path):
"""Setter for `log_path`, use with caution."""
if self.has_active_service:
raise DeviceError(
self,
'Cannot change `log_path` when there is service running.')
old_path = self._log_path
if new_path == old_path:
return
if os.listdir(new_path):
raise DeviceError(
self, 'Logs already exist at %s, cannot override.' % new_path)
if os.path.exists(old_path):
# Remove new path so copytree doesn't complain.
shutil.rmtree(new_path, ignore_errors=True)
shutil.copytree(old_path, new_path)
shutil.rmtree(old_path, ignore_errors=True)
self._log_path = new_path | python | def log_path(self, new_path):
"""Setter for `log_path`, use with caution."""
if self.has_active_service:
raise DeviceError(
self,
'Cannot change `log_path` when there is service running.')
old_path = self._log_path
if new_path == old_path:
return
if os.listdir(new_path):
raise DeviceError(
self, 'Logs already exist at %s, cannot override.' % new_path)
if os.path.exists(old_path):
# Remove new path so copytree doesn't complain.
shutil.rmtree(new_path, ignore_errors=True)
shutil.copytree(old_path, new_path)
shutil.rmtree(old_path, ignore_errors=True)
self._log_path = new_path | [
"def",
"log_path",
"(",
"self",
",",
"new_path",
")",
":",
"if",
"self",
".",
"has_active_service",
":",
"raise",
"DeviceError",
"(",
"self",
",",
"'Cannot change `log_path` when there is service running.'",
")",
"old_path",
"=",
"self",
".",
"_log_path",
"if",
"n... | Setter for `log_path`, use with caution. | [
"Setter",
"for",
"log_path",
"use",
"with",
"caution",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L561-L578 | train | 205,377 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.update_serial | def update_serial(self, new_serial):
"""Updates the serial number of a device.
The "serial number" used with adb's `-s` arg is not necessarily the
actual serial number. For remote devices, it could be a combination of
host names and port numbers.
This is used for when such identifier of remote devices changes during
a test. For example, when a remote device reboots, it may come back
with a different serial number.
This is NOT meant for switching the object to represent another device.
We intentionally did not make it a regular setter of the serial
property so people don't accidentally call this without understanding
the consequences.
Args:
new_serial: string, the new serial number for the same device.
Raises:
DeviceError: tries to update serial when any service is running.
"""
new_serial = str(new_serial)
if self.has_active_service:
raise DeviceError(
self,
'Cannot change device serial number when there is service running.'
)
if self._debug_tag == self.serial:
self._debug_tag = new_serial
self._serial = new_serial
self.adb.serial = new_serial
self.fastboot.serial = new_serial | python | def update_serial(self, new_serial):
"""Updates the serial number of a device.
The "serial number" used with adb's `-s` arg is not necessarily the
actual serial number. For remote devices, it could be a combination of
host names and port numbers.
This is used for when such identifier of remote devices changes during
a test. For example, when a remote device reboots, it may come back
with a different serial number.
This is NOT meant for switching the object to represent another device.
We intentionally did not make it a regular setter of the serial
property so people don't accidentally call this without understanding
the consequences.
Args:
new_serial: string, the new serial number for the same device.
Raises:
DeviceError: tries to update serial when any service is running.
"""
new_serial = str(new_serial)
if self.has_active_service:
raise DeviceError(
self,
'Cannot change device serial number when there is service running.'
)
if self._debug_tag == self.serial:
self._debug_tag = new_serial
self._serial = new_serial
self.adb.serial = new_serial
self.fastboot.serial = new_serial | [
"def",
"update_serial",
"(",
"self",
",",
"new_serial",
")",
":",
"new_serial",
"=",
"str",
"(",
"new_serial",
")",
"if",
"self",
".",
"has_active_service",
":",
"raise",
"DeviceError",
"(",
"self",
",",
"'Cannot change device serial number when there is service runni... | Updates the serial number of a device.
The "serial number" used with adb's `-s` arg is not necessarily the
actual serial number. For remote devices, it could be a combination of
host names and port numbers.
This is used for when such identifier of remote devices changes during
a test. For example, when a remote device reboots, it may come back
with a different serial number.
This is NOT meant for switching the object to represent another device.
We intentionally did not make it a regular setter of the serial
property so people don't accidentally call this without understanding
the consequences.
Args:
new_serial: string, the new serial number for the same device.
Raises:
DeviceError: tries to update serial when any service is running. | [
"Updates",
"the",
"serial",
"number",
"of",
"a",
"device",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L589-L622 | train | 205,378 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.handle_reboot | def handle_reboot(self):
"""Properly manage the service life cycle when the device needs to
temporarily disconnect.
The device can temporarily lose adb connection due to user-triggered
reboot. Use this function to make sure the services
started by Mobly are properly stopped and restored afterwards.
For sample usage, see self.reboot().
"""
self.services.stop_all()
try:
yield
finally:
self.wait_for_boot_completion()
if self.is_rootable:
self.root_adb()
self.services.start_all() | python | def handle_reboot(self):
"""Properly manage the service life cycle when the device needs to
temporarily disconnect.
The device can temporarily lose adb connection due to user-triggered
reboot. Use this function to make sure the services
started by Mobly are properly stopped and restored afterwards.
For sample usage, see self.reboot().
"""
self.services.stop_all()
try:
yield
finally:
self.wait_for_boot_completion()
if self.is_rootable:
self.root_adb()
self.services.start_all() | [
"def",
"handle_reboot",
"(",
"self",
")",
":",
"self",
".",
"services",
".",
"stop_all",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"wait_for_boot_completion",
"(",
")",
"if",
"self",
".",
"is_rootable",
":",
"self",
".",
"root_adb",
"("... | Properly manage the service life cycle when the device needs to
temporarily disconnect.
The device can temporarily lose adb connection due to user-triggered
reboot. Use this function to make sure the services
started by Mobly are properly stopped and restored afterwards.
For sample usage, see self.reboot(). | [
"Properly",
"manage",
"the",
"service",
"life",
"cycle",
"when",
"the",
"device",
"needs",
"to",
"temporarily",
"disconnect",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L625-L642 | train | 205,379 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.build_info | def build_info(self):
"""Get the build info of this Android device, including build id and
build type.
This is not available if the device is in bootloader mode.
Returns:
A dict with the build info of this Android device, or None if the
device is in bootloader mode.
"""
if self.is_bootloader:
self.log.error('Device is in fastboot mode, could not get build '
'info.')
return
info = {}
info['build_id'] = self.adb.getprop('ro.build.id')
info['build_type'] = self.adb.getprop('ro.build.type')
return info | python | def build_info(self):
"""Get the build info of this Android device, including build id and
build type.
This is not available if the device is in bootloader mode.
Returns:
A dict with the build info of this Android device, or None if the
device is in bootloader mode.
"""
if self.is_bootloader:
self.log.error('Device is in fastboot mode, could not get build '
'info.')
return
info = {}
info['build_id'] = self.adb.getprop('ro.build.id')
info['build_type'] = self.adb.getprop('ro.build.type')
return info | [
"def",
"build_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_bootloader",
":",
"self",
".",
"log",
".",
"error",
"(",
"'Device is in fastboot mode, could not get build '",
"'info.'",
")",
"return",
"info",
"=",
"{",
"}",
"info",
"[",
"'build_id'",
"]",
... | Get the build info of this Android device, including build id and
build type.
This is not available if the device is in bootloader mode.
Returns:
A dict with the build info of this Android device, or None if the
device is in bootloader mode. | [
"Get",
"the",
"build",
"info",
"of",
"this",
"Android",
"device",
"including",
"build",
"id",
"and",
"build",
"type",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L698-L715 | train | 205,380 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.is_adb_root | def is_adb_root(self):
"""True if adb is running as root for this device.
"""
try:
return '0' == self.adb.shell('id -u').decode('utf-8').strip()
except adb.AdbError:
# Wait a bit and retry to work around adb flakiness for this cmd.
time.sleep(0.2)
return '0' == self.adb.shell('id -u').decode('utf-8').strip() | python | def is_adb_root(self):
"""True if adb is running as root for this device.
"""
try:
return '0' == self.adb.shell('id -u').decode('utf-8').strip()
except adb.AdbError:
# Wait a bit and retry to work around adb flakiness for this cmd.
time.sleep(0.2)
return '0' == self.adb.shell('id -u').decode('utf-8').strip() | [
"def",
"is_adb_root",
"(",
"self",
")",
":",
"try",
":",
"return",
"'0'",
"==",
"self",
".",
"adb",
".",
"shell",
"(",
"'id -u'",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
"except",
"adb",
".",
"AdbError",
":",
"# Wait a bit an... | True if adb is running as root for this device. | [
"True",
"if",
"adb",
"is",
"running",
"as",
"root",
"for",
"this",
"device",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L724-L732 | train | 205,381 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.model | def model(self):
"""The Android code name for the device.
"""
# If device is in bootloader mode, get mode name from fastboot.
if self.is_bootloader:
out = self.fastboot.getvar('product').strip()
# 'out' is never empty because of the 'total time' message fastboot
# writes to stderr.
lines = out.decode('utf-8').split('\n', 1)
if lines:
tokens = lines[0].split(' ')
if len(tokens) > 1:
return tokens[1].lower()
return None
model = self.adb.getprop('ro.build.product').lower()
if model == 'sprout':
return model
return self.adb.getprop('ro.product.name').lower() | python | def model(self):
"""The Android code name for the device.
"""
# If device is in bootloader mode, get mode name from fastboot.
if self.is_bootloader:
out = self.fastboot.getvar('product').strip()
# 'out' is never empty because of the 'total time' message fastboot
# writes to stderr.
lines = out.decode('utf-8').split('\n', 1)
if lines:
tokens = lines[0].split(' ')
if len(tokens) > 1:
return tokens[1].lower()
return None
model = self.adb.getprop('ro.build.product').lower()
if model == 'sprout':
return model
return self.adb.getprop('ro.product.name').lower() | [
"def",
"model",
"(",
"self",
")",
":",
"# If device is in bootloader mode, get mode name from fastboot.",
"if",
"self",
".",
"is_bootloader",
":",
"out",
"=",
"self",
".",
"fastboot",
".",
"getvar",
"(",
"'product'",
")",
".",
"strip",
"(",
")",
"# 'out' is never ... | The Android code name for the device. | [
"The",
"Android",
"code",
"name",
"for",
"the",
"device",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L739-L756 | train | 205,382 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.load_config | def load_config(self, config):
"""Add attributes to the AndroidDevice object based on config.
Args:
config: A dictionary representing the configs.
Raises:
Error: The config is trying to overwrite an existing attribute.
"""
for k, v in config.items():
if hasattr(self, k):
raise DeviceError(
self,
('Attribute %s already exists with value %s, cannot set '
'again.') % (k, getattr(self, k)))
setattr(self, k, v) | python | def load_config(self, config):
"""Add attributes to the AndroidDevice object based on config.
Args:
config: A dictionary representing the configs.
Raises:
Error: The config is trying to overwrite an existing attribute.
"""
for k, v in config.items():
if hasattr(self, k):
raise DeviceError(
self,
('Attribute %s already exists with value %s, cannot set '
'again.') % (k, getattr(self, k)))
setattr(self, k, v) | [
"def",
"load_config",
"(",
"self",
",",
"config",
")",
":",
"for",
"k",
",",
"v",
"in",
"config",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"k",
")",
":",
"raise",
"DeviceError",
"(",
"self",
",",
"(",
"'Attribute %s already exi... | Add attributes to the AndroidDevice object based on config.
Args:
config: A dictionary representing the configs.
Raises:
Error: The config is trying to overwrite an existing attribute. | [
"Add",
"attributes",
"to",
"the",
"AndroidDevice",
"object",
"based",
"on",
"config",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L758-L773 | train | 205,383 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.root_adb | def root_adb(self):
"""Change adb to root mode for this device if allowed.
If executed on a production build, adb will not be switched to root
mode per security restrictions.
"""
self.adb.root()
self.adb.wait_for_device(
timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND) | python | def root_adb(self):
"""Change adb to root mode for this device if allowed.
If executed on a production build, adb will not be switched to root
mode per security restrictions.
"""
self.adb.root()
self.adb.wait_for_device(
timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND) | [
"def",
"root_adb",
"(",
"self",
")",
":",
"self",
".",
"adb",
".",
"root",
"(",
")",
"self",
".",
"adb",
".",
"wait_for_device",
"(",
"timeout",
"=",
"DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND",
")"
] | Change adb to root mode for this device if allowed.
If executed on a production build, adb will not be switched to root
mode per security restrictions. | [
"Change",
"adb",
"to",
"root",
"mode",
"for",
"this",
"device",
"if",
"allowed",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L775-L783 | train | 205,384 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.load_snippet | def load_snippet(self, name, package):
"""Starts the snippet apk with the given package name and connects.
Examples:
.. code-block:: python
ad.load_snippet(
name='maps', package='com.google.maps.snippets')
ad.maps.activateZoom('3')
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.
Raises:
SnippetError: Illegal load operations are attempted.
"""
# Should not load snippet with an existing attribute.
if hasattr(self, name):
raise SnippetError(
self,
'Attribute "%s" already exists, please use a different name.' %
name)
self.services.snippets.add_snippet_client(name, package) | python | def load_snippet(self, name, package):
"""Starts the snippet apk with the given package name and connects.
Examples:
.. code-block:: python
ad.load_snippet(
name='maps', package='com.google.maps.snippets')
ad.maps.activateZoom('3')
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.
Raises:
SnippetError: Illegal load operations are attempted.
"""
# Should not load snippet with an existing attribute.
if hasattr(self, name):
raise SnippetError(
self,
'Attribute "%s" already exists, please use a different name.' %
name)
self.services.snippets.add_snippet_client(name, package) | [
"def",
"load_snippet",
"(",
"self",
",",
"name",
",",
"package",
")",
":",
"# Should not load snippet with an existing attribute.",
"if",
"hasattr",
"(",
"self",
",",
"name",
")",
":",
"raise",
"SnippetError",
"(",
"self",
",",
"'Attribute \"%s\" already exists, pleas... | Starts the snippet apk with the given package name and connects.
Examples:
.. code-block:: python
ad.load_snippet(
name='maps', package='com.google.maps.snippets')
ad.maps.activateZoom('3')
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.
Raises:
SnippetError: Illegal load operations are attempted. | [
"Starts",
"the",
"snippet",
"apk",
"with",
"the",
"given",
"package",
"name",
"and",
"connects",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L785-L811 | train | 205,385 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.take_bug_report | def take_bug_report(self,
test_name,
begin_time,
timeout=300,
destination=None):
"""Takes a bug report on the device and stores it in a file.
Args:
test_name: Name of the test method that triggered this bug report.
begin_time: Timestamp of when the test started.
timeout: float, the number of seconds to wait for bugreport to
complete, default is 5min.
destination: string, path to the directory where the bugreport
should be saved.
"""
new_br = True
try:
stdout = self.adb.shell('bugreportz -v').decode('utf-8')
# This check is necessary for builds before N, where adb shell's ret
# code and stderr are not propagated properly.
if 'not found' in stdout:
new_br = False
except adb.AdbError:
new_br = False
if destination:
br_path = utils.abs_path(destination)
else:
br_path = os.path.join(self.log_path, 'BugReports')
utils.create_dir(br_path)
base_name = ',%s,%s.txt' % (begin_time, self._normalized_serial)
if new_br:
base_name = base_name.replace('.txt', '.zip')
test_name_len = utils.MAX_FILENAME_LEN - len(base_name)
out_name = test_name[:test_name_len] + base_name
full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ '))
# in case device restarted, wait for adb interface to return
self.wait_for_boot_completion()
self.log.info('Taking bugreport for %s.', test_name)
if new_br:
out = self.adb.shell('bugreportz', timeout=timeout).decode('utf-8')
if not out.startswith('OK'):
raise DeviceError(self, 'Failed to take bugreport: %s' % out)
br_out_path = out.split(':')[1].strip()
self.adb.pull([br_out_path, full_out_path])
else:
# shell=True as this command redirects the stdout to a local file
# using shell redirection.
self.adb.bugreport(
' > "%s"' % full_out_path, shell=True, timeout=timeout)
self.log.info('Bugreport for %s taken at %s.', test_name,
full_out_path) | python | def take_bug_report(self,
test_name,
begin_time,
timeout=300,
destination=None):
"""Takes a bug report on the device and stores it in a file.
Args:
test_name: Name of the test method that triggered this bug report.
begin_time: Timestamp of when the test started.
timeout: float, the number of seconds to wait for bugreport to
complete, default is 5min.
destination: string, path to the directory where the bugreport
should be saved.
"""
new_br = True
try:
stdout = self.adb.shell('bugreportz -v').decode('utf-8')
# This check is necessary for builds before N, where adb shell's ret
# code and stderr are not propagated properly.
if 'not found' in stdout:
new_br = False
except adb.AdbError:
new_br = False
if destination:
br_path = utils.abs_path(destination)
else:
br_path = os.path.join(self.log_path, 'BugReports')
utils.create_dir(br_path)
base_name = ',%s,%s.txt' % (begin_time, self._normalized_serial)
if new_br:
base_name = base_name.replace('.txt', '.zip')
test_name_len = utils.MAX_FILENAME_LEN - len(base_name)
out_name = test_name[:test_name_len] + base_name
full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ '))
# in case device restarted, wait for adb interface to return
self.wait_for_boot_completion()
self.log.info('Taking bugreport for %s.', test_name)
if new_br:
out = self.adb.shell('bugreportz', timeout=timeout).decode('utf-8')
if not out.startswith('OK'):
raise DeviceError(self, 'Failed to take bugreport: %s' % out)
br_out_path = out.split(':')[1].strip()
self.adb.pull([br_out_path, full_out_path])
else:
# shell=True as this command redirects the stdout to a local file
# using shell redirection.
self.adb.bugreport(
' > "%s"' % full_out_path, shell=True, timeout=timeout)
self.log.info('Bugreport for %s taken at %s.', test_name,
full_out_path) | [
"def",
"take_bug_report",
"(",
"self",
",",
"test_name",
",",
"begin_time",
",",
"timeout",
"=",
"300",
",",
"destination",
"=",
"None",
")",
":",
"new_br",
"=",
"True",
"try",
":",
"stdout",
"=",
"self",
".",
"adb",
".",
"shell",
"(",
"'bugreportz -v'",... | Takes a bug report on the device and stores it in a file.
Args:
test_name: Name of the test method that triggered this bug report.
begin_time: Timestamp of when the test started.
timeout: float, the number of seconds to wait for bugreport to
complete, default is 5min.
destination: string, path to the directory where the bugreport
should be saved. | [
"Takes",
"a",
"bug",
"report",
"on",
"the",
"device",
"and",
"stores",
"it",
"in",
"a",
"file",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L824-L874 | train | 205,386 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.run_iperf_client | def run_iperf_client(self, server_host, extra_args=''):
"""Start iperf client on the device.
Return status as true if iperf client start successfully.
And data flow information as results.
Args:
server_host: Address of the iperf server.
extra_args: A string representing extra arguments for iperf client,
e.g. '-i 1 -t 30'.
Returns:
status: true if iperf client start successfully.
results: results have data flow information
"""
out = self.adb.shell('iperf3 -c %s %s' % (server_host, extra_args))
clean_out = new_str(out, 'utf-8').strip().split('\n')
if 'error' in clean_out[0].lower():
return False, clean_out
return True, clean_out | python | def run_iperf_client(self, server_host, extra_args=''):
"""Start iperf client on the device.
Return status as true if iperf client start successfully.
And data flow information as results.
Args:
server_host: Address of the iperf server.
extra_args: A string representing extra arguments for iperf client,
e.g. '-i 1 -t 30'.
Returns:
status: true if iperf client start successfully.
results: results have data flow information
"""
out = self.adb.shell('iperf3 -c %s %s' % (server_host, extra_args))
clean_out = new_str(out, 'utf-8').strip().split('\n')
if 'error' in clean_out[0].lower():
return False, clean_out
return True, clean_out | [
"def",
"run_iperf_client",
"(",
"self",
",",
"server_host",
",",
"extra_args",
"=",
"''",
")",
":",
"out",
"=",
"self",
".",
"adb",
".",
"shell",
"(",
"'iperf3 -c %s %s'",
"%",
"(",
"server_host",
",",
"extra_args",
")",
")",
"clean_out",
"=",
"new_str",
... | Start iperf client on the device.
Return status as true if iperf client start successfully.
And data flow information as results.
Args:
server_host: Address of the iperf server.
extra_args: A string representing extra arguments for iperf client,
e.g. '-i 1 -t 30'.
Returns:
status: true if iperf client start successfully.
results: results have data flow information | [
"Start",
"iperf",
"client",
"on",
"the",
"device",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L876-L895 | train | 205,387 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.wait_for_boot_completion | def wait_for_boot_completion(
self, timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND):
"""Waits for Android framework to broadcast ACTION_BOOT_COMPLETED.
This function times out after 15 minutes.
Args:
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect.
"""
timeout_start = time.time()
self.adb.wait_for_device(timeout=timeout)
while time.time() < timeout_start + timeout:
try:
if self.is_boot_completed():
return
except adb.AdbError:
# adb shell calls may fail during certain period of booting
# process, which is normal. Ignoring these errors.
pass
time.sleep(5)
raise DeviceError(self, 'Booting process timed out') | python | def wait_for_boot_completion(
self, timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND):
"""Waits for Android framework to broadcast ACTION_BOOT_COMPLETED.
This function times out after 15 minutes.
Args:
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect.
"""
timeout_start = time.time()
self.adb.wait_for_device(timeout=timeout)
while time.time() < timeout_start + timeout:
try:
if self.is_boot_completed():
return
except adb.AdbError:
# adb shell calls may fail during certain period of booting
# process, which is normal. Ignoring these errors.
pass
time.sleep(5)
raise DeviceError(self, 'Booting process timed out') | [
"def",
"wait_for_boot_completion",
"(",
"self",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND",
")",
":",
"timeout_start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"adb",
".",
"wait_for_device",
"(",
"timeout",
"=",
"timeout",
")",
"while"... | Waits for Android framework to broadcast ACTION_BOOT_COMPLETED.
This function times out after 15 minutes.
Args:
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect. | [
"Waits",
"for",
"Android",
"framework",
"to",
"broadcast",
"ACTION_BOOT_COMPLETED",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L897-L919 | train | 205,388 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.is_boot_completed | def is_boot_completed(self):
"""Checks if device boot is completed by verifying system property."""
completed = self.adb.getprop('sys.boot_completed')
if completed == '1':
self.log.debug('Device boot completed.')
return True
return False | python | def is_boot_completed(self):
"""Checks if device boot is completed by verifying system property."""
completed = self.adb.getprop('sys.boot_completed')
if completed == '1':
self.log.debug('Device boot completed.')
return True
return False | [
"def",
"is_boot_completed",
"(",
"self",
")",
":",
"completed",
"=",
"self",
".",
"adb",
".",
"getprop",
"(",
"'sys.boot_completed'",
")",
"if",
"completed",
"==",
"'1'",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Device boot completed.'",
")",
"return",
... | Checks if device boot is completed by verifying system property. | [
"Checks",
"if",
"device",
"boot",
"is",
"completed",
"by",
"verifying",
"system",
"property",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L921-L927 | train | 205,389 |
google/mobly | mobly/controllers/android_device.py | AndroidDevice.is_adb_detectable | def is_adb_detectable(self):
"""Checks if USB is on and device is ready by verifying adb devices."""
serials = list_adb_devices()
if self.serial in serials:
self.log.debug('Is now adb detectable.')
return True
return False | python | def is_adb_detectable(self):
"""Checks if USB is on and device is ready by verifying adb devices."""
serials = list_adb_devices()
if self.serial in serials:
self.log.debug('Is now adb detectable.')
return True
return False | [
"def",
"is_adb_detectable",
"(",
"self",
")",
":",
"serials",
"=",
"list_adb_devices",
"(",
")",
"if",
"self",
".",
"serial",
"in",
"serials",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Is now adb detectable.'",
")",
"return",
"True",
"return",
"False"
] | Checks if USB is on and device is ready by verifying adb devices. | [
"Checks",
"if",
"USB",
"is",
"on",
"and",
"device",
"is",
"ready",
"by",
"verifying",
"adb",
"devices",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L929-L935 | train | 205,390 |
google/mobly | mobly/expects.py | expect_true | def expect_true(condition, msg, extras=None):
"""Expects an expression evaluates to True.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in test
result.
"""
try:
asserts.assert_true(condition, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected a `True` value, got `False`.')
recorder.add_error(e) | python | def expect_true(condition, msg, extras=None):
"""Expects an expression evaluates to True.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in test
result.
"""
try:
asserts.assert_true(condition, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected a `True` value, got `False`.')
recorder.add_error(e) | [
"def",
"expect_true",
"(",
"condition",
",",
"msg",
",",
"extras",
"=",
"None",
")",
":",
"try",
":",
"asserts",
".",
"assert_true",
"(",
"condition",
",",
"msg",
",",
"extras",
")",
"except",
"signals",
".",
"TestSignal",
"as",
"e",
":",
"logging",
".... | Expects an expression evaluates to True.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in test
result. | [
"Expects",
"an",
"expression",
"evaluates",
"to",
"True",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/expects.py#L68-L84 | train | 205,391 |
google/mobly | mobly/expects.py | expect_false | def expect_false(condition, msg, extras=None):
"""Expects an expression evaluates to False.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in test
result.
"""
try:
asserts.assert_false(condition, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected a `False` value, got `True`.')
recorder.add_error(e) | python | def expect_false(condition, msg, extras=None):
"""Expects an expression evaluates to False.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in test
result.
"""
try:
asserts.assert_false(condition, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected a `False` value, got `True`.')
recorder.add_error(e) | [
"def",
"expect_false",
"(",
"condition",
",",
"msg",
",",
"extras",
"=",
"None",
")",
":",
"try",
":",
"asserts",
".",
"assert_false",
"(",
"condition",
",",
"msg",
",",
"extras",
")",
"except",
"signals",
".",
"TestSignal",
"as",
"e",
":",
"logging",
... | Expects an expression evaluates to False.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in test
result. | [
"Expects",
"an",
"expression",
"evaluates",
"to",
"False",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/expects.py#L87-L103 | train | 205,392 |
google/mobly | mobly/expects.py | expect_equal | def expect_equal(first, second, msg=None, extras=None):
"""Expects the equality of objects, otherwise fail the test.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info about the failure.
extras: An optional field for extra information to be included in test
result.
"""
try:
asserts.assert_equal(first, second, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected %s equals to %s, but they are not.', first,
second)
recorder.add_error(e) | python | def expect_equal(first, second, msg=None, extras=None):
"""Expects the equality of objects, otherwise fail the test.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info about the failure.
extras: An optional field for extra information to be included in test
result.
"""
try:
asserts.assert_equal(first, second, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected %s equals to %s, but they are not.', first,
second)
recorder.add_error(e) | [
"def",
"expect_equal",
"(",
"first",
",",
"second",
",",
"msg",
"=",
"None",
",",
"extras",
"=",
"None",
")",
":",
"try",
":",
"asserts",
".",
"assert_equal",
"(",
"first",
",",
"second",
",",
"msg",
",",
"extras",
")",
"except",
"signals",
".",
"Tes... | Expects the equality of objects, otherwise fail the test.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info about the failure.
extras: An optional field for extra information to be included in test
result. | [
"Expects",
"the",
"equality",
"of",
"objects",
"otherwise",
"fail",
"the",
"test",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/expects.py#L106-L127 | train | 205,393 |
google/mobly | mobly/expects.py | expect_no_raises | def expect_no_raises(message=None, extras=None):
"""Expects no exception is raised in a context.
If the expectation is not met, the test is marked as fail after its
execution finishes.
A default message is added to the exception `details`.
Args:
message: string, custom message to add to exception's `details`.
extras: An optional field for extra information to be included in test
result.
"""
try:
yield
except Exception as e:
e_record = records.ExceptionRecord(e)
if extras:
e_record.extras = extras
msg = message or 'Got an unexpected exception'
details = '%s: %s' % (msg, e_record.details)
logging.exception(details)
e_record.details = details
recorder.add_error(e_record) | python | def expect_no_raises(message=None, extras=None):
"""Expects no exception is raised in a context.
If the expectation is not met, the test is marked as fail after its
execution finishes.
A default message is added to the exception `details`.
Args:
message: string, custom message to add to exception's `details`.
extras: An optional field for extra information to be included in test
result.
"""
try:
yield
except Exception as e:
e_record = records.ExceptionRecord(e)
if extras:
e_record.extras = extras
msg = message or 'Got an unexpected exception'
details = '%s: %s' % (msg, e_record.details)
logging.exception(details)
e_record.details = details
recorder.add_error(e_record) | [
"def",
"expect_no_raises",
"(",
"message",
"=",
"None",
",",
"extras",
"=",
"None",
")",
":",
"try",
":",
"yield",
"except",
"Exception",
"as",
"e",
":",
"e_record",
"=",
"records",
".",
"ExceptionRecord",
"(",
"e",
")",
"if",
"extras",
":",
"e_record",
... | Expects no exception is raised in a context.
If the expectation is not met, the test is marked as fail after its
execution finishes.
A default message is added to the exception `details`.
Args:
message: string, custom message to add to exception's `details`.
extras: An optional field for extra information to be included in test
result. | [
"Expects",
"no",
"exception",
"is",
"raised",
"in",
"a",
"context",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/expects.py#L131-L154 | train | 205,394 |
google/mobly | mobly/expects.py | _ExpectErrorRecorder.reset_internal_states | def reset_internal_states(self, record=None):
"""Resets the internal state of the recorder.
Args:
record: records.TestResultRecord, the test record for a test.
"""
self._record = None
self._count = 0
self._record = record | python | def reset_internal_states(self, record=None):
"""Resets the internal state of the recorder.
Args:
record: records.TestResultRecord, the test record for a test.
"""
self._record = None
self._count = 0
self._record = record | [
"def",
"reset_internal_states",
"(",
"self",
",",
"record",
"=",
"None",
")",
":",
"self",
".",
"_record",
"=",
"None",
"self",
".",
"_count",
"=",
"0",
"self",
".",
"_record",
"=",
"record"
] | Resets the internal state of the recorder.
Args:
record: records.TestResultRecord, the test record for a test. | [
"Resets",
"the",
"internal",
"state",
"of",
"the",
"recorder",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/expects.py#L34-L42 | train | 205,395 |
google/mobly | mobly/expects.py | _ExpectErrorRecorder.add_error | def add_error(self, error):
"""Record an error from expect APIs.
This method generates a position stamp for the expect. The stamp is
composed of a timestamp and the number of errors recorded so far.
Args:
error: Exception or signals.ExceptionRecord, the error to add.
"""
self._count += 1
self._record.add_error('expect@%s+%s' % (time.time(), self._count),
error) | python | def add_error(self, error):
"""Record an error from expect APIs.
This method generates a position stamp for the expect. The stamp is
composed of a timestamp and the number of errors recorded so far.
Args:
error: Exception or signals.ExceptionRecord, the error to add.
"""
self._count += 1
self._record.add_error('expect@%s+%s' % (time.time(), self._count),
error) | [
"def",
"add_error",
"(",
"self",
",",
"error",
")",
":",
"self",
".",
"_count",
"+=",
"1",
"self",
".",
"_record",
".",
"add_error",
"(",
"'expect@%s+%s'",
"%",
"(",
"time",
".",
"time",
"(",
")",
",",
"self",
".",
"_count",
")",
",",
"error",
")"
... | Record an error from expect APIs.
This method generates a position stamp for the expect. The stamp is
composed of a timestamp and the number of errors recorded so far.
Args:
error: Exception or signals.ExceptionRecord, the error to add. | [
"Record",
"an",
"error",
"from",
"expect",
"APIs",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/expects.py#L54-L65 | train | 205,396 |
google/mobly | mobly/controllers/android_device_lib/services/logcat.py | Logcat._enable_logpersist | def _enable_logpersist(self):
"""Attempts to enable logpersist daemon to persist logs."""
# Logpersist is only allowed on rootable devices because of excessive
# reads/writes for persisting logs.
if not self._ad.is_rootable:
return
logpersist_warning = ('%s encountered an error enabling persistent'
' logs, logs may not get saved.')
# Android L and older versions do not have logpersist installed,
# so check that the logpersist scripts exists before trying to use
# them.
if not self._ad.adb.has_shell_command('logpersist.start'):
logging.warning(logpersist_warning, self)
return
try:
# Disable adb log spam filter for rootable devices. Have to stop
# and clear settings first because 'start' doesn't support --clear
# option before Android N.
self._ad.adb.shell('logpersist.stop --clear')
self._ad.adb.shell('logpersist.start')
except adb.AdbError:
logging.warning(logpersist_warning, self) | python | def _enable_logpersist(self):
"""Attempts to enable logpersist daemon to persist logs."""
# Logpersist is only allowed on rootable devices because of excessive
# reads/writes for persisting logs.
if not self._ad.is_rootable:
return
logpersist_warning = ('%s encountered an error enabling persistent'
' logs, logs may not get saved.')
# Android L and older versions do not have logpersist installed,
# so check that the logpersist scripts exists before trying to use
# them.
if not self._ad.adb.has_shell_command('logpersist.start'):
logging.warning(logpersist_warning, self)
return
try:
# Disable adb log spam filter for rootable devices. Have to stop
# and clear settings first because 'start' doesn't support --clear
# option before Android N.
self._ad.adb.shell('logpersist.stop --clear')
self._ad.adb.shell('logpersist.start')
except adb.AdbError:
logging.warning(logpersist_warning, self) | [
"def",
"_enable_logpersist",
"(",
"self",
")",
":",
"# Logpersist is only allowed on rootable devices because of excessive",
"# reads/writes for persisting logs.",
"if",
"not",
"self",
".",
"_ad",
".",
"is_rootable",
":",
"return",
"logpersist_warning",
"=",
"(",
"'%s encount... | Attempts to enable logpersist daemon to persist logs. | [
"Attempts",
"to",
"enable",
"logpersist",
"daemon",
"to",
"persist",
"logs",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/logcat.py#L66-L89 | train | 205,397 |
google/mobly | mobly/controllers/android_device_lib/services/logcat.py | Logcat.clear_adb_log | def clear_adb_log(self):
"""Clears cached adb content."""
try:
self._ad.adb.logcat('-c')
except adb.AdbError as e:
# On Android O, the clear command fails due to a known bug.
# Catching this so we don't crash from this Android issue.
if b'failed to clear' in e.stderr:
self._ad.log.warning(
'Encountered known Android error to clear logcat.')
else:
raise | python | def clear_adb_log(self):
"""Clears cached adb content."""
try:
self._ad.adb.logcat('-c')
except adb.AdbError as e:
# On Android O, the clear command fails due to a known bug.
# Catching this so we don't crash from this Android issue.
if b'failed to clear' in e.stderr:
self._ad.log.warning(
'Encountered known Android error to clear logcat.')
else:
raise | [
"def",
"clear_adb_log",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_ad",
".",
"adb",
".",
"logcat",
"(",
"'-c'",
")",
"except",
"adb",
".",
"AdbError",
"as",
"e",
":",
"# On Android O, the clear command fails due to a known bug.",
"# Catching this so we don'... | Clears cached adb content. | [
"Clears",
"cached",
"adb",
"content",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/logcat.py#L120-L131 | train | 205,398 |
google/mobly | mobly/controllers/android_device_lib/services/logcat.py | Logcat.cat_adb_log | def cat_adb_log(self, tag, begin_time):
"""Takes an excerpt of the adb logcat log from a certain time point to
current time.
Args:
tag: An identifier of the time period, usualy the name of a test.
begin_time: Logline format timestamp of the beginning of the time
period.
"""
if not self.adb_logcat_file_path:
raise Error(
self._ad,
'Attempting to cat adb log when none has been collected.')
end_time = mobly_logger.get_log_line_timestamp()
self._ad.log.debug('Extracting adb log from logcat.')
adb_excerpt_path = os.path.join(self._ad.log_path, 'AdbLogExcerpts')
utils.create_dir(adb_excerpt_path)
f_name = os.path.basename(self.adb_logcat_file_path)
out_name = f_name.replace('adblog,', '').replace('.txt', '')
out_name = ',%s,%s.txt' % (begin_time, out_name)
out_name = out_name.replace(':', '-')
tag_len = utils.MAX_FILENAME_LEN - len(out_name)
tag = tag[:tag_len]
out_name = tag + out_name
full_adblog_path = os.path.join(adb_excerpt_path, out_name)
with io.open(full_adblog_path, 'w', encoding='utf-8') as out:
in_file = self.adb_logcat_file_path
with io.open(
in_file, 'r', encoding='utf-8', errors='replace') as f:
in_range = False
while True:
line = None
try:
line = f.readline()
if not line:
break
except:
continue
line_time = line[:mobly_logger.log_line_timestamp_len]
if not mobly_logger.is_valid_logline_timestamp(line_time):
continue
if self._is_timestamp_in_range(line_time, begin_time,
end_time):
in_range = True
if not line.endswith('\n'):
line += '\n'
out.write(line)
else:
if in_range:
break | python | def cat_adb_log(self, tag, begin_time):
"""Takes an excerpt of the adb logcat log from a certain time point to
current time.
Args:
tag: An identifier of the time period, usualy the name of a test.
begin_time: Logline format timestamp of the beginning of the time
period.
"""
if not self.adb_logcat_file_path:
raise Error(
self._ad,
'Attempting to cat adb log when none has been collected.')
end_time = mobly_logger.get_log_line_timestamp()
self._ad.log.debug('Extracting adb log from logcat.')
adb_excerpt_path = os.path.join(self._ad.log_path, 'AdbLogExcerpts')
utils.create_dir(adb_excerpt_path)
f_name = os.path.basename(self.adb_logcat_file_path)
out_name = f_name.replace('adblog,', '').replace('.txt', '')
out_name = ',%s,%s.txt' % (begin_time, out_name)
out_name = out_name.replace(':', '-')
tag_len = utils.MAX_FILENAME_LEN - len(out_name)
tag = tag[:tag_len]
out_name = tag + out_name
full_adblog_path = os.path.join(adb_excerpt_path, out_name)
with io.open(full_adblog_path, 'w', encoding='utf-8') as out:
in_file = self.adb_logcat_file_path
with io.open(
in_file, 'r', encoding='utf-8', errors='replace') as f:
in_range = False
while True:
line = None
try:
line = f.readline()
if not line:
break
except:
continue
line_time = line[:mobly_logger.log_line_timestamp_len]
if not mobly_logger.is_valid_logline_timestamp(line_time):
continue
if self._is_timestamp_in_range(line_time, begin_time,
end_time):
in_range = True
if not line.endswith('\n'):
line += '\n'
out.write(line)
else:
if in_range:
break | [
"def",
"cat_adb_log",
"(",
"self",
",",
"tag",
",",
"begin_time",
")",
":",
"if",
"not",
"self",
".",
"adb_logcat_file_path",
":",
"raise",
"Error",
"(",
"self",
".",
"_ad",
",",
"'Attempting to cat adb log when none has been collected.'",
")",
"end_time",
"=",
... | Takes an excerpt of the adb logcat log from a certain time point to
current time.
Args:
tag: An identifier of the time period, usualy the name of a test.
begin_time: Logline format timestamp of the beginning of the time
period. | [
"Takes",
"an",
"excerpt",
"of",
"the",
"adb",
"logcat",
"log",
"from",
"a",
"certain",
"time",
"point",
"to",
"current",
"time",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/logcat.py#L133-L182 | train | 205,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.