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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
rgs1/zk_shell | zk_shell/acl.py | ACLReader.from_dict | def from_dict(cls, acl_dict):
""" ACL from dict """
perms = acl_dict.get("perms", Permissions.ALL)
id_dict = acl_dict.get("id", {})
id_scheme = id_dict.get("scheme", "world")
id_id = id_dict.get("id", "anyone")
return ACL(perms, Id(id_scheme, id_id)) | python | def from_dict(cls, acl_dict):
""" ACL from dict """
perms = acl_dict.get("perms", Permissions.ALL)
id_dict = acl_dict.get("id", {})
id_scheme = id_dict.get("scheme", "world")
id_id = id_dict.get("id", "anyone")
return ACL(perms, Id(id_scheme, id_id)) | [
"def",
"from_dict",
"(",
"cls",
",",
"acl_dict",
")",
":",
"perms",
"=",
"acl_dict",
".",
"get",
"(",
"\"perms\"",
",",
"Permissions",
".",
"ALL",
")",
"id_dict",
"=",
"acl_dict",
".",
"get",
"(",
"\"id\"",
",",
"{",
"}",
")",
"id_scheme",
"=",
"id_d... | ACL from dict | [
"ACL",
"from",
"dict"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/acl.py#L85-L91 | train | 213,600 |
rgs1/zk_shell | zk_shell/shell.py | connected | def connected(func):
""" check connected, fails otherwise """
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if not self.connected:
self.show_output("Not connected.")
else:
try:
return func(*args, **kwargs)
except APIError:
self.show_output("ZooKeeper internal error.")
except AuthFailedError:
self.show_output("Authentication failed.")
except NoAuthError:
self.show_output("Not authenticated.")
except BadVersionError:
self.show_output("Bad version.")
except ConnectionLoss:
self.show_output("Connection loss.")
except NotReadOnlyCallError:
self.show_output("Not a read-only operation.")
except BadArgumentsError:
self.show_output("Bad arguments.")
except SessionExpiredError:
self.show_output("Session expired.")
except UnimplementedError as ex:
self.show_output("Not implemented by the server: %s." % str(ex))
except ZookeeperError as ex:
self.show_output("Unknown ZooKeeper error: %s" % str(ex))
return wrapper | python | def connected(func):
""" check connected, fails otherwise """
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if not self.connected:
self.show_output("Not connected.")
else:
try:
return func(*args, **kwargs)
except APIError:
self.show_output("ZooKeeper internal error.")
except AuthFailedError:
self.show_output("Authentication failed.")
except NoAuthError:
self.show_output("Not authenticated.")
except BadVersionError:
self.show_output("Bad version.")
except ConnectionLoss:
self.show_output("Connection loss.")
except NotReadOnlyCallError:
self.show_output("Not a read-only operation.")
except BadArgumentsError:
self.show_output("Bad arguments.")
except SessionExpiredError:
self.show_output("Session expired.")
except UnimplementedError as ex:
self.show_output("Not implemented by the server: %s." % str(ex))
except ZookeeperError as ex:
self.show_output("Unknown ZooKeeper error: %s" % str(ex))
return wrapper | [
"def",
"connected",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"if",
"not",
"self",
".",
"connected",
":",
"self",
".",
"show... | check connected, fails otherwise | [
"check",
"connected",
"fails",
"otherwise"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L96-L127 | train | 213,601 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_add_auth | def do_add_auth(self, params):
"""
\x1b[1mNAME\x1b[0m
add_auth - Authenticates the session
\x1b[1mSYNOPSIS\x1b[0m
add_auth <scheme> <credential>
\x1b[1mEXAMPLES\x1b[0m
> add_auth digest super:s3cr3t
"""
self._zk.add_auth(params.scheme, params.credential) | python | def do_add_auth(self, params):
"""
\x1b[1mNAME\x1b[0m
add_auth - Authenticates the session
\x1b[1mSYNOPSIS\x1b[0m
add_auth <scheme> <credential>
\x1b[1mEXAMPLES\x1b[0m
> add_auth digest super:s3cr3t
"""
self._zk.add_auth(params.scheme, params.credential) | [
"def",
"do_add_auth",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"_zk",
".",
"add_auth",
"(",
"params",
".",
"scheme",
",",
"params",
".",
"credential",
")"
] | \x1b[1mNAME\x1b[0m
add_auth - Authenticates the session
\x1b[1mSYNOPSIS\x1b[0m
add_auth <scheme> <credential>
\x1b[1mEXAMPLES\x1b[0m
> add_auth digest super:s3cr3t | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"add_auth",
"-",
"Authenticates",
"the",
"session"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L305-L317 | train | 213,602 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_set_acls | def do_set_acls(self, params):
"""
\x1b[1mNAME\x1b[0m
set_acls - Sets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
set_acls <path> <acls> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recursively set the acls on the children
\x1b[1mEXAMPLES\x1b[0m
> set_acls /some/path 'world:anyone:r digest:user:aRxISyaKnTP2+OZ9OmQLkq04bvo=:cdrwa'
> set_acls /some/path 'world:anyone:r username_password:user:p@ass0rd:cdrwa'
> set_acls /path 'world:anyone:r' true
"""
try:
acls = ACLReader.extract(shlex.split(params.acls))
except ACLReader.BadACL as ex:
self.show_output("Failed to set ACLs: %s.", ex)
return
def set_acls(path):
try:
self._zk.set_acls(path, acls)
except (NoNodeError, BadVersionError, InvalidACLError, ZookeeperError) as ex:
self.show_output("Failed to set ACLs: %s. Error: %s", str(acls), str(ex))
if params.recursive:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
set_acls(cpath)
set_acls(params.path) | python | def do_set_acls(self, params):
"""
\x1b[1mNAME\x1b[0m
set_acls - Sets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
set_acls <path> <acls> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recursively set the acls on the children
\x1b[1mEXAMPLES\x1b[0m
> set_acls /some/path 'world:anyone:r digest:user:aRxISyaKnTP2+OZ9OmQLkq04bvo=:cdrwa'
> set_acls /some/path 'world:anyone:r username_password:user:p@ass0rd:cdrwa'
> set_acls /path 'world:anyone:r' true
"""
try:
acls = ACLReader.extract(shlex.split(params.acls))
except ACLReader.BadACL as ex:
self.show_output("Failed to set ACLs: %s.", ex)
return
def set_acls(path):
try:
self._zk.set_acls(path, acls)
except (NoNodeError, BadVersionError, InvalidACLError, ZookeeperError) as ex:
self.show_output("Failed to set ACLs: %s. Error: %s", str(acls), str(ex))
if params.recursive:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
set_acls(cpath)
set_acls(params.path) | [
"def",
"do_set_acls",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"acls",
"=",
"ACLReader",
".",
"extract",
"(",
"shlex",
".",
"split",
"(",
"params",
".",
"acls",
")",
")",
"except",
"ACLReader",
".",
"BadACL",
"as",
"ex",
":",
"self",
".",
... | \x1b[1mNAME\x1b[0m
set_acls - Sets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
set_acls <path> <acls> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recursively set the acls on the children
\x1b[1mEXAMPLES\x1b[0m
> set_acls /some/path 'world:anyone:r digest:user:aRxISyaKnTP2+OZ9OmQLkq04bvo=:cdrwa'
> set_acls /some/path 'world:anyone:r username_password:user:p@ass0rd:cdrwa'
> set_acls /path 'world:anyone:r' true | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"set_acls",
"-",
"Sets",
"ACLs",
"for",
"a",
"given",
"path"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L326-L359 | train | 213,603 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_get_acls | def do_get_acls(self, params):
"""
\x1b[1mNAME\x1b[0m
get_acls - Gets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
get_acls <path> [depth] [ephemerals]
\x1b[1mOPTIONS\x1b[0m
* depth: -1 is no recursion, 0 is infinite recursion, N > 0 is up to N levels (default: 0)
* ephemerals: include ephemerals (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get_acls /zookeeper
[ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
> get_acls /zookeeper -1
/zookeeper: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
/zookeeper/config: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
/zookeeper/quota: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
"""
def replace(plist, oldv, newv):
try:
plist.remove(oldv)
plist.insert(0, newv)
except ValueError:
pass
for path, acls in self._zk.get_acls_recursive(params.path, params.depth, params.ephemerals):
replace(acls, READ_ACL_UNSAFE[0], "WORLD_READ")
replace(acls, OPEN_ACL_UNSAFE[0], "WORLD_ALL")
self.show_output("%s: %s", path, acls) | python | def do_get_acls(self, params):
"""
\x1b[1mNAME\x1b[0m
get_acls - Gets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
get_acls <path> [depth] [ephemerals]
\x1b[1mOPTIONS\x1b[0m
* depth: -1 is no recursion, 0 is infinite recursion, N > 0 is up to N levels (default: 0)
* ephemerals: include ephemerals (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get_acls /zookeeper
[ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
> get_acls /zookeeper -1
/zookeeper: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
/zookeeper/config: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
/zookeeper/quota: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
"""
def replace(plist, oldv, newv):
try:
plist.remove(oldv)
plist.insert(0, newv)
except ValueError:
pass
for path, acls in self._zk.get_acls_recursive(params.path, params.depth, params.ephemerals):
replace(acls, READ_ACL_UNSAFE[0], "WORLD_READ")
replace(acls, OPEN_ACL_UNSAFE[0], "WORLD_ALL")
self.show_output("%s: %s", path, acls) | [
"def",
"do_get_acls",
"(",
"self",
",",
"params",
")",
":",
"def",
"replace",
"(",
"plist",
",",
"oldv",
",",
"newv",
")",
":",
"try",
":",
"plist",
".",
"remove",
"(",
"oldv",
")",
"plist",
".",
"insert",
"(",
"0",
",",
"newv",
")",
"except",
"V... | \x1b[1mNAME\x1b[0m
get_acls - Gets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
get_acls <path> [depth] [ephemerals]
\x1b[1mOPTIONS\x1b[0m
* depth: -1 is no recursion, 0 is infinite recursion, N > 0 is up to N levels (default: 0)
* ephemerals: include ephemerals (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get_acls /zookeeper
[ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
> get_acls /zookeeper -1
/zookeeper: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
/zookeeper/config: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
/zookeeper/quota: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))] | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"get_acls",
"-",
"Gets",
"ACLs",
"for",
"a",
"given",
"path"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L380-L412 | train | 213,604 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_watch | def do_watch(self, params):
"""
\x1b[1mNAME\x1b[0m
watch - Recursively watch for all changes under a path.
\x1b[1mSYNOPSIS\x1b[0m
watch <start|stop|stats> <path> [options]
\x1b[1mDESCRIPTION\x1b[0m
watch start <path> [debug] [depth]
with debug=true, print watches as they fire. depth is
the level for recursively setting watches:
* -1: recurse all the way
* 0: don't recurse, only watch the given path
* > 0: recurse up to <level> children
watch stats <path> [repeat] [sleep]
with repeat=0 this command will loop until interrupted. sleep sets
the pause duration in between each iteration.
watch stop <path>
\x1b[1mEXAMPLES\x1b[0m
> watch start /foo/bar
> watch stop /foo/bar
> watch stats /foo/bar
"""
wm = get_watch_manager(self._zk)
if params.command == "start":
debug = to_bool(params.debug)
children = to_int(params.sleep, -1)
wm.add(params.path, debug, children)
elif params.command == "stop":
wm.remove(params.path)
elif params.command == "stats":
repeat = to_int(params.debug, 1)
sleep = to_int(params.sleep, 1)
if repeat == 0:
while True:
wm.stats(params.path)
time.sleep(sleep)
else:
for _ in range(0, repeat):
wm.stats(params.path)
time.sleep(sleep)
else:
self.show_output("watch <start|stop|stats> <path> [verbose]") | python | def do_watch(self, params):
"""
\x1b[1mNAME\x1b[0m
watch - Recursively watch for all changes under a path.
\x1b[1mSYNOPSIS\x1b[0m
watch <start|stop|stats> <path> [options]
\x1b[1mDESCRIPTION\x1b[0m
watch start <path> [debug] [depth]
with debug=true, print watches as they fire. depth is
the level for recursively setting watches:
* -1: recurse all the way
* 0: don't recurse, only watch the given path
* > 0: recurse up to <level> children
watch stats <path> [repeat] [sleep]
with repeat=0 this command will loop until interrupted. sleep sets
the pause duration in between each iteration.
watch stop <path>
\x1b[1mEXAMPLES\x1b[0m
> watch start /foo/bar
> watch stop /foo/bar
> watch stats /foo/bar
"""
wm = get_watch_manager(self._zk)
if params.command == "start":
debug = to_bool(params.debug)
children = to_int(params.sleep, -1)
wm.add(params.path, debug, children)
elif params.command == "stop":
wm.remove(params.path)
elif params.command == "stats":
repeat = to_int(params.debug, 1)
sleep = to_int(params.sleep, 1)
if repeat == 0:
while True:
wm.stats(params.path)
time.sleep(sleep)
else:
for _ in range(0, repeat):
wm.stats(params.path)
time.sleep(sleep)
else:
self.show_output("watch <start|stop|stats> <path> [verbose]") | [
"def",
"do_watch",
"(",
"self",
",",
"params",
")",
":",
"wm",
"=",
"get_watch_manager",
"(",
"self",
".",
"_zk",
")",
"if",
"params",
".",
"command",
"==",
"\"start\"",
":",
"debug",
"=",
"to_bool",
"(",
"params",
".",
"debug",
")",
"children",
"=",
... | \x1b[1mNAME\x1b[0m
watch - Recursively watch for all changes under a path.
\x1b[1mSYNOPSIS\x1b[0m
watch <start|stop|stats> <path> [options]
\x1b[1mDESCRIPTION\x1b[0m
watch start <path> [debug] [depth]
with debug=true, print watches as they fire. depth is
the level for recursively setting watches:
* -1: recurse all the way
* 0: don't recurse, only watch the given path
* > 0: recurse up to <level> children
watch stats <path> [repeat] [sleep]
with repeat=0 this command will loop until interrupted. sleep sets
the pause duration in between each iteration.
watch stop <path>
\x1b[1mEXAMPLES\x1b[0m
> watch start /foo/bar
> watch stop /foo/bar
> watch stats /foo/bar | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"watch",
"-",
"Recursively",
"watch",
"for",
"all",
"changes",
"under",
"a",
"path",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L465-L515 | train | 213,605 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_child_count | def do_child_count(self, params):
"""
\x1b[1mNAME\x1b[0m
child_count - Prints the child count for paths
\x1b[1mSYNOPSIS\x1b[0m
child_count [path] [depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 1)
\x1b[1mEXAMPLES\x1b[0m
> child-count /
/zookeeper: 2
/foo: 0
/bar: 3
"""
for child, level in self._zk.tree(params.path, params.depth, full_path=True):
self.show_output("%s: %d", child, self._zk.child_count(child)) | python | def do_child_count(self, params):
"""
\x1b[1mNAME\x1b[0m
child_count - Prints the child count for paths
\x1b[1mSYNOPSIS\x1b[0m
child_count [path] [depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 1)
\x1b[1mEXAMPLES\x1b[0m
> child-count /
/zookeeper: 2
/foo: 0
/bar: 3
"""
for child, level in self._zk.tree(params.path, params.depth, full_path=True):
self.show_output("%s: %d", child, self._zk.child_count(child)) | [
"def",
"do_child_count",
"(",
"self",
",",
"params",
")",
":",
"for",
"child",
",",
"level",
"in",
"self",
".",
"_zk",
".",
"tree",
"(",
"params",
".",
"path",
",",
"params",
".",
"depth",
",",
"full_path",
"=",
"True",
")",
":",
"self",
".",
"show... | \x1b[1mNAME\x1b[0m
child_count - Prints the child count for paths
\x1b[1mSYNOPSIS\x1b[0m
child_count [path] [depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 1)
\x1b[1mEXAMPLES\x1b[0m
> child-count /
/zookeeper: 2
/foo: 0
/bar: 3 | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"child_count",
"-",
"Prints",
"the",
"child",
"count",
"for",
"paths"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L731-L751 | train | 213,606 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_du | def do_du(self, params):
"""
\x1b[1mNAME\x1b[0m
du - Total number of bytes under a path
\x1b[1mSYNOPSIS\x1b[0m
du [path]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
\x1b[1mEXAMPLES\x1b[0m
> du /
90
"""
self.show_output(pretty_bytes(self._zk.du(params.path))) | python | def do_du(self, params):
"""
\x1b[1mNAME\x1b[0m
du - Total number of bytes under a path
\x1b[1mSYNOPSIS\x1b[0m
du [path]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
\x1b[1mEXAMPLES\x1b[0m
> du /
90
"""
self.show_output(pretty_bytes(self._zk.du(params.path))) | [
"def",
"do_du",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"show_output",
"(",
"pretty_bytes",
"(",
"self",
".",
"_zk",
".",
"du",
"(",
"params",
".",
"path",
")",
")",
")"
] | \x1b[1mNAME\x1b[0m
du - Total number of bytes under a path
\x1b[1mSYNOPSIS\x1b[0m
du [path]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
\x1b[1mEXAMPLES\x1b[0m
> du /
90 | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"du",
"-",
"Total",
"number",
"of",
"bytes",
"under",
"a",
"path"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L761-L777 | train | 213,607 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_find | def do_find(self, params):
"""
\x1b[1mNAME\x1b[0m
find - Find znodes whose path matches a given text
\x1b[1mSYNOPSIS\x1b[0m
find [path] [match]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* match: the string to match in the paths (default: '')
\x1b[1mEXAMPLES\x1b[0m
> find / foo
/foo2
/fooish/wayland
/fooish/xorg
/copy/foo
"""
for path in self._zk.find(params.path, params.match, 0):
self.show_output(path) | python | def do_find(self, params):
"""
\x1b[1mNAME\x1b[0m
find - Find znodes whose path matches a given text
\x1b[1mSYNOPSIS\x1b[0m
find [path] [match]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* match: the string to match in the paths (default: '')
\x1b[1mEXAMPLES\x1b[0m
> find / foo
/foo2
/fooish/wayland
/fooish/xorg
/copy/foo
"""
for path in self._zk.find(params.path, params.match, 0):
self.show_output(path) | [
"def",
"do_find",
"(",
"self",
",",
"params",
")",
":",
"for",
"path",
"in",
"self",
".",
"_zk",
".",
"find",
"(",
"params",
".",
"path",
",",
"params",
".",
"match",
",",
"0",
")",
":",
"self",
".",
"show_output",
"(",
"path",
")"
] | \x1b[1mNAME\x1b[0m
find - Find znodes whose path matches a given text
\x1b[1mSYNOPSIS\x1b[0m
find [path] [match]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* match: the string to match in the paths (default: '')
\x1b[1mEXAMPLES\x1b[0m
> find / foo
/foo2
/fooish/wayland
/fooish/xorg
/copy/foo | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"find",
"-",
"Find",
"znodes",
"whose",
"path",
"matches",
"a",
"given",
"text"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L784-L805 | train | 213,608 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_summary | def do_summary(self, params):
"""
\x1b[1mNAME\x1b[0m
summary - Prints summarized details of a path's children
\x1b[1mSYNOPSIS\x1b[0m
summary [path] [top]
\x1b[1mDESCRIPTION\x1b[0m
The results are sorted by name.
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* top: number of results to be displayed (0 is all) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> summary /services/registrations
Created Last modified Owner Name
Thu Oct 11 09:14:39 2014 Thu Oct 11 09:14:39 2014 - bar
Thu Oct 16 18:54:39 2014 Thu Oct 16 18:54:39 2014 - foo
Thu Oct 12 10:04:01 2014 Thu Oct 12 10:04:01 2014 0x14911e869aa0dc1 member_0000001
"""
self.show_output("%s%s%s%s",
"Created".ljust(32),
"Last modified".ljust(32),
"Owner".ljust(23),
"Name")
results = sorted(self._zk.stat_map(params.path))
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
offs = 1 if params.path == "/" else len(params.path) + 1
for i in range(start, end):
path, stat = results[i]
self.show_output(
"%s%s%s%s",
time.ctime(stat.created).ljust(32),
time.ctime(stat.last_modified).ljust(32),
("0x%x" % stat.ephemeralOwner).ljust(23),
path[offs:]
) | python | def do_summary(self, params):
"""
\x1b[1mNAME\x1b[0m
summary - Prints summarized details of a path's children
\x1b[1mSYNOPSIS\x1b[0m
summary [path] [top]
\x1b[1mDESCRIPTION\x1b[0m
The results are sorted by name.
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* top: number of results to be displayed (0 is all) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> summary /services/registrations
Created Last modified Owner Name
Thu Oct 11 09:14:39 2014 Thu Oct 11 09:14:39 2014 - bar
Thu Oct 16 18:54:39 2014 Thu Oct 16 18:54:39 2014 - foo
Thu Oct 12 10:04:01 2014 Thu Oct 12 10:04:01 2014 0x14911e869aa0dc1 member_0000001
"""
self.show_output("%s%s%s%s",
"Created".ljust(32),
"Last modified".ljust(32),
"Owner".ljust(23),
"Name")
results = sorted(self._zk.stat_map(params.path))
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
offs = 1 if params.path == "/" else len(params.path) + 1
for i in range(start, end):
path, stat = results[i]
self.show_output(
"%s%s%s%s",
time.ctime(stat.created).ljust(32),
time.ctime(stat.last_modified).ljust(32),
("0x%x" % stat.ephemeralOwner).ljust(23),
path[offs:]
) | [
"def",
"do_summary",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"show_output",
"(",
"\"%s%s%s%s\"",
",",
"\"Created\"",
".",
"ljust",
"(",
"32",
")",
",",
"\"Last modified\"",
".",
"ljust",
"(",
"32",
")",
",",
"\"Owner\"",
".",
"ljust",
"(",
"... | \x1b[1mNAME\x1b[0m
summary - Prints summarized details of a path's children
\x1b[1mSYNOPSIS\x1b[0m
summary [path] [top]
\x1b[1mDESCRIPTION\x1b[0m
The results are sorted by name.
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* top: number of results to be displayed (0 is all) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> summary /services/registrations
Created Last modified Owner Name
Thu Oct 11 09:14:39 2014 Thu Oct 11 09:14:39 2014 - bar
Thu Oct 16 18:54:39 2014 Thu Oct 16 18:54:39 2014 - foo
Thu Oct 12 10:04:01 2014 Thu Oct 12 10:04:01 2014 0x14911e869aa0dc1 member_0000001 | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"summary",
"-",
"Prints",
"summarized",
"details",
"of",
"a",
"path",
"s",
"children"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L864-L915 | train | 213,609 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_grep | def do_grep(self, params):
"""
\x1b[1mNAME\x1b[0m
grep - Prints znodes with a value matching the given text
\x1b[1mSYNOPSIS\x1b[0m
grep [path] <content> [show_matches]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* show_matches: show the content that matched (default: false)
\x1b[1mEXAMPLES\x1b[0m
> grep / unbound true
/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin
/copy/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin
"""
self.grep(params.path, params.content, 0, params.show_matches) | python | def do_grep(self, params):
"""
\x1b[1mNAME\x1b[0m
grep - Prints znodes with a value matching the given text
\x1b[1mSYNOPSIS\x1b[0m
grep [path] <content> [show_matches]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* show_matches: show the content that matched (default: false)
\x1b[1mEXAMPLES\x1b[0m
> grep / unbound true
/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin
/copy/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin
"""
self.grep(params.path, params.content, 0, params.show_matches) | [
"def",
"do_grep",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"grep",
"(",
"params",
".",
"path",
",",
"params",
".",
"content",
",",
"0",
",",
"params",
".",
"show_matches",
")"
] | \x1b[1mNAME\x1b[0m
grep - Prints znodes with a value matching the given text
\x1b[1mSYNOPSIS\x1b[0m
grep [path] <content> [show_matches]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* show_matches: show the content that matched (default: false)
\x1b[1mEXAMPLES\x1b[0m
> grep / unbound true
/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin
/copy/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"grep",
"-",
"Prints",
"znodes",
"with",
"a",
"value",
"matching",
"the",
"given",
"text"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L956-L974 | train | 213,610 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_get | def do_get(self, params):
"""
\x1b[1mNAME\x1b[0m
get - Gets the znode's value
\x1b[1mSYNOPSIS\x1b[0m
get <path> [watch]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get /foo
bar
# sets a watch
> get /foo true
bar
# trigger the watch
> set /foo 'notbar'
WatchedEvent(type='CHANGED', state='CONNECTED', path=u'/foo')
"""
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
value, _ = self._zk.get(params.path, **kwargs)
# maybe it's compressed?
if value is not None:
try:
value = zlib.decompress(value)
except:
pass
self.show_output(value) | python | def do_get(self, params):
"""
\x1b[1mNAME\x1b[0m
get - Gets the znode's value
\x1b[1mSYNOPSIS\x1b[0m
get <path> [watch]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get /foo
bar
# sets a watch
> get /foo true
bar
# trigger the watch
> set /foo 'notbar'
WatchedEvent(type='CHANGED', state='CONNECTED', path=u'/foo')
"""
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
value, _ = self._zk.get(params.path, **kwargs)
# maybe it's compressed?
if value is not None:
try:
value = zlib.decompress(value)
except:
pass
self.show_output(value) | [
"def",
"do_get",
"(",
"self",
",",
"params",
")",
":",
"watcher",
"=",
"lambda",
"evt",
":",
"self",
".",
"show_output",
"(",
"str",
"(",
"evt",
")",
")",
"kwargs",
"=",
"{",
"\"watch\"",
":",
"watcher",
"}",
"if",
"params",
".",
"watch",
"else",
"... | \x1b[1mNAME\x1b[0m
get - Gets the znode's value
\x1b[1mSYNOPSIS\x1b[0m
get <path> [watch]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get /foo
bar
# sets a watch
> get /foo true
bar
# trigger the watch
> set /foo 'notbar'
WatchedEvent(type='CHANGED', state='CONNECTED', path=u'/foo') | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"get",
"-",
"Gets",
"the",
"znode",
"s",
"value"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1051-L1086 | train | 213,611 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_exists | def do_exists(self, params):
"""
\x1b[1mNAME\x1b[0m
exists - Gets the znode's stat information
\x1b[1mSYNOPSIS\x1b[0m
exists <path> [watch] [pretty_date]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
exists /foo
Stat(
czxid=101,
mzxid=102,
ctime=1382820644375,
mtime=1382820693801,
version=1,
cversion=0,
aversion=0,
ephemeralOwner=0,
dataLength=6,
numChildren=0,
pzxid=101
)
# sets a watch
> exists /foo true
...
# trigger the watch
> rm /foo
WatchedEvent(type='DELETED', state='CONNECTED', path=u'/foo')
"""
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
pretty = params.pretty_date
path = self.resolve_path(params.path)
stat = self._zk.exists(path, **kwargs)
if stat:
session = stat.ephemeralOwner if stat.ephemeralOwner else 0
self.show_output("Stat(")
self.show_output(" czxid=0x%x", stat.czxid)
self.show_output(" mzxid=0x%x", stat.mzxid)
self.show_output(" ctime=%s", time.ctime(stat.created) if pretty else stat.ctime)
self.show_output(" mtime=%s", time.ctime(stat.last_modified) if pretty else stat.mtime)
self.show_output(" version=%s", stat.version)
self.show_output(" cversion=%s", stat.cversion)
self.show_output(" aversion=%s", stat.aversion)
self.show_output(" ephemeralOwner=0x%x", session)
self.show_output(" dataLength=%s", stat.dataLength)
self.show_output(" numChildren=%s", stat.numChildren)
self.show_output(" pzxid=0x%x", stat.pzxid)
self.show_output(")")
else:
self.show_output("Path %s doesn't exist", params.path) | python | def do_exists(self, params):
"""
\x1b[1mNAME\x1b[0m
exists - Gets the znode's stat information
\x1b[1mSYNOPSIS\x1b[0m
exists <path> [watch] [pretty_date]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
exists /foo
Stat(
czxid=101,
mzxid=102,
ctime=1382820644375,
mtime=1382820693801,
version=1,
cversion=0,
aversion=0,
ephemeralOwner=0,
dataLength=6,
numChildren=0,
pzxid=101
)
# sets a watch
> exists /foo true
...
# trigger the watch
> rm /foo
WatchedEvent(type='DELETED', state='CONNECTED', path=u'/foo')
"""
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
pretty = params.pretty_date
path = self.resolve_path(params.path)
stat = self._zk.exists(path, **kwargs)
if stat:
session = stat.ephemeralOwner if stat.ephemeralOwner else 0
self.show_output("Stat(")
self.show_output(" czxid=0x%x", stat.czxid)
self.show_output(" mzxid=0x%x", stat.mzxid)
self.show_output(" ctime=%s", time.ctime(stat.created) if pretty else stat.ctime)
self.show_output(" mtime=%s", time.ctime(stat.last_modified) if pretty else stat.mtime)
self.show_output(" version=%s", stat.version)
self.show_output(" cversion=%s", stat.cversion)
self.show_output(" aversion=%s", stat.aversion)
self.show_output(" ephemeralOwner=0x%x", session)
self.show_output(" dataLength=%s", stat.dataLength)
self.show_output(" numChildren=%s", stat.numChildren)
self.show_output(" pzxid=0x%x", stat.pzxid)
self.show_output(")")
else:
self.show_output("Path %s doesn't exist", params.path) | [
"def",
"do_exists",
"(",
"self",
",",
"params",
")",
":",
"watcher",
"=",
"lambda",
"evt",
":",
"self",
".",
"show_output",
"(",
"str",
"(",
"evt",
")",
")",
"kwargs",
"=",
"{",
"\"watch\"",
":",
"watcher",
"}",
"if",
"params",
".",
"watch",
"else",
... | \x1b[1mNAME\x1b[0m
exists - Gets the znode's stat information
\x1b[1mSYNOPSIS\x1b[0m
exists <path> [watch] [pretty_date]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
exists /foo
Stat(
czxid=101,
mzxid=102,
ctime=1382820644375,
mtime=1382820693801,
version=1,
cversion=0,
aversion=0,
ephemeralOwner=0,
dataLength=6,
numChildren=0,
pzxid=101
)
# sets a watch
> exists /foo true
...
# trigger the watch
> rm /foo
WatchedEvent(type='DELETED', state='CONNECTED', path=u'/foo') | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"exists",
"-",
"Gets",
"the",
"znode",
"s",
"stat",
"information"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1094-L1151 | train | 213,612 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_create | def do_create(self, params):
"""
\x1b[1mNAME\x1b[0m
create - Creates a znode
\x1b[1mSYNOPSIS\x1b[0m
create <path> <value> [ephemeral] [sequence] [recursive] [async]
\x1b[1mOPTIONS\x1b[0m
* ephemeral: make the znode ephemeral (default: false)
* sequence: make the znode sequential (default: false)
* recursive: recursively create the path (default: false)
* async: don't block waiting on the result (default: false)
\x1b[1mEXAMPLES\x1b[0m
> create /foo 'bar'
# create an ephemeral znode
> create /foo1 '' true
# create an ephemeral|sequential znode
> create /foo1 '' true true
# recursively create a path
> create /very/long/path/here '' false false true
# check the new subtree
> tree
.
├── zookeeper
│ ├── config
│ ├── quota
├── very
│ ├── long
│ │ ├── path
│ │ │ ├── here
"""
try:
kwargs = {"acl": None, "ephemeral": params.ephemeral, "sequence": params.sequence}
if not self.in_transaction:
kwargs["makepath"] = params.recursive
if params.asynchronous and not self.in_transaction:
self.client_context.create_async(params.path, decoded(params.value), **kwargs)
else:
self.client_context.create(params.path, decoded(params.value), **kwargs)
except NodeExistsError:
self.show_output("Path %s exists", params.path)
except NoNodeError:
self.show_output("Missing path in %s (try recursive?)", params.path) | python | def do_create(self, params):
"""
\x1b[1mNAME\x1b[0m
create - Creates a znode
\x1b[1mSYNOPSIS\x1b[0m
create <path> <value> [ephemeral] [sequence] [recursive] [async]
\x1b[1mOPTIONS\x1b[0m
* ephemeral: make the znode ephemeral (default: false)
* sequence: make the znode sequential (default: false)
* recursive: recursively create the path (default: false)
* async: don't block waiting on the result (default: false)
\x1b[1mEXAMPLES\x1b[0m
> create /foo 'bar'
# create an ephemeral znode
> create /foo1 '' true
# create an ephemeral|sequential znode
> create /foo1 '' true true
# recursively create a path
> create /very/long/path/here '' false false true
# check the new subtree
> tree
.
├── zookeeper
│ ├── config
│ ├── quota
├── very
│ ├── long
│ │ ├── path
│ │ │ ├── here
"""
try:
kwargs = {"acl": None, "ephemeral": params.ephemeral, "sequence": params.sequence}
if not self.in_transaction:
kwargs["makepath"] = params.recursive
if params.asynchronous and not self.in_transaction:
self.client_context.create_async(params.path, decoded(params.value), **kwargs)
else:
self.client_context.create(params.path, decoded(params.value), **kwargs)
except NodeExistsError:
self.show_output("Path %s exists", params.path)
except NoNodeError:
self.show_output("Missing path in %s (try recursive?)", params.path) | [
"def",
"do_create",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"kwargs",
"=",
"{",
"\"acl\"",
":",
"None",
",",
"\"ephemeral\"",
":",
"params",
".",
"ephemeral",
",",
"\"sequence\"",
":",
"params",
".",
"sequence",
"}",
"if",
"not",
"self",
".",... | \x1b[1mNAME\x1b[0m
create - Creates a znode
\x1b[1mSYNOPSIS\x1b[0m
create <path> <value> [ephemeral] [sequence] [recursive] [async]
\x1b[1mOPTIONS\x1b[0m
* ephemeral: make the znode ephemeral (default: false)
* sequence: make the znode sequential (default: false)
* recursive: recursively create the path (default: false)
* async: don't block waiting on the result (default: false)
\x1b[1mEXAMPLES\x1b[0m
> create /foo 'bar'
# create an ephemeral znode
> create /foo1 '' true
# create an ephemeral|sequential znode
> create /foo1 '' true true
# recursively create a path
> create /very/long/path/here '' false false true
# check the new subtree
> tree
.
├── zookeeper
│ ├── config
│ ├── quota
├── very
│ ├── long
│ │ ├── path
│ │ │ ├── here | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"create",
"-",
"Creates",
"a",
"znode"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1180-L1230 | train | 213,613 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_set | def do_set(self, params):
"""
\x1b[1mNAME\x1b[0m
set - Updates the znode's value
\x1b[1mSYNOPSIS\x1b[0m
set <path> <value> [version]
\x1b[1mOPTIONS\x1b[0m
* version: only update if version matches (default: -1)
\x1b[1mEXAMPLES\x1b[0m
> set /foo 'bar'
> set /foo 'verybar' 3
"""
self.set(params.path, decoded(params.value), version=params.version) | python | def do_set(self, params):
"""
\x1b[1mNAME\x1b[0m
set - Updates the znode's value
\x1b[1mSYNOPSIS\x1b[0m
set <path> <value> [version]
\x1b[1mOPTIONS\x1b[0m
* version: only update if version matches (default: -1)
\x1b[1mEXAMPLES\x1b[0m
> set /foo 'bar'
> set /foo 'verybar' 3
"""
self.set(params.path, decoded(params.value), version=params.version) | [
"def",
"do_set",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"set",
"(",
"params",
".",
"path",
",",
"decoded",
"(",
"params",
".",
"value",
")",
",",
"version",
"=",
"params",
".",
"version",
")"
] | \x1b[1mNAME\x1b[0m
set - Updates the znode's value
\x1b[1mSYNOPSIS\x1b[0m
set <path> <value> [version]
\x1b[1mOPTIONS\x1b[0m
* version: only update if version matches (default: -1)
\x1b[1mEXAMPLES\x1b[0m
> set /foo 'bar'
> set /foo 'verybar' 3 | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"set",
"-",
"Updates",
"the",
"znode",
"s",
"value"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1247-L1263 | train | 213,614 |
rgs1/zk_shell | zk_shell/shell.py | Shell.set | def set(self, path, value, version):
""" sets a znode's data """
if self.in_transaction:
self.client_context.set_data(path, value, version=version)
else:
self.client_context.set(path, value, version=version) | python | def set(self, path, value, version):
""" sets a znode's data """
if self.in_transaction:
self.client_context.set_data(path, value, version=version)
else:
self.client_context.set(path, value, version=version) | [
"def",
"set",
"(",
"self",
",",
"path",
",",
"value",
",",
"version",
")",
":",
"if",
"self",
".",
"in_transaction",
":",
"self",
".",
"client_context",
".",
"set_data",
"(",
"path",
",",
"value",
",",
"version",
"=",
"version",
")",
"else",
":",
"se... | sets a znode's data | [
"sets",
"a",
"znode",
"s",
"data"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1299-L1304 | train | 213,615 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_rm | def do_rm(self, params):
"""
\x1b[1mNAME\x1b[0m
rm - Remove the znode
\x1b[1mSYNOPSIS\x1b[0m
rm <path> [path] [path] ... [path]
\x1b[1mEXAMPLES\x1b[0m
> rm /foo
> rm /foo /bar
"""
for path in params.paths:
try:
self.client_context.delete(path)
except NotEmptyError:
self.show_output("%s is not empty.", path)
except NoNodeError:
self.show_output("%s doesn't exist.", path) | python | def do_rm(self, params):
"""
\x1b[1mNAME\x1b[0m
rm - Remove the znode
\x1b[1mSYNOPSIS\x1b[0m
rm <path> [path] [path] ... [path]
\x1b[1mEXAMPLES\x1b[0m
> rm /foo
> rm /foo /bar
"""
for path in params.paths:
try:
self.client_context.delete(path)
except NotEmptyError:
self.show_output("%s is not empty.", path)
except NoNodeError:
self.show_output("%s doesn't exist.", path) | [
"def",
"do_rm",
"(",
"self",
",",
"params",
")",
":",
"for",
"path",
"in",
"params",
".",
"paths",
":",
"try",
":",
"self",
".",
"client_context",
".",
"delete",
"(",
"path",
")",
"except",
"NotEmptyError",
":",
"self",
".",
"show_output",
"(",
"\"%s i... | \x1b[1mNAME\x1b[0m
rm - Remove the znode
\x1b[1mSYNOPSIS\x1b[0m
rm <path> [path] [path] ... [path]
\x1b[1mEXAMPLES\x1b[0m
> rm /foo
> rm /foo /bar | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"rm",
"-",
"Remove",
"the",
"znode"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1309-L1328 | train | 213,616 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_txn | def do_txn(self, params):
"""
\x1b[1mNAME\x1b[0m
txn - Create and execute a transaction
\x1b[1mSYNOPSIS\x1b[0m
txn <cmd> [cmd] [cmd] ... [cmd]
\x1b[1mDESCRIPTION\x1b[0m
Allowed cmds are check, create, rm and set. Check parameters are:
check <path> <version>
For create, rm and set see their help menu for their respective parameters.
\x1b[1mEXAMPLES\x1b[0m
> txn 'create /foo "start"' 'check /foo 0' 'set /foo "end"' 'rm /foo 1'
"""
try:
with self.transaction():
for cmd in params.cmds:
try:
self.onecmd(cmd)
except AttributeError:
# silently swallow unrecognized commands
pass
except BadVersionError:
self.show_output("Bad version.")
except NoNodeError:
self.show_output("Missing path.")
except NodeExistsError:
self.show_output("One of the paths exists.") | python | def do_txn(self, params):
"""
\x1b[1mNAME\x1b[0m
txn - Create and execute a transaction
\x1b[1mSYNOPSIS\x1b[0m
txn <cmd> [cmd] [cmd] ... [cmd]
\x1b[1mDESCRIPTION\x1b[0m
Allowed cmds are check, create, rm and set. Check parameters are:
check <path> <version>
For create, rm and set see their help menu for their respective parameters.
\x1b[1mEXAMPLES\x1b[0m
> txn 'create /foo "start"' 'check /foo 0' 'set /foo "end"' 'rm /foo 1'
"""
try:
with self.transaction():
for cmd in params.cmds:
try:
self.onecmd(cmd)
except AttributeError:
# silently swallow unrecognized commands
pass
except BadVersionError:
self.show_output("Bad version.")
except NoNodeError:
self.show_output("Missing path.")
except NodeExistsError:
self.show_output("One of the paths exists.") | [
"def",
"do_txn",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"with",
"self",
".",
"transaction",
"(",
")",
":",
"for",
"cmd",
"in",
"params",
".",
"cmds",
":",
"try",
":",
"self",
".",
"onecmd",
"(",
"cmd",
")",
"except",
"AttributeError",
":... | \x1b[1mNAME\x1b[0m
txn - Create and execute a transaction
\x1b[1mSYNOPSIS\x1b[0m
txn <cmd> [cmd] [cmd] ... [cmd]
\x1b[1mDESCRIPTION\x1b[0m
Allowed cmds are check, create, rm and set. Check parameters are:
check <path> <version>
For create, rm and set see their help menu for their respective parameters.
\x1b[1mEXAMPLES\x1b[0m
> txn 'create /foo "start"' 'check /foo 0' 'set /foo "end"' 'rm /foo 1' | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"txn",
"-",
"Create",
"and",
"execute",
"a",
"transaction"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1355-L1387 | train | 213,617 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_session_info | def do_session_info(self, params):
"""
\x1b[1mNAME\x1b[0m
session_info - Shows information about the current session
\x1b[1mSYNOPSIS\x1b[0m
session_info [match]
\x1b[1mOPTIONS\x1b[0m
* match: only include lines that match (default: '')
\x1b[1mEXAMPLES\x1b[0m
> session_info
state=CONNECTED
xid=4
last_zxid=0x000000505f8be5b3
timeout=10000
client=('127.0.0.1', 60348)
server=('127.0.0.1', 2181)
"""
fmt_str = """state=%s
sessionid=%s
auth_info=%s
protocol_version=%d
xid=%d
last_zxid=0x%.16x
timeout=%d
client=%s
server=%s
data_watches=%s
child_watches=%s"""
content = fmt_str % (
self._zk.client_state,
self._zk.sessionid,
list(self._zk.auth_data),
self._zk.protocol_version,
self._zk.xid,
self._zk.last_zxid,
self._zk.session_timeout,
self._zk.client,
self._zk.server,
",".join(self._zk.data_watches),
",".join(self._zk.child_watches)
)
output = get_matching(content, params.match)
self.show_output(output) | python | def do_session_info(self, params):
"""
\x1b[1mNAME\x1b[0m
session_info - Shows information about the current session
\x1b[1mSYNOPSIS\x1b[0m
session_info [match]
\x1b[1mOPTIONS\x1b[0m
* match: only include lines that match (default: '')
\x1b[1mEXAMPLES\x1b[0m
> session_info
state=CONNECTED
xid=4
last_zxid=0x000000505f8be5b3
timeout=10000
client=('127.0.0.1', 60348)
server=('127.0.0.1', 2181)
"""
fmt_str = """state=%s
sessionid=%s
auth_info=%s
protocol_version=%d
xid=%d
last_zxid=0x%.16x
timeout=%d
client=%s
server=%s
data_watches=%s
child_watches=%s"""
content = fmt_str % (
self._zk.client_state,
self._zk.sessionid,
list(self._zk.auth_data),
self._zk.protocol_version,
self._zk.xid,
self._zk.last_zxid,
self._zk.session_timeout,
self._zk.client,
self._zk.server,
",".join(self._zk.data_watches),
",".join(self._zk.child_watches)
)
output = get_matching(content, params.match)
self.show_output(output) | [
"def",
"do_session_info",
"(",
"self",
",",
"params",
")",
":",
"fmt_str",
"=",
"\"\"\"state=%s\nsessionid=%s\nauth_info=%s\nprotocol_version=%d\nxid=%d\nlast_zxid=0x%.16x\ntimeout=%d\nclient=%s\nserver=%s\ndata_watches=%s\nchild_watches=%s\"\"\"",
"content",
"=",
"fmt_str",
"%",
"(",
... | \x1b[1mNAME\x1b[0m
session_info - Shows information about the current session
\x1b[1mSYNOPSIS\x1b[0m
session_info [match]
\x1b[1mOPTIONS\x1b[0m
* match: only include lines that match (default: '')
\x1b[1mEXAMPLES\x1b[0m
> session_info
state=CONNECTED
xid=4
last_zxid=0x000000505f8be5b3
timeout=10000
client=('127.0.0.1', 60348)
server=('127.0.0.1', 2181) | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"session_info",
"-",
"Shows",
"information",
"about",
"the",
"current",
"session"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1430-L1477 | train | 213,618 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_mntr | def do_mntr(self, params):
"""
\x1b[1mNAME\x1b[0m
mntr - Executes the mntr four-letter command
\x1b[1mSYNOPSIS\x1b[0m
mntr [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> mntr
zk_version 3.5.0--1, built on 11/14/2014 10:45 GMT
zk_min_latency 0
zk_max_latency 8
zk_avg_latency 0
"""
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.mntr(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) | python | def do_mntr(self, params):
"""
\x1b[1mNAME\x1b[0m
mntr - Executes the mntr four-letter command
\x1b[1mSYNOPSIS\x1b[0m
mntr [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> mntr
zk_version 3.5.0--1, built on 11/14/2014 10:45 GMT
zk_min_latency 0
zk_max_latency 8
zk_avg_latency 0
"""
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.mntr(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) | [
"def",
"do_mntr",
"(",
"self",
",",
"params",
")",
":",
"hosts",
"=",
"params",
".",
"hosts",
"if",
"params",
".",
"hosts",
"!=",
"\"\"",
"else",
"None",
"if",
"hosts",
"is",
"not",
"None",
"and",
"invalid_hosts",
"(",
"hosts",
")",
":",
"self",
".",... | \x1b[1mNAME\x1b[0m
mntr - Executes the mntr four-letter command
\x1b[1mSYNOPSIS\x1b[0m
mntr [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> mntr
zk_version 3.5.0--1, built on 11/14/2014 10:45 GMT
zk_min_latency 0
zk_max_latency 8
zk_avg_latency 0 | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"mntr",
"-",
"Executes",
"the",
"mntr",
"four",
"-",
"letter",
"command"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1496-L1529 | train | 213,619 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_cons | def do_cons(self, params):
"""
\x1b[1mNAME\x1b[0m
cons - Executes the cons four-letter command
\x1b[1mSYNOPSIS\x1b[0m
cons [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> cons
/127.0.0.1:40535[0](queued=0,recved=1,sent=0)
...
"""
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.cons(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) | python | def do_cons(self, params):
"""
\x1b[1mNAME\x1b[0m
cons - Executes the cons four-letter command
\x1b[1mSYNOPSIS\x1b[0m
cons [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> cons
/127.0.0.1:40535[0](queued=0,recved=1,sent=0)
...
"""
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.cons(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) | [
"def",
"do_cons",
"(",
"self",
",",
"params",
")",
":",
"hosts",
"=",
"params",
".",
"hosts",
"if",
"params",
".",
"hosts",
"!=",
"\"\"",
"else",
"None",
"if",
"hosts",
"is",
"not",
"None",
"and",
"invalid_hosts",
"(",
"hosts",
")",
":",
"self",
".",... | \x1b[1mNAME\x1b[0m
cons - Executes the cons four-letter command
\x1b[1mSYNOPSIS\x1b[0m
cons [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> cons
/127.0.0.1:40535[0](queued=0,recved=1,sent=0)
... | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"cons",
"-",
"Executes",
"the",
"cons",
"four",
"-",
"letter",
"command"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1532-L1563 | train | 213,620 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_dump | def do_dump(self, params):
"""
\x1b[1mNAME\x1b[0m
dump - Executes the dump four-letter command
\x1b[1mSYNOPSIS\x1b[0m
dump [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> dump
SessionTracker dump:
Session Sets (3)/(1):
0 expire at Fri Nov 14 02:49:52 PST 2014:
0 expire at Fri Nov 14 02:49:56 PST 2014:
1 expire at Fri Nov 14 02:50:00 PST 2014:
0x149adea89940107
ephemeral nodes dump:
Sessions with Ephemerals (0):
"""
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.dump(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) | python | def do_dump(self, params):
"""
\x1b[1mNAME\x1b[0m
dump - Executes the dump four-letter command
\x1b[1mSYNOPSIS\x1b[0m
dump [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> dump
SessionTracker dump:
Session Sets (3)/(1):
0 expire at Fri Nov 14 02:49:52 PST 2014:
0 expire at Fri Nov 14 02:49:56 PST 2014:
1 expire at Fri Nov 14 02:50:00 PST 2014:
0x149adea89940107
ephemeral nodes dump:
Sessions with Ephemerals (0):
"""
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.dump(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) | [
"def",
"do_dump",
"(",
"self",
",",
"params",
")",
":",
"hosts",
"=",
"params",
".",
"hosts",
"if",
"params",
".",
"hosts",
"!=",
"\"\"",
"else",
"None",
"if",
"hosts",
"is",
"not",
"None",
"and",
"invalid_hosts",
"(",
"hosts",
")",
":",
"self",
".",... | \x1b[1mNAME\x1b[0m
dump - Executes the dump four-letter command
\x1b[1mSYNOPSIS\x1b[0m
dump [hosts] [match]
\x1b[1mOPTIONS\x1b[0m
* hosts: the hosts to connect to (default: the current connected host)
* match: only output lines that include the given string (default: '')
\x1b[1mEXAMPLES\x1b[0m
> dump
SessionTracker dump:
Session Sets (3)/(1):
0 expire at Fri Nov 14 02:49:52 PST 2014:
0 expire at Fri Nov 14 02:49:56 PST 2014:
1 expire at Fri Nov 14 02:50:00 PST 2014:
0x149adea89940107
ephemeral nodes dump:
Sessions with Ephemerals (0): | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"dump",
"-",
"Executes",
"the",
"dump",
"four",
"-",
"letter",
"command"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1566-L1603 | train | 213,621 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_rmr | def do_rmr(self, params):
"""
\x1b[1mNAME\x1b[0m
rmr - Delete a path and all its children
\x1b[1mSYNOPSIS\x1b[0m
rmr <path> [path] [path] ... [path]
\x1b[1mEXAMPLES\x1b[0m
> rmr /foo
> rmr /foo /bar
"""
for path in params.paths:
self._zk.delete(path, recursive=True) | python | def do_rmr(self, params):
"""
\x1b[1mNAME\x1b[0m
rmr - Delete a path and all its children
\x1b[1mSYNOPSIS\x1b[0m
rmr <path> [path] [path] ... [path]
\x1b[1mEXAMPLES\x1b[0m
> rmr /foo
> rmr /foo /bar
"""
for path in params.paths:
self._zk.delete(path, recursive=True) | [
"def",
"do_rmr",
"(",
"self",
",",
"params",
")",
":",
"for",
"path",
"in",
"params",
".",
"paths",
":",
"self",
".",
"_zk",
".",
"delete",
"(",
"path",
",",
"recursive",
"=",
"True",
")"
] | \x1b[1mNAME\x1b[0m
rmr - Delete a path and all its children
\x1b[1mSYNOPSIS\x1b[0m
rmr <path> [path] [path] ... [path]
\x1b[1mEXAMPLES\x1b[0m
> rmr /foo
> rmr /foo /bar | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"rmr",
"-",
"Delete",
"a",
"path",
"and",
"all",
"its",
"children"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1775-L1789 | train | 213,622 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_child_watch | def do_child_watch(self, params):
"""
\x1b[1mNAME\x1b[0m
child_watch - Watch a path for child changes
\x1b[1mSYNOPSIS\x1b[0m
child_watch <path> [verbose]
\x1b[1mOPTIONS\x1b[0m
* verbose: prints list of znodes (default: false)
\x1b[1mEXAMPLES\x1b[0m
# only prints the current number of children
> child_watch /
# prints num of children along with znodes listing
> child_watch / true
"""
get_child_watcher(self._zk, print_func=self.show_output).update(
params.path, params.verbose) | python | def do_child_watch(self, params):
"""
\x1b[1mNAME\x1b[0m
child_watch - Watch a path for child changes
\x1b[1mSYNOPSIS\x1b[0m
child_watch <path> [verbose]
\x1b[1mOPTIONS\x1b[0m
* verbose: prints list of znodes (default: false)
\x1b[1mEXAMPLES\x1b[0m
# only prints the current number of children
> child_watch /
# prints num of children along with znodes listing
> child_watch / true
"""
get_child_watcher(self._zk, print_func=self.show_output).update(
params.path, params.verbose) | [
"def",
"do_child_watch",
"(",
"self",
",",
"params",
")",
":",
"get_child_watcher",
"(",
"self",
".",
"_zk",
",",
"print_func",
"=",
"self",
".",
"show_output",
")",
".",
"update",
"(",
"params",
".",
"path",
",",
"params",
".",
"verbose",
")"
] | \x1b[1mNAME\x1b[0m
child_watch - Watch a path for child changes
\x1b[1mSYNOPSIS\x1b[0m
child_watch <path> [verbose]
\x1b[1mOPTIONS\x1b[0m
* verbose: prints list of znodes (default: false)
\x1b[1mEXAMPLES\x1b[0m
# only prints the current number of children
> child_watch /
# prints num of children along with znodes listing
> child_watch / true | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"child_watch",
"-",
"Watch",
"a",
"path",
"for",
"child",
"changes"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1818-L1838 | train | 213,623 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_diff | def do_diff(self, params):
"""
\x1b[1mNAME\x1b[0m
diff - Display the differences between two paths
\x1b[1mSYNOPSIS\x1b[0m
diff <src> <dst>
\x1b[1mDESCRIPTION\x1b[0m
The output is interpreted as:
-- means the znode is missing in /new-configs
++ means the znode is new in /new-configs
+- means the znode's content differ between /configs and /new-configs
\x1b[1mEXAMPLES\x1b[0m
> diff /configs /new-configs
-- service-x/hosts
++ service-x/hosts.json
+- service-x/params
"""
count = 0
for count, (diff, path) in enumerate(self._zk.diff(params.path_a, params.path_b), 1):
if diff == -1:
self.show_output("-- %s", path)
elif diff == 0:
self.show_output("-+ %s", path)
elif diff == 1:
self.show_output("++ %s", path)
if count == 0:
self.show_output("Branches are equal.") | python | def do_diff(self, params):
"""
\x1b[1mNAME\x1b[0m
diff - Display the differences between two paths
\x1b[1mSYNOPSIS\x1b[0m
diff <src> <dst>
\x1b[1mDESCRIPTION\x1b[0m
The output is interpreted as:
-- means the znode is missing in /new-configs
++ means the znode is new in /new-configs
+- means the znode's content differ between /configs and /new-configs
\x1b[1mEXAMPLES\x1b[0m
> diff /configs /new-configs
-- service-x/hosts
++ service-x/hosts.json
+- service-x/params
"""
count = 0
for count, (diff, path) in enumerate(self._zk.diff(params.path_a, params.path_b), 1):
if diff == -1:
self.show_output("-- %s", path)
elif diff == 0:
self.show_output("-+ %s", path)
elif diff == 1:
self.show_output("++ %s", path)
if count == 0:
self.show_output("Branches are equal.") | [
"def",
"do_diff",
"(",
"self",
",",
"params",
")",
":",
"count",
"=",
"0",
"for",
"count",
",",
"(",
"diff",
",",
"path",
")",
"in",
"enumerate",
"(",
"self",
".",
"_zk",
".",
"diff",
"(",
"params",
".",
"path_a",
",",
"params",
".",
"path_b",
")... | \x1b[1mNAME\x1b[0m
diff - Display the differences between two paths
\x1b[1mSYNOPSIS\x1b[0m
diff <src> <dst>
\x1b[1mDESCRIPTION\x1b[0m
The output is interpreted as:
-- means the znode is missing in /new-configs
++ means the znode is new in /new-configs
+- means the znode's content differ between /configs and /new-configs
\x1b[1mEXAMPLES\x1b[0m
> diff /configs /new-configs
-- service-x/hosts
++ service-x/hosts.json
+- service-x/params | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"diff",
"-",
"Display",
"the",
"differences",
"between",
"two",
"paths"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1847-L1878 | train | 213,624 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_json_valid | def do_json_valid(self, params):
"""
\x1b[1mNAME\x1b[0m
json_valid - Checks znodes for valid JSON
\x1b[1mSYNOPSIS\x1b[0m
json_valid <path> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recurse to all children (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_valid /some/valid/json_znode
yes.
> json_valid /some/invalid/json_znode
no.
> json_valid /configs true
/configs/a: yes.
/configs/b: no.
"""
def check_valid(path, print_path):
result = "no"
value, _ = self._zk.get(path)
if value is not None:
try:
x = json.loads(value)
result = "yes"
except ValueError:
pass
if print_path:
self.show_output("%s: %s.", os.path.basename(path), result)
else:
self.show_output("%s.", result)
if not params.recursive:
check_valid(params.path, False)
else:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
check_valid(cpath, True) | python | def do_json_valid(self, params):
"""
\x1b[1mNAME\x1b[0m
json_valid - Checks znodes for valid JSON
\x1b[1mSYNOPSIS\x1b[0m
json_valid <path> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recurse to all children (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_valid /some/valid/json_znode
yes.
> json_valid /some/invalid/json_znode
no.
> json_valid /configs true
/configs/a: yes.
/configs/b: no.
"""
def check_valid(path, print_path):
result = "no"
value, _ = self._zk.get(path)
if value is not None:
try:
x = json.loads(value)
result = "yes"
except ValueError:
pass
if print_path:
self.show_output("%s: %s.", os.path.basename(path), result)
else:
self.show_output("%s.", result)
if not params.recursive:
check_valid(params.path, False)
else:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
check_valid(cpath, True) | [
"def",
"do_json_valid",
"(",
"self",
",",
"params",
")",
":",
"def",
"check_valid",
"(",
"path",
",",
"print_path",
")",
":",
"result",
"=",
"\"no\"",
"value",
",",
"_",
"=",
"self",
".",
"_zk",
".",
"get",
"(",
"path",
")",
"if",
"value",
"is",
"n... | \x1b[1mNAME\x1b[0m
json_valid - Checks znodes for valid JSON
\x1b[1mSYNOPSIS\x1b[0m
json_valid <path> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recurse to all children (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_valid /some/valid/json_znode
yes.
> json_valid /some/invalid/json_znode
no.
> json_valid /configs true
/configs/a: yes.
/configs/b: no. | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"json_valid",
"-",
"Checks",
"znodes",
"for",
"valid",
"JSON"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1887-L1930 | train | 213,625 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_json_cat | def do_json_cat(self, params):
"""
\x1b[1mNAME\x1b[0m
json_cat - Pretty prints a znode's JSON
\x1b[1mSYNOPSIS\x1b[0m
json_cat <path> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recurse to all children (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_cat /configs/clusters
{
"dc0": {
"network": "10.2.0.0/16",
},
.....
}
> json_cat /configs true
/configs/clusters:
{
"dc0": {
"network": "10.2.0.0/16",
},
.....
}
/configs/dns_servers:
[
"10.2.0.1",
"10.3.0.1"
]
"""
def json_output(path, print_path):
value, _ = self._zk.get(path)
if value is not None:
try:
value = json.dumps(json.loads(value), indent=4)
except ValueError:
pass
if print_path:
self.show_output("%s:\n%s", os.path.basename(path), value)
else:
self.show_output(value)
if not params.recursive:
json_output(params.path, False)
else:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
json_output(cpath, True) | python | def do_json_cat(self, params):
"""
\x1b[1mNAME\x1b[0m
json_cat - Pretty prints a znode's JSON
\x1b[1mSYNOPSIS\x1b[0m
json_cat <path> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recurse to all children (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_cat /configs/clusters
{
"dc0": {
"network": "10.2.0.0/16",
},
.....
}
> json_cat /configs true
/configs/clusters:
{
"dc0": {
"network": "10.2.0.0/16",
},
.....
}
/configs/dns_servers:
[
"10.2.0.1",
"10.3.0.1"
]
"""
def json_output(path, print_path):
value, _ = self._zk.get(path)
if value is not None:
try:
value = json.dumps(json.loads(value), indent=4)
except ValueError:
pass
if print_path:
self.show_output("%s:\n%s", os.path.basename(path), value)
else:
self.show_output(value)
if not params.recursive:
json_output(params.path, False)
else:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
json_output(cpath, True) | [
"def",
"do_json_cat",
"(",
"self",
",",
"params",
")",
":",
"def",
"json_output",
"(",
"path",
",",
"print_path",
")",
":",
"value",
",",
"_",
"=",
"self",
".",
"_zk",
".",
"get",
"(",
"path",
")",
"if",
"value",
"is",
"not",
"None",
":",
"try",
... | \x1b[1mNAME\x1b[0m
json_cat - Pretty prints a znode's JSON
\x1b[1mSYNOPSIS\x1b[0m
json_cat <path> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recurse to all children (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_cat /configs/clusters
{
"dc0": {
"network": "10.2.0.0/16",
},
.....
}
> json_cat /configs true
/configs/clusters:
{
"dc0": {
"network": "10.2.0.0/16",
},
.....
}
/configs/dns_servers:
[
"10.2.0.1",
"10.3.0.1"
] | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"json_cat",
"-",
"Pretty",
"prints",
"a",
"znode",
"s",
"JSON"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L1939-L1992 | train | 213,626 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_json_count_values | def do_json_count_values(self, params):
"""
\x1b[1mNAME\x1b[0m
json_count_values - Gets the frequency of the values associated with the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_count_values <path> <keys> [top] [minfreq] [reverse] [report_errors] [print_path]
\x1b[1mOPTIONS\x1b[0m
* top: number of results to show (0 is all) (default: 0)
* minfreq: minimum frequency to be displayed (default: 1)
* reverse: sort in descending order (default: true)
* report_errors: report bad znodes (default: false)
* print_path: print the path if there are results (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_count_values /configs/primary_service endpoint.host
10.20.0.2 3
10.20.0.4 3
10.20.0.5 3
10.20.0.6 1
10.20.0.7 1
...
"""
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
values = defaultdict(int)
for path, data in path_map.get():
try:
value = Keys.value(json_deserialize(data), params.keys)
values[value] += 1
except BadJSON as ex:
if params.report_errors:
self.show_output("Path %s has bad JSON.", path)
except Keys.Missing as ex:
if params.report_errors:
self.show_output("Path %s is missing key %s.", path, ex)
results = sorted(values.items(), key=lambda item: item[1], reverse=params.reverse)
results = [r for r in results if r[1] >= params.minfreq]
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
if len(results) > 0 and params.print_path:
self.show_output(params.path)
for i in range(start, end):
value, frequency = results[i]
self.show_output("%s = %d", value, frequency)
# if no results were found we call it a failure (i.e.: exit(1) from --run-once)
if len(results) == 0:
return False | python | def do_json_count_values(self, params):
"""
\x1b[1mNAME\x1b[0m
json_count_values - Gets the frequency of the values associated with the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_count_values <path> <keys> [top] [minfreq] [reverse] [report_errors] [print_path]
\x1b[1mOPTIONS\x1b[0m
* top: number of results to show (0 is all) (default: 0)
* minfreq: minimum frequency to be displayed (default: 1)
* reverse: sort in descending order (default: true)
* report_errors: report bad znodes (default: false)
* print_path: print the path if there are results (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_count_values /configs/primary_service endpoint.host
10.20.0.2 3
10.20.0.4 3
10.20.0.5 3
10.20.0.6 1
10.20.0.7 1
...
"""
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
values = defaultdict(int)
for path, data in path_map.get():
try:
value = Keys.value(json_deserialize(data), params.keys)
values[value] += 1
except BadJSON as ex:
if params.report_errors:
self.show_output("Path %s has bad JSON.", path)
except Keys.Missing as ex:
if params.report_errors:
self.show_output("Path %s is missing key %s.", path, ex)
results = sorted(values.items(), key=lambda item: item[1], reverse=params.reverse)
results = [r for r in results if r[1] >= params.minfreq]
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
if len(results) > 0 and params.print_path:
self.show_output(params.path)
for i in range(start, end):
value, frequency = results[i]
self.show_output("%s = %d", value, frequency)
# if no results were found we call it a failure (i.e.: exit(1) from --run-once)
if len(results) == 0:
return False | [
"def",
"do_json_count_values",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"Keys",
".",
"validate",
"(",
"params",
".",
"keys",
")",
"except",
"Keys",
".",
"Bad",
"as",
"ex",
":",
"self",
".",
"show_output",
"(",
"str",
"(",
"ex",
")",
")",
"... | \x1b[1mNAME\x1b[0m
json_count_values - Gets the frequency of the values associated with the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_count_values <path> <keys> [top] [minfreq] [reverse] [report_errors] [print_path]
\x1b[1mOPTIONS\x1b[0m
* top: number of results to show (0 is all) (default: 0)
* minfreq: minimum frequency to be displayed (default: 1)
* reverse: sort in descending order (default: true)
* report_errors: report bad znodes (default: false)
* print_path: print the path if there are results (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_count_values /configs/primary_service endpoint.host
10.20.0.2 3
10.20.0.4 3
10.20.0.5 3
10.20.0.6 1
10.20.0.7 1
... | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"json_count_values",
"-",
"Gets",
"the",
"frequency",
"of",
"the",
"values",
"associated",
"with",
"the",
"given",
"keys"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L2411-L2477 | train | 213,627 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_json_dupes_for_keys | def do_json_dupes_for_keys(self, params):
"""
\x1b[1mNAME\x1b[0m
json_duples_for_keys - Gets the duplicate znodes for the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_dupes_for_keys <path> <keys> [prefix] [report_errors] [first]
\x1b[1mDESCRIPTION\x1b[0m
Znodes with duplicated keys are sorted and all but the first (original) one
are printed.
\x1b[1mOPTIONS\x1b[0m
* prefix: only include matching znodes
* report_errors: turn on error reporting (i.e.: bad JSON in a znode)
* first: print the first, non duplicated, znode too.
\x1b[1mEXAMPLES\x1b[0m
> json_cat /configs/primary_service true
member_0000000186
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
member_0000000187
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
> json_dupes_for_keys /configs/primary_service shard
member_0000000187
"""
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
dupes_by_path = defaultdict(lambda: defaultdict(list))
for path, data in path_map.get():
parent, child = split(path)
if not child.startswith(params.prefix):
continue
try:
value = Keys.value(json_deserialize(data), params.keys)
dupes_by_path[parent][value].append(path)
except BadJSON as ex:
if params.report_errors:
self.show_output("Path %s has bad JSON.", path)
except Keys.Missing as ex:
if params.report_errors:
self.show_output("Path %s is missing key %s.", path, ex)
dupes = []
for _, paths_by_value in dupes_by_path.items():
for _, paths in paths_by_value.items():
if len(paths) > 1:
paths.sort()
paths = paths if params.first else paths[1:]
for path in paths:
idx = bisect.bisect(dupes, path)
dupes.insert(idx, path)
for dup in dupes:
self.show_output(dup)
# if no dupes were found we call it a failure (i.e.: exit(1) from --run-once)
if len(dupes) == 0:
return False | python | def do_json_dupes_for_keys(self, params):
"""
\x1b[1mNAME\x1b[0m
json_duples_for_keys - Gets the duplicate znodes for the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_dupes_for_keys <path> <keys> [prefix] [report_errors] [first]
\x1b[1mDESCRIPTION\x1b[0m
Znodes with duplicated keys are sorted and all but the first (original) one
are printed.
\x1b[1mOPTIONS\x1b[0m
* prefix: only include matching znodes
* report_errors: turn on error reporting (i.e.: bad JSON in a znode)
* first: print the first, non duplicated, znode too.
\x1b[1mEXAMPLES\x1b[0m
> json_cat /configs/primary_service true
member_0000000186
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
member_0000000187
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
> json_dupes_for_keys /configs/primary_service shard
member_0000000187
"""
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
dupes_by_path = defaultdict(lambda: defaultdict(list))
for path, data in path_map.get():
parent, child = split(path)
if not child.startswith(params.prefix):
continue
try:
value = Keys.value(json_deserialize(data), params.keys)
dupes_by_path[parent][value].append(path)
except BadJSON as ex:
if params.report_errors:
self.show_output("Path %s has bad JSON.", path)
except Keys.Missing as ex:
if params.report_errors:
self.show_output("Path %s is missing key %s.", path, ex)
dupes = []
for _, paths_by_value in dupes_by_path.items():
for _, paths in paths_by_value.items():
if len(paths) > 1:
paths.sort()
paths = paths if params.first else paths[1:]
for path in paths:
idx = bisect.bisect(dupes, path)
dupes.insert(idx, path)
for dup in dupes:
self.show_output(dup)
# if no dupes were found we call it a failure (i.e.: exit(1) from --run-once)
if len(dupes) == 0:
return False | [
"def",
"do_json_dupes_for_keys",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"Keys",
".",
"validate",
"(",
"params",
".",
"keys",
")",
"except",
"Keys",
".",
"Bad",
"as",
"ex",
":",
"self",
".",
"show_output",
"(",
"str",
"(",
"ex",
")",
")",
... | \x1b[1mNAME\x1b[0m
json_duples_for_keys - Gets the duplicate znodes for the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_dupes_for_keys <path> <keys> [prefix] [report_errors] [first]
\x1b[1mDESCRIPTION\x1b[0m
Znodes with duplicated keys are sorted and all but the first (original) one
are printed.
\x1b[1mOPTIONS\x1b[0m
* prefix: only include matching znodes
* report_errors: turn on error reporting (i.e.: bad JSON in a znode)
* first: print the first, non duplicated, znode too.
\x1b[1mEXAMPLES\x1b[0m
> json_cat /configs/primary_service true
member_0000000186
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
member_0000000187
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
> json_dupes_for_keys /configs/primary_service shard
member_0000000187 | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"json_duples_for_keys",
"-",
"Gets",
"the",
"duplicate",
"znodes",
"for",
"the",
"given",
"keys"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L2503-L2588 | train | 213,628 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_edit | def do_edit(self, params):
"""
\x1b[1mNAME\x1b[0m
edit - Opens up an editor to modify and update a znode.
\x1b[1mSYNOPSIS\x1b[0m
edit <path>
\x1b[1mDESCRIPTION\x1b[0m
If the content has not changed, the znode won't be updated.
$EDITOR must be set for zk-shell to find your editor.
\x1b[1mEXAMPLES\x1b[0m
# make sure $EDITOR is set in your shell
> edit /configs/webservers/primary
# change something and save
> get /configs/webservers/primary
# updated content
"""
if os.getuid() == 0:
self.show_output("edit cannot be run as root.")
return
editor = os.getenv("EDITOR", os.getenv("VISUAL", "/usr/bin/vi"))
if editor is None:
self.show_output("No editor found, please set $EDITOR")
return
editor = which(editor)
if not editor:
self.show_output("Cannot find executable editor, please set $EDITOR")
return
st = os.stat(editor)
if (st.st_mode & statlib.S_ISUID) or (st.st_mode & statlib.S_ISUID):
self.show_output("edit cannot use setuid/setgid binaries.")
return
# copy content to tempfile
value, stat = self._zk.get(params.path)
_, tmppath = tempfile.mkstemp()
with open(tmppath, "w") as fh:
fh.write(value if value else "")
# launch editor
rv = os.system("%s %s" % (editor, tmppath))
if rv != 0:
self.show_output("%s did not exit successfully" % editor)
try:
os.unlink(tmppath)
except OSError: pass
return
# did it change? if so, save it
with open(tmppath, "r") as fh:
newvalue = fh.read()
if newvalue != value:
self.set(params.path, decoded(newvalue), stat.version)
try:
os.unlink(tmppath)
except OSError: pass | python | def do_edit(self, params):
"""
\x1b[1mNAME\x1b[0m
edit - Opens up an editor to modify and update a znode.
\x1b[1mSYNOPSIS\x1b[0m
edit <path>
\x1b[1mDESCRIPTION\x1b[0m
If the content has not changed, the znode won't be updated.
$EDITOR must be set for zk-shell to find your editor.
\x1b[1mEXAMPLES\x1b[0m
# make sure $EDITOR is set in your shell
> edit /configs/webservers/primary
# change something and save
> get /configs/webservers/primary
# updated content
"""
if os.getuid() == 0:
self.show_output("edit cannot be run as root.")
return
editor = os.getenv("EDITOR", os.getenv("VISUAL", "/usr/bin/vi"))
if editor is None:
self.show_output("No editor found, please set $EDITOR")
return
editor = which(editor)
if not editor:
self.show_output("Cannot find executable editor, please set $EDITOR")
return
st = os.stat(editor)
if (st.st_mode & statlib.S_ISUID) or (st.st_mode & statlib.S_ISUID):
self.show_output("edit cannot use setuid/setgid binaries.")
return
# copy content to tempfile
value, stat = self._zk.get(params.path)
_, tmppath = tempfile.mkstemp()
with open(tmppath, "w") as fh:
fh.write(value if value else "")
# launch editor
rv = os.system("%s %s" % (editor, tmppath))
if rv != 0:
self.show_output("%s did not exit successfully" % editor)
try:
os.unlink(tmppath)
except OSError: pass
return
# did it change? if so, save it
with open(tmppath, "r") as fh:
newvalue = fh.read()
if newvalue != value:
self.set(params.path, decoded(newvalue), stat.version)
try:
os.unlink(tmppath)
except OSError: pass | [
"def",
"do_edit",
"(",
"self",
",",
"params",
")",
":",
"if",
"os",
".",
"getuid",
"(",
")",
"==",
"0",
":",
"self",
".",
"show_output",
"(",
"\"edit cannot be run as root.\"",
")",
"return",
"editor",
"=",
"os",
".",
"getenv",
"(",
"\"EDITOR\"",
",",
... | \x1b[1mNAME\x1b[0m
edit - Opens up an editor to modify and update a znode.
\x1b[1mSYNOPSIS\x1b[0m
edit <path>
\x1b[1mDESCRIPTION\x1b[0m
If the content has not changed, the znode won't be updated.
$EDITOR must be set for zk-shell to find your editor.
\x1b[1mEXAMPLES\x1b[0m
# make sure $EDITOR is set in your shell
> edit /configs/webservers/primary
# change something and save
> get /configs/webservers/primary
# updated content | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"edit",
"-",
"Opens",
"up",
"an",
"editor",
"to",
"modify",
"and",
"update",
"a",
"znode",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L2602-L2664 | train | 213,629 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_loop | def do_loop(self, params):
"""
\x1b[1mNAME\x1b[0m
loop - Runs commands in a loop
\x1b[1mSYNOPSIS\x1b[0m
loop <repeat> <pause> <cmd1> <cmd2> ... <cmdN>
\x1b[1mDESCRIPTION\x1b[0m
Runs <cmds> <repeat> times (0 means forever), with a pause of <pause> secs inbetween
each <cmd> (0 means no pause).
\x1b[1mEXAMPLES\x1b[0m
> loop 3 0 "get /foo"
...
> loop 3 0 "get /foo" "get /bar"
...
"""
repeat = params.repeat
if repeat < 0:
self.show_output("<repeat> must be >= 0.")
return
pause = params.pause
if pause < 0:
self.show_output("<pause> must be >= 0.")
return
cmds = params.cmds
i = 0
with self.transitions_disabled():
while True:
for cmd in cmds:
try:
self.onecmd(cmd)
except Exception as ex:
self.show_output("Command failed: %s.", ex)
if pause > 0.0:
time.sleep(pause)
i += 1
if repeat > 0 and i >= repeat:
break | python | def do_loop(self, params):
"""
\x1b[1mNAME\x1b[0m
loop - Runs commands in a loop
\x1b[1mSYNOPSIS\x1b[0m
loop <repeat> <pause> <cmd1> <cmd2> ... <cmdN>
\x1b[1mDESCRIPTION\x1b[0m
Runs <cmds> <repeat> times (0 means forever), with a pause of <pause> secs inbetween
each <cmd> (0 means no pause).
\x1b[1mEXAMPLES\x1b[0m
> loop 3 0 "get /foo"
...
> loop 3 0 "get /foo" "get /bar"
...
"""
repeat = params.repeat
if repeat < 0:
self.show_output("<repeat> must be >= 0.")
return
pause = params.pause
if pause < 0:
self.show_output("<pause> must be >= 0.")
return
cmds = params.cmds
i = 0
with self.transitions_disabled():
while True:
for cmd in cmds:
try:
self.onecmd(cmd)
except Exception as ex:
self.show_output("Command failed: %s.", ex)
if pause > 0.0:
time.sleep(pause)
i += 1
if repeat > 0 and i >= repeat:
break | [
"def",
"do_loop",
"(",
"self",
",",
"params",
")",
":",
"repeat",
"=",
"params",
".",
"repeat",
"if",
"repeat",
"<",
"0",
":",
"self",
".",
"show_output",
"(",
"\"<repeat> must be >= 0.\"",
")",
"return",
"pause",
"=",
"params",
".",
"pause",
"if",
"paus... | \x1b[1mNAME\x1b[0m
loop - Runs commands in a loop
\x1b[1mSYNOPSIS\x1b[0m
loop <repeat> <pause> <cmd1> <cmd2> ... <cmdN>
\x1b[1mDESCRIPTION\x1b[0m
Runs <cmds> <repeat> times (0 means forever), with a pause of <pause> secs inbetween
each <cmd> (0 means no pause).
\x1b[1mEXAMPLES\x1b[0m
> loop 3 0 "get /foo"
...
> loop 3 0 "get /foo" "get /bar"
... | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"loop",
"-",
"Runs",
"commands",
"in",
"a",
"loop"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L2670-L2713 | train | 213,630 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_session_endpoint | def do_session_endpoint(self, params):
"""
\x1b[1mNAME\x1b[0m
session_endpoint - Gets the session's IP endpoints
\x1b[1mSYNOPSIS\x1b[0m
session_endpoint <session> <hosts> [reverse_lookup]
\x1b[1mDESCRIPTION\x1b[0m
where hosts is a list of hosts in the host1[:port1][,host2[:port2]],... form
\x1b[1mOPTIONS\x1b[0m
* reverse_lookup: convert IPs back to hostnames (default: false)
\x1b[1mEXAMPLES\x1b[0m
> session_endpoint 0xa4788b919450e6 10.0.0.1,10.0.0.2,10.0.0.3
10.3.2.12:54250 10.0.0.2:2181
"""
if invalid_hosts(params.hosts):
self.show_output("List of hosts has the wrong syntax.")
return
try:
info_by_id = self._zk.sessions_info(params.hosts)
except XClient.CmdFailed as ex:
self.show_output(str(ex))
return
info = info_by_id.get(params.session, None)
if info is None:
self.show_output("No session info for %s.", params.session)
else:
self.show_output("%s", info.resolved_endpoints if params.reverse else info.endpoints) | python | def do_session_endpoint(self, params):
"""
\x1b[1mNAME\x1b[0m
session_endpoint - Gets the session's IP endpoints
\x1b[1mSYNOPSIS\x1b[0m
session_endpoint <session> <hosts> [reverse_lookup]
\x1b[1mDESCRIPTION\x1b[0m
where hosts is a list of hosts in the host1[:port1][,host2[:port2]],... form
\x1b[1mOPTIONS\x1b[0m
* reverse_lookup: convert IPs back to hostnames (default: false)
\x1b[1mEXAMPLES\x1b[0m
> session_endpoint 0xa4788b919450e6 10.0.0.1,10.0.0.2,10.0.0.3
10.3.2.12:54250 10.0.0.2:2181
"""
if invalid_hosts(params.hosts):
self.show_output("List of hosts has the wrong syntax.")
return
try:
info_by_id = self._zk.sessions_info(params.hosts)
except XClient.CmdFailed as ex:
self.show_output(str(ex))
return
info = info_by_id.get(params.session, None)
if info is None:
self.show_output("No session info for %s.", params.session)
else:
self.show_output("%s", info.resolved_endpoints if params.reverse else info.endpoints) | [
"def",
"do_session_endpoint",
"(",
"self",
",",
"params",
")",
":",
"if",
"invalid_hosts",
"(",
"params",
".",
"hosts",
")",
":",
"self",
".",
"show_output",
"(",
"\"List of hosts has the wrong syntax.\"",
")",
"return",
"try",
":",
"info_by_id",
"=",
"self",
... | \x1b[1mNAME\x1b[0m
session_endpoint - Gets the session's IP endpoints
\x1b[1mSYNOPSIS\x1b[0m
session_endpoint <session> <hosts> [reverse_lookup]
\x1b[1mDESCRIPTION\x1b[0m
where hosts is a list of hosts in the host1[:port1][,host2[:port2]],... form
\x1b[1mOPTIONS\x1b[0m
* reverse_lookup: convert IPs back to hostnames (default: false)
\x1b[1mEXAMPLES\x1b[0m
> session_endpoint 0xa4788b919450e6 10.0.0.1,10.0.0.2,10.0.0.3
10.3.2.12:54250 10.0.0.2:2181 | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"session_endpoint",
"-",
"Gets",
"the",
"session",
"s",
"IP",
"endpoints"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L2799-L2832 | train | 213,631 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_fill | def do_fill(self, params):
"""
\x1b[1mNAME\x1b[0m
fill - Fills a znode with the given value
\x1b[1mSYNOPSIS\x1b[0m
fill <path> <char> <count>
\x1b[1mEXAMPLES\x1b[0m
> fill /some/znode X 1048576
"""
self._zk.set(params.path, decoded(params.val * params.repeat)) | python | def do_fill(self, params):
"""
\x1b[1mNAME\x1b[0m
fill - Fills a znode with the given value
\x1b[1mSYNOPSIS\x1b[0m
fill <path> <char> <count>
\x1b[1mEXAMPLES\x1b[0m
> fill /some/znode X 1048576
"""
self._zk.set(params.path, decoded(params.val * params.repeat)) | [
"def",
"do_fill",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"_zk",
".",
"set",
"(",
"params",
".",
"path",
",",
"decoded",
"(",
"params",
".",
"val",
"*",
"params",
".",
"repeat",
")",
")"
] | \x1b[1mNAME\x1b[0m
fill - Fills a znode with the given value
\x1b[1mSYNOPSIS\x1b[0m
fill <path> <char> <count>
\x1b[1mEXAMPLES\x1b[0m
> fill /some/znode X 1048576 | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"fill",
"-",
"Fills",
"a",
"znode",
"with",
"the",
"given",
"value"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L2843-L2855 | train | 213,632 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_time | def do_time(self, params):
"""
\x1b[1mNAME\x1b[0m
time - Measures elapsed seconds after running commands
\x1b[1mSYNOPSIS\x1b[0m
time <cmd1> <cmd2> ... <cmdN>
\x1b[1mEXAMPLES\x1b[0m
> time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"'
Took 0.05585 seconds
"""
start = time.time()
for cmd in params.cmds:
try:
self.onecmd(cmd)
except Exception as ex:
self.show_output("Command failed: %s.", ex)
elapsed = "{0:.5f}".format(time.time() - start)
self.show_output("Took %s seconds" % elapsed) | python | def do_time(self, params):
"""
\x1b[1mNAME\x1b[0m
time - Measures elapsed seconds after running commands
\x1b[1mSYNOPSIS\x1b[0m
time <cmd1> <cmd2> ... <cmdN>
\x1b[1mEXAMPLES\x1b[0m
> time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"'
Took 0.05585 seconds
"""
start = time.time()
for cmd in params.cmds:
try:
self.onecmd(cmd)
except Exception as ex:
self.show_output("Command failed: %s.", ex)
elapsed = "{0:.5f}".format(time.time() - start)
self.show_output("Took %s seconds" % elapsed) | [
"def",
"do_time",
"(",
"self",
",",
"params",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"cmd",
"in",
"params",
".",
"cmds",
":",
"try",
":",
"self",
".",
"onecmd",
"(",
"cmd",
")",
"except",
"Exception",
"as",
"ex",
":",
"self... | \x1b[1mNAME\x1b[0m
time - Measures elapsed seconds after running commands
\x1b[1mSYNOPSIS\x1b[0m
time <cmd1> <cmd2> ... <cmdN>
\x1b[1mEXAMPLES\x1b[0m
> time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"'
Took 0.05585 seconds | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"time",
"-",
"Measures",
"elapsed",
"seconds",
"after",
"running",
"commands"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L2883-L2903 | train | 213,633 |
rgs1/zk_shell | zk_shell/shell.py | Shell.do_echo | def do_echo(self, params):
"""
\x1b[1mNAME\x1b[0m
echo - displays formatted data
\x1b[1mSYNOPSIS\x1b[0m
echo <fmtstr> [cmd1] [cmd2] ... [cmdN]
\x1b[1mEXAMPLES\x1b[0m
> echo hello
hello
> echo 'The value of /foo is %s' 'get /foo'
bar
"""
values = []
with self.output_context() as context:
for cmd in params.cmds:
rv = self.onecmd(cmd)
val = "" if rv is False else context.value.rstrip("\n")
values.append(val)
context.reset()
try:
self.show_output(params.fmtstr, *values)
except TypeError:
self.show_output("Bad format string or missing arguments.") | python | def do_echo(self, params):
"""
\x1b[1mNAME\x1b[0m
echo - displays formatted data
\x1b[1mSYNOPSIS\x1b[0m
echo <fmtstr> [cmd1] [cmd2] ... [cmdN]
\x1b[1mEXAMPLES\x1b[0m
> echo hello
hello
> echo 'The value of /foo is %s' 'get /foo'
bar
"""
values = []
with self.output_context() as context:
for cmd in params.cmds:
rv = self.onecmd(cmd)
val = "" if rv is False else context.value.rstrip("\n")
values.append(val)
context.reset()
try:
self.show_output(params.fmtstr, *values)
except TypeError:
self.show_output("Bad format string or missing arguments.") | [
"def",
"do_echo",
"(",
"self",
",",
"params",
")",
":",
"values",
"=",
"[",
"]",
"with",
"self",
".",
"output_context",
"(",
")",
"as",
"context",
":",
"for",
"cmd",
"in",
"params",
".",
"cmds",
":",
"rv",
"=",
"self",
".",
"onecmd",
"(",
"cmd",
... | \x1b[1mNAME\x1b[0m
echo - displays formatted data
\x1b[1mSYNOPSIS\x1b[0m
echo <fmtstr> [cmd1] [cmd2] ... [cmdN]
\x1b[1mEXAMPLES\x1b[0m
> echo hello
hello
> echo 'The value of /foo is %s' 'get /foo'
bar | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"echo",
"-",
"displays",
"formatted",
"data"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L2973-L2999 | train | 213,634 |
rgs1/zk_shell | zk_shell/xclient.py | connected_socket | def connected_socket(address, timeout=3):
""" yields a connected socket """
sock = socket.create_connection(address, timeout)
yield sock
sock.close() | python | def connected_socket(address, timeout=3):
""" yields a connected socket """
sock = socket.create_connection(address, timeout)
yield sock
sock.close() | [
"def",
"connected_socket",
"(",
"address",
",",
"timeout",
"=",
"3",
")",
":",
"sock",
"=",
"socket",
".",
"create_connection",
"(",
"address",
",",
"timeout",
")",
"yield",
"sock",
"sock",
".",
"close",
"(",
")"
] | yields a connected socket | [
"yields",
"a",
"connected",
"socket"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L22-L26 | train | 213,635 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.get_bytes | def get_bytes(self, *args, **kwargs):
""" no string decoding performed """
return super(XClient, self).get(*args, **kwargs) | python | def get_bytes(self, *args, **kwargs):
""" no string decoding performed """
return super(XClient, self).get(*args, **kwargs) | [
"def",
"get_bytes",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"XClient",
",",
"self",
")",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | no string decoding performed | [
"no",
"string",
"decoding",
"performed"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L159-L161 | train | 213,636 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.get_acls_recursive | def get_acls_recursive(self, path, depth, include_ephemerals):
"""A recursive generator wrapper for get_acls
:param path: path from which to start
:param depth: depth of the recursion (-1 no recursion, 0 means no limit)
:param include_ephemerals: get ACLs for ephemerals too
"""
yield path, self.get_acls(path)[0]
if depth == -1:
return
for tpath, _ in self.tree(path, depth, full_path=True):
try:
acls, stat = self.get_acls(tpath)
except NoNodeError:
continue
if not include_ephemerals and stat.ephemeralOwner != 0:
continue
yield tpath, acls | python | def get_acls_recursive(self, path, depth, include_ephemerals):
"""A recursive generator wrapper for get_acls
:param path: path from which to start
:param depth: depth of the recursion (-1 no recursion, 0 means no limit)
:param include_ephemerals: get ACLs for ephemerals too
"""
yield path, self.get_acls(path)[0]
if depth == -1:
return
for tpath, _ in self.tree(path, depth, full_path=True):
try:
acls, stat = self.get_acls(tpath)
except NoNodeError:
continue
if not include_ephemerals and stat.ephemeralOwner != 0:
continue
yield tpath, acls | [
"def",
"get_acls_recursive",
"(",
"self",
",",
"path",
",",
"depth",
",",
"include_ephemerals",
")",
":",
"yield",
"path",
",",
"self",
".",
"get_acls",
"(",
"path",
")",
"[",
"0",
"]",
"if",
"depth",
"==",
"-",
"1",
":",
"return",
"for",
"tpath",
",... | A recursive generator wrapper for get_acls
:param path: path from which to start
:param depth: depth of the recursion (-1 no recursion, 0 means no limit)
:param include_ephemerals: get ACLs for ephemerals too | [
"A",
"recursive",
"generator",
"wrapper",
"for",
"get_acls"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L186-L207 | train | 213,637 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.find | def find(self, path, match, flags):
""" find every matching child path under path """
try:
match = re.compile(match, flags)
except sre_constants.error as ex:
print("Bad regexp: %s" % (ex))
return
offset = len(path)
for cpath in Tree(self, path).get():
if match.search(cpath[offset:]):
yield cpath | python | def find(self, path, match, flags):
""" find every matching child path under path """
try:
match = re.compile(match, flags)
except sre_constants.error as ex:
print("Bad regexp: %s" % (ex))
return
offset = len(path)
for cpath in Tree(self, path).get():
if match.search(cpath[offset:]):
yield cpath | [
"def",
"find",
"(",
"self",
",",
"path",
",",
"match",
",",
"flags",
")",
":",
"try",
":",
"match",
"=",
"re",
".",
"compile",
"(",
"match",
",",
"flags",
")",
"except",
"sre_constants",
".",
"error",
"as",
"ex",
":",
"print",
"(",
"\"Bad regexp: %s\... | find every matching child path under path | [
"find",
"every",
"matching",
"child",
"path",
"under",
"path"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L209-L220 | train | 213,638 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.grep | def grep(self, path, content, flags):
""" grep every child path under path for content """
try:
match = re.compile(content, flags)
except sre_constants.error as ex:
print("Bad regexp: %s" % (ex))
return
for gpath, matches in self.do_grep(path, match):
yield (gpath, matches) | python | def grep(self, path, content, flags):
""" grep every child path under path for content """
try:
match = re.compile(content, flags)
except sre_constants.error as ex:
print("Bad regexp: %s" % (ex))
return
for gpath, matches in self.do_grep(path, match):
yield (gpath, matches) | [
"def",
"grep",
"(",
"self",
",",
"path",
",",
"content",
",",
"flags",
")",
":",
"try",
":",
"match",
"=",
"re",
".",
"compile",
"(",
"content",
",",
"flags",
")",
"except",
"sre_constants",
".",
"error",
"as",
"ex",
":",
"print",
"(",
"\"Bad regexp:... | grep every child path under path for content | [
"grep",
"every",
"child",
"path",
"under",
"path",
"for",
"content"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L222-L231 | train | 213,639 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.do_grep | def do_grep(self, path, match):
""" grep's work horse """
try:
children = self.get_children(path)
except (NoNodeError, NoAuthError):
children = []
for child in children:
full_path = os.path.join(path, child)
try:
value, _ = self.get(full_path)
except (NoNodeError, NoAuthError):
value = ""
if value is not None:
matches = [line for line in value.split("\n") if match.search(line)]
if len(matches) > 0:
yield (full_path, matches)
for mpath, matches in self.do_grep(full_path, match):
yield (mpath, matches) | python | def do_grep(self, path, match):
""" grep's work horse """
try:
children = self.get_children(path)
except (NoNodeError, NoAuthError):
children = []
for child in children:
full_path = os.path.join(path, child)
try:
value, _ = self.get(full_path)
except (NoNodeError, NoAuthError):
value = ""
if value is not None:
matches = [line for line in value.split("\n") if match.search(line)]
if len(matches) > 0:
yield (full_path, matches)
for mpath, matches in self.do_grep(full_path, match):
yield (mpath, matches) | [
"def",
"do_grep",
"(",
"self",
",",
"path",
",",
"match",
")",
":",
"try",
":",
"children",
"=",
"self",
".",
"get_children",
"(",
"path",
")",
"except",
"(",
"NoNodeError",
",",
"NoAuthError",
")",
":",
"children",
"=",
"[",
"]",
"for",
"child",
"in... | grep's work horse | [
"grep",
"s",
"work",
"horse"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L233-L253 | train | 213,640 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.tree | def tree(self, path, max_depth, full_path=False, include_stat=False):
"""DFS generator which starts from a given path and goes up to a max depth.
:param path: path from which the DFS will start
:param max_depth: max depth of DFS (0 means no limit)
:param full_path: should the full path of the child node be returned
:param include_stat: return the child Znode's stat along with the name & level
"""
for child_level_stat in self.do_tree(path, max_depth, 0, full_path, include_stat):
yield child_level_stat | python | def tree(self, path, max_depth, full_path=False, include_stat=False):
"""DFS generator which starts from a given path and goes up to a max depth.
:param path: path from which the DFS will start
:param max_depth: max depth of DFS (0 means no limit)
:param full_path: should the full path of the child node be returned
:param include_stat: return the child Znode's stat along with the name & level
"""
for child_level_stat in self.do_tree(path, max_depth, 0, full_path, include_stat):
yield child_level_stat | [
"def",
"tree",
"(",
"self",
",",
"path",
",",
"max_depth",
",",
"full_path",
"=",
"False",
",",
"include_stat",
"=",
"False",
")",
":",
"for",
"child_level_stat",
"in",
"self",
".",
"do_tree",
"(",
"path",
",",
"max_depth",
",",
"0",
",",
"full_path",
... | DFS generator which starts from a given path and goes up to a max depth.
:param path: path from which the DFS will start
:param max_depth: max depth of DFS (0 means no limit)
:param full_path: should the full path of the child node be returned
:param include_stat: return the child Znode's stat along with the name & level | [
"DFS",
"generator",
"which",
"starts",
"from",
"a",
"given",
"path",
"and",
"goes",
"up",
"to",
"a",
"max",
"depth",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L270-L279 | train | 213,641 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.do_tree | def do_tree(self, path, max_depth, level, full_path, include_stat):
""" tree's work horse """
try:
children = self.get_children(path)
except (NoNodeError, NoAuthError):
children = []
for child in children:
cpath = os.path.join(path, child) if full_path else child
if include_stat:
yield cpath, level, self.stat(os.path.join(path, child))
else:
yield cpath, level
if max_depth == 0 or level + 1 < max_depth:
cpath = os.path.join(path, child)
for rchild_rlevel_rstat in self.do_tree(cpath, max_depth, level + 1, full_path, include_stat):
yield rchild_rlevel_rstat | python | def do_tree(self, path, max_depth, level, full_path, include_stat):
""" tree's work horse """
try:
children = self.get_children(path)
except (NoNodeError, NoAuthError):
children = []
for child in children:
cpath = os.path.join(path, child) if full_path else child
if include_stat:
yield cpath, level, self.stat(os.path.join(path, child))
else:
yield cpath, level
if max_depth == 0 or level + 1 < max_depth:
cpath = os.path.join(path, child)
for rchild_rlevel_rstat in self.do_tree(cpath, max_depth, level + 1, full_path, include_stat):
yield rchild_rlevel_rstat | [
"def",
"do_tree",
"(",
"self",
",",
"path",
",",
"max_depth",
",",
"level",
",",
"full_path",
",",
"include_stat",
")",
":",
"try",
":",
"children",
"=",
"self",
".",
"get_children",
"(",
"path",
")",
"except",
"(",
"NoNodeError",
",",
"NoAuthError",
")"... | tree's work horse | [
"tree",
"s",
"work",
"horse"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L281-L298 | train | 213,642 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.equal | def equal(self, path_a, path_b):
"""
compare if a and b have the same bytes
"""
content_a, _ = self.get_bytes(path_a)
content_b, _ = self.get_bytes(path_b)
return content_a == content_b | python | def equal(self, path_a, path_b):
"""
compare if a and b have the same bytes
"""
content_a, _ = self.get_bytes(path_a)
content_b, _ = self.get_bytes(path_b)
return content_a == content_b | [
"def",
"equal",
"(",
"self",
",",
"path_a",
",",
"path_b",
")",
":",
"content_a",
",",
"_",
"=",
"self",
".",
"get_bytes",
"(",
"path_a",
")",
"content_b",
",",
"_",
"=",
"self",
".",
"get_bytes",
"(",
"path_b",
")",
"return",
"content_a",
"==",
"con... | compare if a and b have the same bytes | [
"compare",
"if",
"a",
"and",
"b",
"have",
"the",
"same",
"bytes"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L350-L357 | train | 213,643 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.stat | def stat(self, path):
""" safely gets the Znode's Stat """
try:
stat = self.exists(str(path))
except (NoNodeError, NoAuthError):
stat = None
return stat | python | def stat(self, path):
""" safely gets the Znode's Stat """
try:
stat = self.exists(str(path))
except (NoNodeError, NoAuthError):
stat = None
return stat | [
"def",
"stat",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"stat",
"=",
"self",
".",
"exists",
"(",
"str",
"(",
"path",
")",
")",
"except",
"(",
"NoNodeError",
",",
"NoAuthError",
")",
":",
"stat",
"=",
"None",
"return",
"stat"
] | safely gets the Znode's Stat | [
"safely",
"gets",
"the",
"Znode",
"s",
"Stat"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L359-L365 | train | 213,644 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.reconnect | def reconnect(self):
""" forces a reconnect by shutting down the connected socket
return True if the reconnect happened, False otherwise
"""
state_change_event = self.handler.event_object()
def listener(state):
if state is KazooState.SUSPENDED:
state_change_event.set()
self.add_listener(listener)
self._connection._socket.shutdown(socket.SHUT_RDWR)
state_change_event.wait(1)
if not state_change_event.is_set():
return False
# wait until we are back
while not self.connected:
time.sleep(0.1)
return True | python | def reconnect(self):
""" forces a reconnect by shutting down the connected socket
return True if the reconnect happened, False otherwise
"""
state_change_event = self.handler.event_object()
def listener(state):
if state is KazooState.SUSPENDED:
state_change_event.set()
self.add_listener(listener)
self._connection._socket.shutdown(socket.SHUT_RDWR)
state_change_event.wait(1)
if not state_change_event.is_set():
return False
# wait until we are back
while not self.connected:
time.sleep(0.1)
return True | [
"def",
"reconnect",
"(",
"self",
")",
":",
"state_change_event",
"=",
"self",
".",
"handler",
".",
"event_object",
"(",
")",
"def",
"listener",
"(",
"state",
")",
":",
"if",
"state",
"is",
"KazooState",
".",
"SUSPENDED",
":",
"state_change_event",
".",
"se... | forces a reconnect by shutting down the connected socket
return True if the reconnect happened, False otherwise | [
"forces",
"a",
"reconnect",
"by",
"shutting",
"down",
"the",
"connected",
"socket",
"return",
"True",
"if",
"the",
"reconnect",
"happened",
"False",
"otherwise"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L439-L461 | train | 213,645 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.dump_by_server | def dump_by_server(self, hosts):
"""Returns the output of dump for each server.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of ((server_ip, port), ClientInfo).
"""
dump_by_endpoint = {}
for endpoint in self._to_endpoints(hosts):
try:
out = self.cmd([endpoint], "dump")
except self.CmdFailed as ex:
out = ""
dump_by_endpoint[endpoint] = out
return dump_by_endpoint | python | def dump_by_server(self, hosts):
"""Returns the output of dump for each server.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of ((server_ip, port), ClientInfo).
"""
dump_by_endpoint = {}
for endpoint in self._to_endpoints(hosts):
try:
out = self.cmd([endpoint], "dump")
except self.CmdFailed as ex:
out = ""
dump_by_endpoint[endpoint] = out
return dump_by_endpoint | [
"def",
"dump_by_server",
"(",
"self",
",",
"hosts",
")",
":",
"dump_by_endpoint",
"=",
"{",
"}",
"for",
"endpoint",
"in",
"self",
".",
"_to_endpoints",
"(",
"hosts",
")",
":",
"try",
":",
"out",
"=",
"self",
".",
"cmd",
"(",
"[",
"endpoint",
"]",
","... | Returns the output of dump for each server.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of ((server_ip, port), ClientInfo). | [
"Returns",
"the",
"output",
"of",
"dump",
"for",
"each",
"server",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L463-L479 | train | 213,646 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.ephemerals_info | def ephemerals_info(self, hosts):
"""Returns ClientInfo per path.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (path, ClientInfo).
"""
info_by_path, info_by_id = {}, {}
for server_endpoint, dump in self.dump_by_server(hosts).items():
server_ip, server_port = server_endpoint
sid = None
for line in dump.split("\n"):
mat = self.SESSION_REGEX.match(line)
if mat:
sid = mat.group(1)
continue
mat = self.PATH_REGEX.match(line)
if mat:
info = info_by_id.get(sid, None)
if info is None:
info = info_by_id[sid] = ClientInfo(sid)
info_by_path[mat.group(1)] = info
continue
mat = self.IP_PORT_REGEX.match(line)
if mat:
ip, port, sid = mat.groups()
if sid not in info_by_id:
continue
info_by_id[sid](ip, int(port), server_ip, server_port)
return info_by_path | python | def ephemerals_info(self, hosts):
"""Returns ClientInfo per path.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (path, ClientInfo).
"""
info_by_path, info_by_id = {}, {}
for server_endpoint, dump in self.dump_by_server(hosts).items():
server_ip, server_port = server_endpoint
sid = None
for line in dump.split("\n"):
mat = self.SESSION_REGEX.match(line)
if mat:
sid = mat.group(1)
continue
mat = self.PATH_REGEX.match(line)
if mat:
info = info_by_id.get(sid, None)
if info is None:
info = info_by_id[sid] = ClientInfo(sid)
info_by_path[mat.group(1)] = info
continue
mat = self.IP_PORT_REGEX.match(line)
if mat:
ip, port, sid = mat.groups()
if sid not in info_by_id:
continue
info_by_id[sid](ip, int(port), server_ip, server_port)
return info_by_path | [
"def",
"ephemerals_info",
"(",
"self",
",",
"hosts",
")",
":",
"info_by_path",
",",
"info_by_id",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"server_endpoint",
",",
"dump",
"in",
"self",
".",
"dump_by_server",
"(",
"hosts",
")",
".",
"items",
"(",
")",
":",
... | Returns ClientInfo per path.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (path, ClientInfo). | [
"Returns",
"ClientInfo",
"per",
"path",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L481-L514 | train | 213,647 |
rgs1/zk_shell | zk_shell/xclient.py | XClient.sessions_info | def sessions_info(self, hosts):
"""Returns ClientInfo per session.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (session_id, ClientInfo).
"""
info_by_id = {}
for server_endpoint, dump in self.dump_by_server(hosts).items():
server_ip, server_port = server_endpoint
for line in dump.split("\n"):
mat = self.IP_PORT_REGEX.match(line)
if mat is None:
continue
ip, port, sid = mat.groups()
info_by_id[sid] = ClientInfo(sid, ip, port, server_ip, server_port)
return info_by_id | python | def sessions_info(self, hosts):
"""Returns ClientInfo per session.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (session_id, ClientInfo).
"""
info_by_id = {}
for server_endpoint, dump in self.dump_by_server(hosts).items():
server_ip, server_port = server_endpoint
for line in dump.split("\n"):
mat = self.IP_PORT_REGEX.match(line)
if mat is None:
continue
ip, port, sid = mat.groups()
info_by_id[sid] = ClientInfo(sid, ip, port, server_ip, server_port)
return info_by_id | [
"def",
"sessions_info",
"(",
"self",
",",
"hosts",
")",
":",
"info_by_id",
"=",
"{",
"}",
"for",
"server_endpoint",
",",
"dump",
"in",
"self",
".",
"dump_by_server",
"(",
"hosts",
")",
".",
"items",
"(",
")",
":",
"server_ip",
",",
"server_port",
"=",
... | Returns ClientInfo per session.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (session_id, ClientInfo). | [
"Returns",
"ClientInfo",
"per",
"session",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L516-L534 | train | 213,648 |
rgs1/zk_shell | zk_shell/watcher.py | ChildWatcher.update | def update(self, path, verbose=False):
""" if the path isn't being watched, start watching it
if it is, stop watching it
"""
if path in self._by_path:
self.remove(path)
else:
self.add(path, verbose) | python | def update(self, path, verbose=False):
""" if the path isn't being watched, start watching it
if it is, stop watching it
"""
if path in self._by_path:
self.remove(path)
else:
self.add(path, verbose) | [
"def",
"update",
"(",
"self",
",",
"path",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"path",
"in",
"self",
".",
"_by_path",
":",
"self",
".",
"remove",
"(",
"path",
")",
"else",
":",
"self",
".",
"add",
"(",
"path",
",",
"verbose",
")"
] | if the path isn't being watched, start watching it
if it is, stop watching it | [
"if",
"the",
"path",
"isn",
"t",
"being",
"watched",
"start",
"watching",
"it",
"if",
"it",
"is",
"stop",
"watching",
"it"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/watcher.py#L36-L43 | train | 213,649 |
rgs1/zk_shell | zk_shell/copy_util.py | Proxy.from_string | def from_string(cls, string, exists=False, asynchronous=False, verbose=False):
"""
if exists is bool, then check it either exists or it doesn't.
if exists is None, we don't care.
"""
result = cls.parse(string)
if result.scheme not in cls.TYPES:
raise CopyError("Invalid scheme: %s" % (result.scheme))
return cls.TYPES[result.scheme](result, exists, asynchronous, verbose) | python | def from_string(cls, string, exists=False, asynchronous=False, verbose=False):
"""
if exists is bool, then check it either exists or it doesn't.
if exists is None, we don't care.
"""
result = cls.parse(string)
if result.scheme not in cls.TYPES:
raise CopyError("Invalid scheme: %s" % (result.scheme))
return cls.TYPES[result.scheme](result, exists, asynchronous, verbose) | [
"def",
"from_string",
"(",
"cls",
",",
"string",
",",
"exists",
"=",
"False",
",",
"asynchronous",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"result",
"=",
"cls",
".",
"parse",
"(",
"string",
")",
"if",
"result",
".",
"scheme",
"not",
"in... | if exists is bool, then check it either exists or it doesn't.
if exists is None, we don't care. | [
"if",
"exists",
"is",
"bool",
"then",
"check",
"it",
"either",
"exists",
"or",
"it",
"doesn",
"t",
".",
"if",
"exists",
"is",
"None",
"we",
"don",
"t",
"care",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/copy_util.py#L148-L158 | train | 213,650 |
rgs1/zk_shell | zk_shell/copy_util.py | ZKProxy.zk_walk | def zk_walk(self, root_path, branch_path):
"""
skip ephemeral znodes since there's no point in copying those
"""
full_path = os.path.join(root_path, branch_path) if branch_path else root_path
try:
children = self.client.get_children(full_path)
except NoNodeError:
children = set()
except NoAuthError:
raise AuthError("read children", full_path)
for child in children:
child_path = os.path.join(branch_path, child) if branch_path else child
try:
stat = self.client.exists(os.path.join(root_path, child_path))
except NoAuthError:
raise AuthError("read", child)
if stat is None or stat.ephemeralOwner != 0:
continue
yield child_path
for new_path in self.zk_walk(root_path, child_path):
yield new_path | python | def zk_walk(self, root_path, branch_path):
"""
skip ephemeral znodes since there's no point in copying those
"""
full_path = os.path.join(root_path, branch_path) if branch_path else root_path
try:
children = self.client.get_children(full_path)
except NoNodeError:
children = set()
except NoAuthError:
raise AuthError("read children", full_path)
for child in children:
child_path = os.path.join(branch_path, child) if branch_path else child
try:
stat = self.client.exists(os.path.join(root_path, child_path))
except NoAuthError:
raise AuthError("read", child)
if stat is None or stat.ephemeralOwner != 0:
continue
yield child_path
for new_path in self.zk_walk(root_path, child_path):
yield new_path | [
"def",
"zk_walk",
"(",
"self",
",",
"root_path",
",",
"branch_path",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_path",
",",
"branch_path",
")",
"if",
"branch_path",
"else",
"root_path",
"try",
":",
"children",
"=",
"self",
"."... | skip ephemeral znodes since there's no point in copying those | [
"skip",
"ephemeral",
"znodes",
"since",
"there",
"s",
"no",
"point",
"in",
"copying",
"those"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/copy_util.py#L371-L396 | train | 213,651 |
rgs1/zk_shell | zk_shell/copy_util.py | FileProxy.write_path | def write_path(self, path_value):
""" this will overwrite dst path - be careful """
parent_dir = os.path.dirname(self.path)
try:
os.makedirs(parent_dir)
except OSError:
pass
with open(self.path, "w") as fph:
fph.write(path_value.value) | python | def write_path(self, path_value):
""" this will overwrite dst path - be careful """
parent_dir = os.path.dirname(self.path)
try:
os.makedirs(parent_dir)
except OSError:
pass
with open(self.path, "w") as fph:
fph.write(path_value.value) | [
"def",
"write_path",
"(",
"self",
",",
"path_value",
")",
":",
"parent_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"parent_dir",
")",
"except",
"OSError",
":",
"pass",
"with",
"... | this will overwrite dst path - be careful | [
"this",
"will",
"overwrite",
"dst",
"path",
"-",
"be",
"careful"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/copy_util.py#L422-L430 | train | 213,652 |
rgs1/zk_shell | zk_shell/tree.py | Tree.get | def get(self, exclude_recurse=None):
"""
Paths matching exclude_recurse will not be recursed.
"""
reqs = Queue()
pending = 1
path = self.path
zk = self.zk
def child_of(path):
return zk.get_children_async(path)
def dispatch(path):
return Request(path, child_of(path))
stat = zk.exists(path)
if stat is None or stat.numChildren == 0:
return
reqs.put(dispatch(path))
while pending:
req = reqs.get()
try:
children = req.value
for child in children:
cpath = os.path.join(req.path, child)
if exclude_recurse is None or exclude_recurse not in child:
pending += 1
reqs.put(dispatch(cpath))
yield cpath
except (NoNodeError, NoAuthError): pass
pending -= 1 | python | def get(self, exclude_recurse=None):
"""
Paths matching exclude_recurse will not be recursed.
"""
reqs = Queue()
pending = 1
path = self.path
zk = self.zk
def child_of(path):
return zk.get_children_async(path)
def dispatch(path):
return Request(path, child_of(path))
stat = zk.exists(path)
if stat is None or stat.numChildren == 0:
return
reqs.put(dispatch(path))
while pending:
req = reqs.get()
try:
children = req.value
for child in children:
cpath = os.path.join(req.path, child)
if exclude_recurse is None or exclude_recurse not in child:
pending += 1
reqs.put(dispatch(cpath))
yield cpath
except (NoNodeError, NoAuthError): pass
pending -= 1 | [
"def",
"get",
"(",
"self",
",",
"exclude_recurse",
"=",
"None",
")",
":",
"reqs",
"=",
"Queue",
"(",
")",
"pending",
"=",
"1",
"path",
"=",
"self",
".",
"path",
"zk",
"=",
"self",
".",
"zk",
"def",
"child_of",
"(",
"path",
")",
":",
"return",
"zk... | Paths matching exclude_recurse will not be recursed. | [
"Paths",
"matching",
"exclude_recurse",
"will",
"not",
"be",
"recursed",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/tree.py#L46-L80 | train | 213,653 |
rgs1/zk_shell | zk_shell/keys.py | to_type | def to_type(value, ptype):
""" Convert value to ptype """
if ptype == 'str':
return str(value)
elif ptype == 'int':
return int(value)
elif ptype == 'float':
return float(value)
elif ptype == 'bool':
if value.lower() == 'true':
return True
elif value.lower() == 'false':
return False
raise ValueError('Bad bool value: %s' % value)
elif ptype == 'json':
return json.loads(value)
return ValueError('Unknown type') | python | def to_type(value, ptype):
""" Convert value to ptype """
if ptype == 'str':
return str(value)
elif ptype == 'int':
return int(value)
elif ptype == 'float':
return float(value)
elif ptype == 'bool':
if value.lower() == 'true':
return True
elif value.lower() == 'false':
return False
raise ValueError('Bad bool value: %s' % value)
elif ptype == 'json':
return json.loads(value)
return ValueError('Unknown type') | [
"def",
"to_type",
"(",
"value",
",",
"ptype",
")",
":",
"if",
"ptype",
"==",
"'str'",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"ptype",
"==",
"'int'",
":",
"return",
"int",
"(",
"value",
")",
"elif",
"ptype",
"==",
"'float'",
":",
"return",
... | Convert value to ptype | [
"Convert",
"value",
"to",
"ptype"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/keys.py#L210-L227 | train | 213,654 |
rgs1/zk_shell | zk_shell/keys.py | Keys.validate_one | def validate_one(cls, keystr):
""" validates one key string """
regex = r'%s$' % cls.ALLOWED_KEY
if re.match(regex, keystr) is None:
raise cls.Bad("Bad key syntax for: %s. Should be: key1.key2..." % (keystr))
return True | python | def validate_one(cls, keystr):
""" validates one key string """
regex = r'%s$' % cls.ALLOWED_KEY
if re.match(regex, keystr) is None:
raise cls.Bad("Bad key syntax for: %s. Should be: key1.key2..." % (keystr))
return True | [
"def",
"validate_one",
"(",
"cls",
",",
"keystr",
")",
":",
"regex",
"=",
"r'%s$'",
"%",
"cls",
".",
"ALLOWED_KEY",
"if",
"re",
".",
"match",
"(",
"regex",
",",
"keystr",
")",
"is",
"None",
":",
"raise",
"cls",
".",
"Bad",
"(",
"\"Bad key syntax for: %... | validates one key string | [
"validates",
"one",
"key",
"string"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/keys.py#L74-L80 | train | 213,655 |
rgs1/zk_shell | zk_shell/keys.py | Keys.validate | def validate(cls, keystr):
""" raises cls.Bad if keys has errors """
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
cls.validate_one(cls.extract(k))
else:
# plain keys str
cls.validate_one(keystr) | python | def validate(cls, keystr):
""" raises cls.Bad if keys has errors """
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
cls.validate_one(cls.extract(k))
else:
# plain keys str
cls.validate_one(keystr) | [
"def",
"validate",
"(",
"cls",
",",
"keystr",
")",
":",
"if",
"\"#{\"",
"in",
"keystr",
":",
"# it's a template with keys vars",
"keys",
"=",
"cls",
".",
"from_template",
"(",
"keystr",
")",
"for",
"k",
"in",
"keys",
":",
"cls",
".",
"validate_one",
"(",
... | raises cls.Bad if keys has errors | [
"raises",
"cls",
".",
"Bad",
"if",
"keys",
"has",
"errors"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/keys.py#L95-L104 | train | 213,656 |
rgs1/zk_shell | zk_shell/keys.py | Keys.fetch | def fetch(cls, obj, keys):
"""
fetches the value corresponding to keys from obj
"""
current = obj
for key in keys.split("."):
if type(current) == list:
try:
key = int(key)
except TypeError:
raise cls.Missing(key)
try:
current = current[key]
except (IndexError, KeyError, TypeError) as ex:
raise cls.Missing(key)
return current | python | def fetch(cls, obj, keys):
"""
fetches the value corresponding to keys from obj
"""
current = obj
for key in keys.split("."):
if type(current) == list:
try:
key = int(key)
except TypeError:
raise cls.Missing(key)
try:
current = current[key]
except (IndexError, KeyError, TypeError) as ex:
raise cls.Missing(key)
return current | [
"def",
"fetch",
"(",
"cls",
",",
"obj",
",",
"keys",
")",
":",
"current",
"=",
"obj",
"for",
"key",
"in",
"keys",
".",
"split",
"(",
"\".\"",
")",
":",
"if",
"type",
"(",
"current",
")",
"==",
"list",
":",
"try",
":",
"key",
"=",
"int",
"(",
... | fetches the value corresponding to keys from obj | [
"fetches",
"the",
"value",
"corresponding",
"to",
"keys",
"from",
"obj"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/keys.py#L107-L124 | train | 213,657 |
rgs1/zk_shell | zk_shell/keys.py | Keys.value | def value(cls, obj, keystr):
"""
gets the value corresponding to keys from obj. if keys is a template
string, it extrapolates the keys in it
"""
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
v = cls.fetch(obj, cls.extract(k))
keystr = keystr.replace(k, str(v))
value = keystr
else:
# plain keys str
value = cls.fetch(obj, keystr)
return value | python | def value(cls, obj, keystr):
"""
gets the value corresponding to keys from obj. if keys is a template
string, it extrapolates the keys in it
"""
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
v = cls.fetch(obj, cls.extract(k))
keystr = keystr.replace(k, str(v))
value = keystr
else:
# plain keys str
value = cls.fetch(obj, keystr)
return value | [
"def",
"value",
"(",
"cls",
",",
"obj",
",",
"keystr",
")",
":",
"if",
"\"#{\"",
"in",
"keystr",
":",
"# it's a template with keys vars",
"keys",
"=",
"cls",
".",
"from_template",
"(",
"keystr",
")",
"for",
"k",
"in",
"keys",
":",
"v",
"=",
"cls",
".",... | gets the value corresponding to keys from obj. if keys is a template
string, it extrapolates the keys in it | [
"gets",
"the",
"value",
"corresponding",
"to",
"keys",
"from",
"obj",
".",
"if",
"keys",
"is",
"a",
"template",
"string",
"it",
"extrapolates",
"the",
"keys",
"in",
"it"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/keys.py#L127-L144 | train | 213,658 |
rgs1/zk_shell | zk_shell/keys.py | Keys.set | def set(cls, obj, keys, value, fill_list_value=None):
"""
sets the value for the given keys on obj. if any of the given
keys does not exist, create the intermediate containers.
"""
current = obj
keys_list = keys.split(".")
for idx, key in enumerate(keys_list, 1):
if type(current) == list:
# Validate this key works with a list.
try:
key = int(key)
except ValueError:
raise cls.Missing(key)
try:
# This is the last key, so set the value.
if idx == len(keys_list):
if type(current) == list:
safe_list_set(
current,
key,
lambda: copy.copy(fill_list_value),
value
)
else:
current[key] = value
# done.
return
# More keys left, ensure we have a container for this key.
if type(key) == int:
try:
current[key]
except IndexError:
# Create a list for this key.
cnext = container_for_key(keys_list[idx])
if type(cnext) == list:
def fill_with():
return []
else:
def fill_with():
return {}
safe_list_set(
current,
key,
fill_with,
[] if type(cnext) == list else {}
)
else:
if key not in current:
# Create a list for this key.
current[key] = container_for_key(keys_list[idx])
# Move on to the next key.
current = current[key]
except (IndexError, KeyError, TypeError):
raise cls.Missing(key) | python | def set(cls, obj, keys, value, fill_list_value=None):
"""
sets the value for the given keys on obj. if any of the given
keys does not exist, create the intermediate containers.
"""
current = obj
keys_list = keys.split(".")
for idx, key in enumerate(keys_list, 1):
if type(current) == list:
# Validate this key works with a list.
try:
key = int(key)
except ValueError:
raise cls.Missing(key)
try:
# This is the last key, so set the value.
if idx == len(keys_list):
if type(current) == list:
safe_list_set(
current,
key,
lambda: copy.copy(fill_list_value),
value
)
else:
current[key] = value
# done.
return
# More keys left, ensure we have a container for this key.
if type(key) == int:
try:
current[key]
except IndexError:
# Create a list for this key.
cnext = container_for_key(keys_list[idx])
if type(cnext) == list:
def fill_with():
return []
else:
def fill_with():
return {}
safe_list_set(
current,
key,
fill_with,
[] if type(cnext) == list else {}
)
else:
if key not in current:
# Create a list for this key.
current[key] = container_for_key(keys_list[idx])
# Move on to the next key.
current = current[key]
except (IndexError, KeyError, TypeError):
raise cls.Missing(key) | [
"def",
"set",
"(",
"cls",
",",
"obj",
",",
"keys",
",",
"value",
",",
"fill_list_value",
"=",
"None",
")",
":",
"current",
"=",
"obj",
"keys_list",
"=",
"keys",
".",
"split",
"(",
"\".\"",
")",
"for",
"idx",
",",
"key",
"in",
"enumerate",
"(",
"key... | sets the value for the given keys on obj. if any of the given
keys does not exist, create the intermediate containers. | [
"sets",
"the",
"value",
"for",
"the",
"given",
"keys",
"on",
"obj",
".",
"if",
"any",
"of",
"the",
"given",
"keys",
"does",
"not",
"exist",
"create",
"the",
"intermediate",
"containers",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/keys.py#L147-L207 | train | 213,659 |
rgs1/zk_shell | zk_shell/util.py | pretty_bytes | def pretty_bytes(num):
""" pretty print the given number of bytes """
for unit in ['', 'KB', 'MB', 'GB']:
if num < 1024.0:
if unit == '':
return "%d" % (num)
else:
return "%3.1f%s" % (num, unit)
num /= 1024.0
return "%3.1f%s" % (num, 'TB') | python | def pretty_bytes(num):
""" pretty print the given number of bytes """
for unit in ['', 'KB', 'MB', 'GB']:
if num < 1024.0:
if unit == '':
return "%d" % (num)
else:
return "%3.1f%s" % (num, unit)
num /= 1024.0
return "%3.1f%s" % (num, 'TB') | [
"def",
"pretty_bytes",
"(",
"num",
")",
":",
"for",
"unit",
"in",
"[",
"''",
",",
"'KB'",
",",
"'MB'",
",",
"'GB'",
"]",
":",
"if",
"num",
"<",
"1024.0",
":",
"if",
"unit",
"==",
"''",
":",
"return",
"\"%d\"",
"%",
"(",
"num",
")",
"else",
":",... | pretty print the given number of bytes | [
"pretty",
"print",
"the",
"given",
"number",
"of",
"bytes"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/util.py#L20-L29 | train | 213,660 |
rgs1/zk_shell | zk_shell/util.py | valid_ipv4 | def valid_ipv4(ip):
""" check if ip is a valid ipv4 """
match = _valid_ipv4.match(ip)
if match is None:
return False
octets = match.groups()
if len(octets) != 4:
return False
first = int(octets[0])
if first < 1 or first > 254:
return False
for i in range(1, 4):
octet = int(octets[i])
if octet < 0 or octet > 255:
return False
return True | python | def valid_ipv4(ip):
""" check if ip is a valid ipv4 """
match = _valid_ipv4.match(ip)
if match is None:
return False
octets = match.groups()
if len(octets) != 4:
return False
first = int(octets[0])
if first < 1 or first > 254:
return False
for i in range(1, 4):
octet = int(octets[i])
if octet < 0 or octet > 255:
return False
return True | [
"def",
"valid_ipv4",
"(",
"ip",
")",
":",
"match",
"=",
"_valid_ipv4",
".",
"match",
"(",
"ip",
")",
"if",
"match",
"is",
"None",
":",
"return",
"False",
"octets",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"len",
"(",
"octets",
")",
"!=",
"4",
... | check if ip is a valid ipv4 | [
"check",
"if",
"ip",
"is",
"a",
"valid",
"ipv4"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/util.py#L104-L123 | train | 213,661 |
rgs1/zk_shell | zk_shell/util.py | valid_host | def valid_host(host):
""" check valid hostname """
for part in host.split("."):
if not _valid_host_part.match(part):
return False
return True | python | def valid_host(host):
""" check valid hostname """
for part in host.split("."):
if not _valid_host_part.match(part):
return False
return True | [
"def",
"valid_host",
"(",
"host",
")",
":",
"for",
"part",
"in",
"host",
".",
"split",
"(",
"\".\"",
")",
":",
"if",
"not",
"_valid_host_part",
".",
"match",
"(",
"part",
")",
":",
"return",
"False",
"return",
"True"
] | check valid hostname | [
"check",
"valid",
"hostname"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/util.py#L126-L132 | train | 213,662 |
rgs1/zk_shell | zk_shell/util.py | valid_host_with_port | def valid_host_with_port(hostport):
"""
matches hostname or an IP, optionally with a port
"""
host, port = hostport.rsplit(":", 1) if ":" in hostport else (hostport, None)
# first, validate host or IP
if not valid_ipv4(host) and not valid_host(host):
return False
# now, validate port
if port is not None and not valid_port(port):
return False
return True | python | def valid_host_with_port(hostport):
"""
matches hostname or an IP, optionally with a port
"""
host, port = hostport.rsplit(":", 1) if ":" in hostport else (hostport, None)
# first, validate host or IP
if not valid_ipv4(host) and not valid_host(host):
return False
# now, validate port
if port is not None and not valid_port(port):
return False
return True | [
"def",
"valid_host_with_port",
"(",
"hostport",
")",
":",
"host",
",",
"port",
"=",
"hostport",
".",
"rsplit",
"(",
"\":\"",
",",
"1",
")",
"if",
"\":\"",
"in",
"hostport",
"else",
"(",
"hostport",
",",
"None",
")",
"# first, validate host or IP",
"if",
"n... | matches hostname or an IP, optionally with a port | [
"matches",
"hostname",
"or",
"an",
"IP",
"optionally",
"with",
"a",
"port"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/util.py#L135-L149 | train | 213,663 |
rgs1/zk_shell | zk_shell/util.py | split | def split(path):
"""
splits path into parent, child
"""
if path == '/':
return ('/', None)
parent, child = path.rsplit('/', 1)
if parent == '':
parent = '/'
return (parent, child) | python | def split(path):
"""
splits path into parent, child
"""
if path == '/':
return ('/', None)
parent, child = path.rsplit('/', 1)
if parent == '':
parent = '/'
return (parent, child) | [
"def",
"split",
"(",
"path",
")",
":",
"if",
"path",
"==",
"'/'",
":",
"return",
"(",
"'/'",
",",
"None",
")",
"parent",
",",
"child",
"=",
"path",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"if",
"parent",
"==",
"''",
":",
"parent",
"=",
"'/'",... | splits path into parent, child | [
"splits",
"path",
"into",
"parent",
"child"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/util.py#L173-L185 | train | 213,664 |
rgs1/zk_shell | zk_shell/util.py | find_outliers | def find_outliers(group, delta):
"""
given a list of values, find those that are apart from the rest by
`delta`. the indexes for the outliers is returned, if any.
examples:
values = [100, 6, 7, 8, 9, 10, 150]
find_outliers(values, 5) -> [0, 6]
values = [5, 6, 5, 4, 5]
find_outliers(values, 3) -> []
"""
with_pos = sorted([pair for pair in enumerate(group)], key=lambda p: p[1])
outliers_start = outliers_end = -1
for i in range(0, len(with_pos) - 1):
cur = with_pos[i][1]
nex = with_pos[i + 1][1]
if nex - cur > delta:
# depending on where we are, outliers are the remaining
# items or the ones that we've already seen.
if i < (len(with_pos) - i):
# outliers are close to the start
outliers_start, outliers_end = 0, i + 1
else:
# outliers are close to the end
outliers_start, outliers_end = i + 1, len(with_pos)
break
if outliers_start != -1:
return [with_pos[i][0] for i in range(outliers_start, outliers_end)]
else:
return [] | python | def find_outliers(group, delta):
"""
given a list of values, find those that are apart from the rest by
`delta`. the indexes for the outliers is returned, if any.
examples:
values = [100, 6, 7, 8, 9, 10, 150]
find_outliers(values, 5) -> [0, 6]
values = [5, 6, 5, 4, 5]
find_outliers(values, 3) -> []
"""
with_pos = sorted([pair for pair in enumerate(group)], key=lambda p: p[1])
outliers_start = outliers_end = -1
for i in range(0, len(with_pos) - 1):
cur = with_pos[i][1]
nex = with_pos[i + 1][1]
if nex - cur > delta:
# depending on where we are, outliers are the remaining
# items or the ones that we've already seen.
if i < (len(with_pos) - i):
# outliers are close to the start
outliers_start, outliers_end = 0, i + 1
else:
# outliers are close to the end
outliers_start, outliers_end = i + 1, len(with_pos)
break
if outliers_start != -1:
return [with_pos[i][0] for i in range(outliers_start, outliers_end)]
else:
return [] | [
"def",
"find_outliers",
"(",
"group",
",",
"delta",
")",
":",
"with_pos",
"=",
"sorted",
"(",
"[",
"pair",
"for",
"pair",
"in",
"enumerate",
"(",
"group",
")",
"]",
",",
"key",
"=",
"lambda",
"p",
":",
"p",
"[",
"1",
"]",
")",
"outliers_start",
"="... | given a list of values, find those that are apart from the rest by
`delta`. the indexes for the outliers is returned, if any.
examples:
values = [100, 6, 7, 8, 9, 10, 150]
find_outliers(values, 5) -> [0, 6]
values = [5, 6, 5, 4, 5]
find_outliers(values, 3) -> [] | [
"given",
"a",
"list",
"of",
"values",
"find",
"those",
"that",
"are",
"apart",
"from",
"the",
"rest",
"by",
"delta",
".",
"the",
"indexes",
"for",
"the",
"outliers",
"is",
"returned",
"if",
"any",
"."
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/util.py#L214-L250 | train | 213,665 |
rgs1/zk_shell | zk_shell/util.py | get_matching | def get_matching(content, match):
""" filters out lines that don't include match """
if match != "":
lines = [line for line in content.split("\n") if match in line]
content = "\n".join(lines)
return content | python | def get_matching(content, match):
""" filters out lines that don't include match """
if match != "":
lines = [line for line in content.split("\n") if match in line]
content = "\n".join(lines)
return content | [
"def",
"get_matching",
"(",
"content",
",",
"match",
")",
":",
"if",
"match",
"!=",
"\"\"",
":",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"content",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"match",
"in",
"line",
"]",
"content",
"=",
"\"\\n\""... | filters out lines that don't include match | [
"filters",
"out",
"lines",
"that",
"don",
"t",
"include",
"match"
] | bbf34fdfcf1f81100e2a5816fad8af6afc782a54 | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/util.py#L270-L275 | train | 213,666 |
Miserlou/zappa-django-utils | zappa_django_utils/db/backends/s3sqlite/base.py | DatabaseWrapper.load_remote_db | def load_remote_db(self):
"""
Load remote S3 DB
"""
signature_version = self.settings_dict.get("SIGNATURE_VERSION", "s3v4")
s3 = boto3.resource(
's3',
config=botocore.client.Config(signature_version=signature_version),
)
if '/tmp/' not in self.settings_dict['NAME']:
try:
etag = ''
if os.path.isfile('/tmp/' + self.settings_dict['NAME']):
m = hashlib.md5()
with open('/tmp/' + self.settings_dict['NAME'], 'rb') as f:
m.update(f.read())
# In general the ETag is the md5 of the file, in some cases it's not,
# and in that case we will just need to reload the file, I don't see any other way
etag = m.hexdigest()
obj = s3.Object(self.settings_dict['BUCKET'], self.settings_dict['NAME'])
obj_bytes = obj.get(IfNoneMatch=etag)["Body"] # Will throw E on 304 or 404
with open('/tmp/' + self.settings_dict['NAME'], 'wb') as f:
f.write(obj_bytes.read())
m = hashlib.md5()
with open('/tmp/' + self.settings_dict['NAME'], 'rb') as f:
m.update(f.read())
self.db_hash = m.hexdigest()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "304":
logging.debug("ETag matches md5 of local copy, using local copy of DB!")
self.db_hash = etag
else:
logging.debug("Couldn't load remote DB object.")
except Exception as e:
# Weird one
logging.debug(e)
# SQLite DatabaseWrapper will treat our tmp as normal now
# Check because Django likes to call this function a lot more than it should
if '/tmp/' not in self.settings_dict['NAME']:
self.settings_dict['REMOTE_NAME'] = self.settings_dict['NAME']
self.settings_dict['NAME'] = '/tmp/' + self.settings_dict['NAME']
# Make sure it exists if it doesn't yet
if not os.path.isfile(self.settings_dict['NAME']):
open(self.settings_dict['NAME'], 'a').close()
logging.debug("Loaded remote DB!") | python | def load_remote_db(self):
"""
Load remote S3 DB
"""
signature_version = self.settings_dict.get("SIGNATURE_VERSION", "s3v4")
s3 = boto3.resource(
's3',
config=botocore.client.Config(signature_version=signature_version),
)
if '/tmp/' not in self.settings_dict['NAME']:
try:
etag = ''
if os.path.isfile('/tmp/' + self.settings_dict['NAME']):
m = hashlib.md5()
with open('/tmp/' + self.settings_dict['NAME'], 'rb') as f:
m.update(f.read())
# In general the ETag is the md5 of the file, in some cases it's not,
# and in that case we will just need to reload the file, I don't see any other way
etag = m.hexdigest()
obj = s3.Object(self.settings_dict['BUCKET'], self.settings_dict['NAME'])
obj_bytes = obj.get(IfNoneMatch=etag)["Body"] # Will throw E on 304 or 404
with open('/tmp/' + self.settings_dict['NAME'], 'wb') as f:
f.write(obj_bytes.read())
m = hashlib.md5()
with open('/tmp/' + self.settings_dict['NAME'], 'rb') as f:
m.update(f.read())
self.db_hash = m.hexdigest()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "304":
logging.debug("ETag matches md5 of local copy, using local copy of DB!")
self.db_hash = etag
else:
logging.debug("Couldn't load remote DB object.")
except Exception as e:
# Weird one
logging.debug(e)
# SQLite DatabaseWrapper will treat our tmp as normal now
# Check because Django likes to call this function a lot more than it should
if '/tmp/' not in self.settings_dict['NAME']:
self.settings_dict['REMOTE_NAME'] = self.settings_dict['NAME']
self.settings_dict['NAME'] = '/tmp/' + self.settings_dict['NAME']
# Make sure it exists if it doesn't yet
if not os.path.isfile(self.settings_dict['NAME']):
open(self.settings_dict['NAME'], 'a').close()
logging.debug("Loaded remote DB!") | [
"def",
"load_remote_db",
"(",
"self",
")",
":",
"signature_version",
"=",
"self",
".",
"settings_dict",
".",
"get",
"(",
"\"SIGNATURE_VERSION\"",
",",
"\"s3v4\"",
")",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
",",
"config",
"=",
"botocore",
".",
"... | Load remote S3 DB | [
"Load",
"remote",
"S3",
"DB"
] | 33ec0dd4334ceb37bece829a2f01188d5ed00f31 | https://github.com/Miserlou/zappa-django-utils/blob/33ec0dd4334ceb37bece829a2f01188d5ed00f31/zappa_django_utils/db/backends/s3sqlite/base.py#L18-L73 | train | 213,667 |
Miserlou/zappa-django-utils | zappa_django_utils/db/backends/s3sqlite/base.py | DatabaseWrapper.close | def close(self, *args, **kwargs):
"""
Engine closed, copy file to DB if it has changed
"""
super(DatabaseWrapper, self).close(*args, **kwargs)
signature_version = self.settings_dict.get("SIGNATURE_VERSION", "s3v4")
s3 = boto3.resource(
's3',
config=botocore.client.Config(signature_version=signature_version),
)
try:
with open(self.settings_dict['NAME'], 'rb') as f:
fb = f.read()
m = hashlib.md5()
m.update(fb)
if self.db_hash == m.hexdigest():
logging.debug("Database unchanged, not saving to remote DB!")
return
bytesIO = BytesIO()
bytesIO.write(fb)
bytesIO.seek(0)
s3_object = s3.Object(self.settings_dict['BUCKET'], self.settings_dict['REMOTE_NAME'])
result = s3_object.put('rb', Body=bytesIO)
except Exception as e:
logging.debug(e)
logging.debug("Saved to remote DB!") | python | def close(self, *args, **kwargs):
"""
Engine closed, copy file to DB if it has changed
"""
super(DatabaseWrapper, self).close(*args, **kwargs)
signature_version = self.settings_dict.get("SIGNATURE_VERSION", "s3v4")
s3 = boto3.resource(
's3',
config=botocore.client.Config(signature_version=signature_version),
)
try:
with open(self.settings_dict['NAME'], 'rb') as f:
fb = f.read()
m = hashlib.md5()
m.update(fb)
if self.db_hash == m.hexdigest():
logging.debug("Database unchanged, not saving to remote DB!")
return
bytesIO = BytesIO()
bytesIO.write(fb)
bytesIO.seek(0)
s3_object = s3.Object(self.settings_dict['BUCKET'], self.settings_dict['REMOTE_NAME'])
result = s3_object.put('rb', Body=bytesIO)
except Exception as e:
logging.debug(e)
logging.debug("Saved to remote DB!") | [
"def",
"close",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"DatabaseWrapper",
",",
"self",
")",
".",
"close",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"signature_version",
"=",
"self",
".",
"settings_dict",... | Engine closed, copy file to DB if it has changed | [
"Engine",
"closed",
"copy",
"file",
"to",
"DB",
"if",
"it",
"has",
"changed"
] | 33ec0dd4334ceb37bece829a2f01188d5ed00f31 | https://github.com/Miserlou/zappa-django-utils/blob/33ec0dd4334ceb37bece829a2f01188d5ed00f31/zappa_django_utils/db/backends/s3sqlite/base.py#L80-L111 | train | 213,668 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/chip.py | Chip.id | def id(self): # pylint: disable=invalid-name,too-many-branches,too-many-return-statements
"""Return a unique id for the detected chip, if any."""
# There are some times we want to trick the platform detection
# say if a raspberry pi doesn't have the right ID, or for testing
try:
return os.environ['BLINKA_FORCECHIP']
except KeyError: # no forced chip, continue with testing!
pass
# Special case, if we have an environment var set, we could use FT232H
try:
if os.environ['BLINKA_FT232H']:
# we can't have ftdi1 as a dependency cause its wierd
# to install, sigh.
import ftdi1 as ftdi # pylint: disable=import-error
try:
ctx = None
ctx = ftdi.new() # Create a libftdi context.
# Enumerate FTDI devices.
count, _ = ftdi.usb_find_all(ctx, 0, 0)
if count < 0:
raise RuntimeError('ftdi_usb_find_all returned error %d : %s' %
count, ftdi.get_error_string(self._ctx))
if count == 0:
raise RuntimeError('BLINKA_FT232H environment variable' + \
'set, but no FT232H device found')
finally:
# Make sure to clean up list and context when done.
if ctx is not None:
ftdi.free(ctx)
return FT232H
except KeyError: # no FT232H environment var
pass
platform = sys.platform
if platform == "linux" or platform == "linux2":
return self._linux_id()
if platform == "esp8266":
return ESP8266
if platform == "samd21":
return SAMD21
if platform == "pyboard":
return STM32
# nothing found!
return None | python | def id(self): # pylint: disable=invalid-name,too-many-branches,too-many-return-statements
"""Return a unique id for the detected chip, if any."""
# There are some times we want to trick the platform detection
# say if a raspberry pi doesn't have the right ID, or for testing
try:
return os.environ['BLINKA_FORCECHIP']
except KeyError: # no forced chip, continue with testing!
pass
# Special case, if we have an environment var set, we could use FT232H
try:
if os.environ['BLINKA_FT232H']:
# we can't have ftdi1 as a dependency cause its wierd
# to install, sigh.
import ftdi1 as ftdi # pylint: disable=import-error
try:
ctx = None
ctx = ftdi.new() # Create a libftdi context.
# Enumerate FTDI devices.
count, _ = ftdi.usb_find_all(ctx, 0, 0)
if count < 0:
raise RuntimeError('ftdi_usb_find_all returned error %d : %s' %
count, ftdi.get_error_string(self._ctx))
if count == 0:
raise RuntimeError('BLINKA_FT232H environment variable' + \
'set, but no FT232H device found')
finally:
# Make sure to clean up list and context when done.
if ctx is not None:
ftdi.free(ctx)
return FT232H
except KeyError: # no FT232H environment var
pass
platform = sys.platform
if platform == "linux" or platform == "linux2":
return self._linux_id()
if platform == "esp8266":
return ESP8266
if platform == "samd21":
return SAMD21
if platform == "pyboard":
return STM32
# nothing found!
return None | [
"def",
"id",
"(",
"self",
")",
":",
"# pylint: disable=invalid-name,too-many-branches,too-many-return-statements",
"# There are some times we want to trick the platform detection",
"# say if a raspberry pi doesn't have the right ID, or for testing",
"try",
":",
"return",
"os",
".",
"envi... | Return a unique id for the detected chip, if any. | [
"Return",
"a",
"unique",
"id",
"for",
"the",
"detected",
"chip",
"if",
"any",
"."
] | cddd4d47e530026778dc4e3c3ccabad14e6eac46 | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/chip.py#L26-L70 | train | 213,669 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/chip.py | Chip._linux_id | def _linux_id(self):
"""Attempt to detect the CPU on a computer running the Linux kernel."""
linux_id = None
hardware = self.detector.get_cpuinfo_field("Hardware")
if hardware is None:
vendor_id = self.detector.get_cpuinfo_field("vendor_id")
if vendor_id in ("GenuineIntel", "AuthenticAMD"):
linux_id = GENERIC_X86
compatible = self.detector.get_device_compatible()
if compatible and 'tegra' in compatible:
if 'cv' in compatible or 'nano' in compatible:
linux_id = T210
elif 'quill' in compatible:
linux_id = T186
elif 'xavier' in compatible:
linux_id = T194
elif hardware in ("BCM2708", "BCM2709", "BCM2835"):
linux_id = BCM2XXX
elif "AM33XX" in hardware:
linux_id = AM33XX
elif "sun8i" in hardware:
linux_id = SUN8I
elif "ODROIDC" in hardware:
linux_id = S805
elif "ODROID-C2" in hardware:
linux_id = S905
elif "SAMA5" in hardware:
linux_id = SAMA5
return linux_id | python | def _linux_id(self):
"""Attempt to detect the CPU on a computer running the Linux kernel."""
linux_id = None
hardware = self.detector.get_cpuinfo_field("Hardware")
if hardware is None:
vendor_id = self.detector.get_cpuinfo_field("vendor_id")
if vendor_id in ("GenuineIntel", "AuthenticAMD"):
linux_id = GENERIC_X86
compatible = self.detector.get_device_compatible()
if compatible and 'tegra' in compatible:
if 'cv' in compatible or 'nano' in compatible:
linux_id = T210
elif 'quill' in compatible:
linux_id = T186
elif 'xavier' in compatible:
linux_id = T194
elif hardware in ("BCM2708", "BCM2709", "BCM2835"):
linux_id = BCM2XXX
elif "AM33XX" in hardware:
linux_id = AM33XX
elif "sun8i" in hardware:
linux_id = SUN8I
elif "ODROIDC" in hardware:
linux_id = S805
elif "ODROID-C2" in hardware:
linux_id = S905
elif "SAMA5" in hardware:
linux_id = SAMA5
return linux_id | [
"def",
"_linux_id",
"(",
"self",
")",
":",
"linux_id",
"=",
"None",
"hardware",
"=",
"self",
".",
"detector",
".",
"get_cpuinfo_field",
"(",
"\"Hardware\"",
")",
"if",
"hardware",
"is",
"None",
":",
"vendor_id",
"=",
"self",
".",
"detector",
".",
"get_cpui... | Attempt to detect the CPU on a computer running the Linux kernel. | [
"Attempt",
"to",
"detect",
"the",
"CPU",
"on",
"a",
"computer",
"running",
"the",
"Linux",
"kernel",
"."
] | cddd4d47e530026778dc4e3c3ccabad14e6eac46 | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/chip.py#L73-L105 | train | 213,670 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/board.py | Board.id | def id(self):
"""Return a unique id for the detected board, if any."""
# There are some times we want to trick the platform detection
# say if a raspberry pi doesn't have the right ID, or for testing
try:
return os.environ['BLINKA_FORCEBOARD']
except KeyError: # no forced board, continue with testing!
pass
chip_id = self.detector.chip.id
board_id = None
if chip_id == ap_chip.BCM2XXX:
board_id = self._pi_id()
elif chip_id == ap_chip.AM33XX:
board_id = self._beaglebone_id()
elif chip_id == ap_chip.GENERIC_X86:
board_id = GENERIC_LINUX_PC
elif chip_id == ap_chip.SUN8I:
board_id = self._armbian_id()
elif chip_id == ap_chip.SAMA5:
board_id = self._sama5_id()
elif chip_id == ap_chip.ESP8266:
board_id = FEATHER_HUZZAH
elif chip_id == ap_chip.SAMD21:
board_id = FEATHER_M0_EXPRESS
elif chip_id == ap_chip.STM32:
board_id = PYBOARD
elif chip_id == ap_chip.S805:
board_id = ODROID_C1
elif chip_id == ap_chip.S905:
board_id = ODROID_C2
elif chip_id == ap_chip.FT232H:
board_id = FTDI_FT232H
elif chip_id in (ap_chip.T210, ap_chip.T186, ap_chip.T194):
board_id = self._tegra_id()
return board_id | python | def id(self):
"""Return a unique id for the detected board, if any."""
# There are some times we want to trick the platform detection
# say if a raspberry pi doesn't have the right ID, or for testing
try:
return os.environ['BLINKA_FORCEBOARD']
except KeyError: # no forced board, continue with testing!
pass
chip_id = self.detector.chip.id
board_id = None
if chip_id == ap_chip.BCM2XXX:
board_id = self._pi_id()
elif chip_id == ap_chip.AM33XX:
board_id = self._beaglebone_id()
elif chip_id == ap_chip.GENERIC_X86:
board_id = GENERIC_LINUX_PC
elif chip_id == ap_chip.SUN8I:
board_id = self._armbian_id()
elif chip_id == ap_chip.SAMA5:
board_id = self._sama5_id()
elif chip_id == ap_chip.ESP8266:
board_id = FEATHER_HUZZAH
elif chip_id == ap_chip.SAMD21:
board_id = FEATHER_M0_EXPRESS
elif chip_id == ap_chip.STM32:
board_id = PYBOARD
elif chip_id == ap_chip.S805:
board_id = ODROID_C1
elif chip_id == ap_chip.S905:
board_id = ODROID_C2
elif chip_id == ap_chip.FT232H:
board_id = FTDI_FT232H
elif chip_id in (ap_chip.T210, ap_chip.T186, ap_chip.T194):
board_id = self._tegra_id()
return board_id | [
"def",
"id",
"(",
"self",
")",
":",
"# There are some times we want to trick the platform detection",
"# say if a raspberry pi doesn't have the right ID, or for testing",
"try",
":",
"return",
"os",
".",
"environ",
"[",
"'BLINKA_FORCEBOARD'",
"]",
"except",
"KeyError",
":",
"... | Return a unique id for the detected board, if any. | [
"Return",
"a",
"unique",
"id",
"for",
"the",
"detected",
"board",
"if",
"any",
"."
] | cddd4d47e530026778dc4e3c3ccabad14e6eac46 | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/board.py#L240-L276 | train | 213,671 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/board.py | Board._pi_id | def _pi_id(self):
"""Try to detect id of a Raspberry Pi."""
# Check for Pi boards:
pi_rev_code = self._pi_rev_code()
if pi_rev_code:
for model, codes in _PI_REV_CODES.items():
if pi_rev_code in codes:
return model
return None | python | def _pi_id(self):
"""Try to detect id of a Raspberry Pi."""
# Check for Pi boards:
pi_rev_code = self._pi_rev_code()
if pi_rev_code:
for model, codes in _PI_REV_CODES.items():
if pi_rev_code in codes:
return model
return None | [
"def",
"_pi_id",
"(",
"self",
")",
":",
"# Check for Pi boards:",
"pi_rev_code",
"=",
"self",
".",
"_pi_rev_code",
"(",
")",
"if",
"pi_rev_code",
":",
"for",
"model",
",",
"codes",
"in",
"_PI_REV_CODES",
".",
"items",
"(",
")",
":",
"if",
"pi_rev_code",
"i... | Try to detect id of a Raspberry Pi. | [
"Try",
"to",
"detect",
"id",
"of",
"a",
"Raspberry",
"Pi",
"."
] | cddd4d47e530026778dc4e3c3ccabad14e6eac46 | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/board.py#L279-L287 | train | 213,672 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/board.py | Board._pi_rev_code | def _pi_rev_code(self):
"""Attempt to find a Raspberry Pi revision code for this board."""
# 2708 is Pi 1
# 2709 is Pi 2
# 2835 is Pi 3 (or greater) on 4.9.x kernel
# Anything else is not a Pi.
if self.detector.chip.id != ap_chip.BCM2XXX:
# Something else, not a Pi.
return None
return self.detector.get_cpuinfo_field('Revision') | python | def _pi_rev_code(self):
"""Attempt to find a Raspberry Pi revision code for this board."""
# 2708 is Pi 1
# 2709 is Pi 2
# 2835 is Pi 3 (or greater) on 4.9.x kernel
# Anything else is not a Pi.
if self.detector.chip.id != ap_chip.BCM2XXX:
# Something else, not a Pi.
return None
return self.detector.get_cpuinfo_field('Revision') | [
"def",
"_pi_rev_code",
"(",
"self",
")",
":",
"# 2708 is Pi 1",
"# 2709 is Pi 2",
"# 2835 is Pi 3 (or greater) on 4.9.x kernel",
"# Anything else is not a Pi.",
"if",
"self",
".",
"detector",
".",
"chip",
".",
"id",
"!=",
"ap_chip",
".",
"BCM2XXX",
":",
"# Something els... | Attempt to find a Raspberry Pi revision code for this board. | [
"Attempt",
"to",
"find",
"a",
"Raspberry",
"Pi",
"revision",
"code",
"for",
"this",
"board",
"."
] | cddd4d47e530026778dc4e3c3ccabad14e6eac46 | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/board.py#L289-L298 | train | 213,673 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/board.py | Board._beaglebone_id | def _beaglebone_id(self):
"""Try to detect id of a Beaglebone."""
try:
with open("/sys/bus/nvmem/devices/0-00500/nvmem", "rb") as eeprom:
eeprom_bytes = eeprom.read(16)
except FileNotFoundError:
return None
if eeprom_bytes[:4] != b'\xaaU3\xee':
return None
id_string = eeprom_bytes[4:].decode("ascii")
for model, bb_ids in _BEAGLEBONE_BOARD_IDS.items():
for bb_id in bb_ids:
if id_string == bb_id[1]:
return model
return None | python | def _beaglebone_id(self):
"""Try to detect id of a Beaglebone."""
try:
with open("/sys/bus/nvmem/devices/0-00500/nvmem", "rb") as eeprom:
eeprom_bytes = eeprom.read(16)
except FileNotFoundError:
return None
if eeprom_bytes[:4] != b'\xaaU3\xee':
return None
id_string = eeprom_bytes[4:].decode("ascii")
for model, bb_ids in _BEAGLEBONE_BOARD_IDS.items():
for bb_id in bb_ids:
if id_string == bb_id[1]:
return model
return None | [
"def",
"_beaglebone_id",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"\"/sys/bus/nvmem/devices/0-00500/nvmem\"",
",",
"\"rb\"",
")",
"as",
"eeprom",
":",
"eeprom_bytes",
"=",
"eeprom",
".",
"read",
"(",
"16",
")",
"except",
"FileNotFoundError",
":"... | Try to detect id of a Beaglebone. | [
"Try",
"to",
"detect",
"id",
"of",
"a",
"Beaglebone",
"."
] | cddd4d47e530026778dc4e3c3ccabad14e6eac46 | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/board.py#L301-L318 | train | 213,674 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/board.py | Board._tegra_id | def _tegra_id(self):
"""Try to detect the id of aarch64 board."""
board_value = self.detector.get_device_model()
if 'tx1' in board_value:
return JETSON_TX1
elif 'quill' in board_value:
return JETSON_TX2
elif 'xavier' in board_value:
return JETSON_XAVIER
elif 'nano' in board_value:
return JETSON_NANO
return None | python | def _tegra_id(self):
"""Try to detect the id of aarch64 board."""
board_value = self.detector.get_device_model()
if 'tx1' in board_value:
return JETSON_TX1
elif 'quill' in board_value:
return JETSON_TX2
elif 'xavier' in board_value:
return JETSON_XAVIER
elif 'nano' in board_value:
return JETSON_NANO
return None | [
"def",
"_tegra_id",
"(",
"self",
")",
":",
"board_value",
"=",
"self",
".",
"detector",
".",
"get_device_model",
"(",
")",
"if",
"'tx1'",
"in",
"board_value",
":",
"return",
"JETSON_TX1",
"elif",
"'quill'",
"in",
"board_value",
":",
"return",
"JETSON_TX2",
"... | Try to detect the id of aarch64 board. | [
"Try",
"to",
"detect",
"the",
"id",
"of",
"aarch64",
"board",
"."
] | cddd4d47e530026778dc4e3c3ccabad14e6eac46 | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/board.py#L335-L346 | train | 213,675 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/board.py | Board.any_embedded_linux | def any_embedded_linux(self):
"""Check whether the current board is any embedded Linux device."""
return self.any_raspberry_pi or self.any_beaglebone or \
self.any_orange_pi or self.any_giant_board or self.any_jetson_board | python | def any_embedded_linux(self):
"""Check whether the current board is any embedded Linux device."""
return self.any_raspberry_pi or self.any_beaglebone or \
self.any_orange_pi or self.any_giant_board or self.any_jetson_board | [
"def",
"any_embedded_linux",
"(",
"self",
")",
":",
"return",
"self",
".",
"any_raspberry_pi",
"or",
"self",
".",
"any_beaglebone",
"or",
"self",
".",
"any_orange_pi",
"or",
"self",
".",
"any_giant_board",
"or",
"self",
".",
"any_jetson_board"
] | Check whether the current board is any embedded Linux device. | [
"Check",
"whether",
"the",
"current",
"board",
"is",
"any",
"embedded",
"Linux",
"device",
"."
] | cddd4d47e530026778dc4e3c3ccabad14e6eac46 | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/board.py#L379-L382 | train | 213,676 |
aws/aws-xray-sdk-python | aws_xray_sdk/ext/aiohttp/middleware.py | middleware | async def middleware(request, handler):
"""
Main middleware function, deals with all the X-Ray segment logic
"""
# Create X-Ray headers
xray_header = construct_xray_header(request.headers)
# Get name of service or generate a dynamic one from host
name = calculate_segment_name(request.headers['host'].split(':', 1)[0], xray_recorder)
sampling_req = {
'host': request.headers['host'],
'method': request.method,
'path': request.path,
'service': name,
}
sampling_decision = calculate_sampling_decision(
trace_header=xray_header,
recorder=xray_recorder,
sampling_req=sampling_req,
)
# Start a segment
segment = xray_recorder.begin_segment(
name=name,
traceid=xray_header.root,
parent_id=xray_header.parent,
sampling=sampling_decision,
)
segment.save_origin_trace_header(xray_header)
# Store request metadata in the current segment
segment.put_http_meta(http.URL, str(request.url))
segment.put_http_meta(http.METHOD, request.method)
if 'User-Agent' in request.headers:
segment.put_http_meta(http.USER_AGENT, request.headers['User-Agent'])
if 'X-Forwarded-For' in request.headers:
segment.put_http_meta(http.CLIENT_IP, request.headers['X-Forwarded-For'])
segment.put_http_meta(http.X_FORWARDED_FOR, True)
elif 'remote_addr' in request.headers:
segment.put_http_meta(http.CLIENT_IP, request.headers['remote_addr'])
else:
segment.put_http_meta(http.CLIENT_IP, request.remote)
try:
# Call next middleware or request handler
response = await handler(request)
except HTTPException as exc:
# Non 2XX responses are raised as HTTPExceptions
response = exc
raise
except Exception as err:
# Store exception information including the stacktrace to the segment
response = None
segment.put_http_meta(http.STATUS, 500)
stack = stacktrace.get_stacktrace(limit=xray_recorder.max_trace_back)
segment.add_exception(err, stack)
raise
finally:
if response is not None:
segment.put_http_meta(http.STATUS, response.status)
if 'Content-Length' in response.headers:
length = int(response.headers['Content-Length'])
segment.put_http_meta(http.CONTENT_LENGTH, length)
header_str = prepare_response_header(xray_header, segment)
response.headers[http.XRAY_HEADER] = header_str
xray_recorder.end_segment()
return response | python | async def middleware(request, handler):
"""
Main middleware function, deals with all the X-Ray segment logic
"""
# Create X-Ray headers
xray_header = construct_xray_header(request.headers)
# Get name of service or generate a dynamic one from host
name = calculate_segment_name(request.headers['host'].split(':', 1)[0], xray_recorder)
sampling_req = {
'host': request.headers['host'],
'method': request.method,
'path': request.path,
'service': name,
}
sampling_decision = calculate_sampling_decision(
trace_header=xray_header,
recorder=xray_recorder,
sampling_req=sampling_req,
)
# Start a segment
segment = xray_recorder.begin_segment(
name=name,
traceid=xray_header.root,
parent_id=xray_header.parent,
sampling=sampling_decision,
)
segment.save_origin_trace_header(xray_header)
# Store request metadata in the current segment
segment.put_http_meta(http.URL, str(request.url))
segment.put_http_meta(http.METHOD, request.method)
if 'User-Agent' in request.headers:
segment.put_http_meta(http.USER_AGENT, request.headers['User-Agent'])
if 'X-Forwarded-For' in request.headers:
segment.put_http_meta(http.CLIENT_IP, request.headers['X-Forwarded-For'])
segment.put_http_meta(http.X_FORWARDED_FOR, True)
elif 'remote_addr' in request.headers:
segment.put_http_meta(http.CLIENT_IP, request.headers['remote_addr'])
else:
segment.put_http_meta(http.CLIENT_IP, request.remote)
try:
# Call next middleware or request handler
response = await handler(request)
except HTTPException as exc:
# Non 2XX responses are raised as HTTPExceptions
response = exc
raise
except Exception as err:
# Store exception information including the stacktrace to the segment
response = None
segment.put_http_meta(http.STATUS, 500)
stack = stacktrace.get_stacktrace(limit=xray_recorder.max_trace_back)
segment.add_exception(err, stack)
raise
finally:
if response is not None:
segment.put_http_meta(http.STATUS, response.status)
if 'Content-Length' in response.headers:
length = int(response.headers['Content-Length'])
segment.put_http_meta(http.CONTENT_LENGTH, length)
header_str = prepare_response_header(xray_header, segment)
response.headers[http.XRAY_HEADER] = header_str
xray_recorder.end_segment()
return response | [
"async",
"def",
"middleware",
"(",
"request",
",",
"handler",
")",
":",
"# Create X-Ray headers",
"xray_header",
"=",
"construct_xray_header",
"(",
"request",
".",
"headers",
")",
"# Get name of service or generate a dynamic one from host",
"name",
"=",
"calculate_segment_n... | Main middleware function, deals with all the X-Ray segment logic | [
"Main",
"middleware",
"function",
"deals",
"with",
"all",
"the",
"X",
"-",
"Ray",
"segment",
"logic"
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/ext/aiohttp/middleware.py#L15-L87 | train | 213,677 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/traceid.py | TraceId.to_id | def to_id(self):
"""
Convert TraceId object to a string.
"""
return "%s%s%s%s%s" % (TraceId.VERSION, TraceId.DELIMITER,
format(self.start_time, 'x'),
TraceId.DELIMITER, self.__number) | python | def to_id(self):
"""
Convert TraceId object to a string.
"""
return "%s%s%s%s%s" % (TraceId.VERSION, TraceId.DELIMITER,
format(self.start_time, 'x'),
TraceId.DELIMITER, self.__number) | [
"def",
"to_id",
"(",
"self",
")",
":",
"return",
"\"%s%s%s%s%s\"",
"%",
"(",
"TraceId",
".",
"VERSION",
",",
"TraceId",
".",
"DELIMITER",
",",
"format",
"(",
"self",
".",
"start_time",
",",
"'x'",
")",
",",
"TraceId",
".",
"DELIMITER",
",",
"self",
"."... | Convert TraceId object to a string. | [
"Convert",
"TraceId",
"object",
"to",
"a",
"string",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/traceid.py#L22-L28 | train | 213,678 |
aws/aws-xray-sdk-python | aws_xray_sdk/ext/httplib/patch.py | unpatch | def unpatch():
"""
Unpatch any previously patched modules.
This operation is idempotent.
"""
_PATCHED_MODULES.discard('httplib')
setattr(httplib, PATCH_FLAG, False)
# _send_request encapsulates putrequest, putheader[s], and endheaders
unwrap(httplib.HTTPConnection, '_send_request')
unwrap(httplib.HTTPConnection, 'getresponse')
unwrap(httplib.HTTPResponse, 'read') | python | def unpatch():
"""
Unpatch any previously patched modules.
This operation is idempotent.
"""
_PATCHED_MODULES.discard('httplib')
setattr(httplib, PATCH_FLAG, False)
# _send_request encapsulates putrequest, putheader[s], and endheaders
unwrap(httplib.HTTPConnection, '_send_request')
unwrap(httplib.HTTPConnection, 'getresponse')
unwrap(httplib.HTTPResponse, 'read') | [
"def",
"unpatch",
"(",
")",
":",
"_PATCHED_MODULES",
".",
"discard",
"(",
"'httplib'",
")",
"setattr",
"(",
"httplib",
",",
"PATCH_FLAG",
",",
"False",
")",
"# _send_request encapsulates putrequest, putheader[s], and endheaders",
"unwrap",
"(",
"httplib",
".",
"HTTPCo... | Unpatch any previously patched modules.
This operation is idempotent. | [
"Unpatch",
"any",
"previously",
"patched",
"modules",
".",
"This",
"operation",
"is",
"idempotent",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/ext/httplib/patch.py#L178-L188 | train | 213,679 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/async_context.py | task_factory | def task_factory(loop, coro):
"""
Task factory function
Fuction closely mirrors the logic inside of
asyncio.BaseEventLoop.create_task. Then if there is a current
task and the current task has a context then share that context
with the new task
"""
task = asyncio.Task(coro, loop=loop)
if task._source_traceback: # flake8: noqa
del task._source_traceback[-1] # flake8: noqa
# Share context with new task if possible
current_task = asyncio.Task.current_task(loop=loop)
if current_task is not None and hasattr(current_task, 'context'):
setattr(task, 'context', current_task.context)
return task | python | def task_factory(loop, coro):
"""
Task factory function
Fuction closely mirrors the logic inside of
asyncio.BaseEventLoop.create_task. Then if there is a current
task and the current task has a context then share that context
with the new task
"""
task = asyncio.Task(coro, loop=loop)
if task._source_traceback: # flake8: noqa
del task._source_traceback[-1] # flake8: noqa
# Share context with new task if possible
current_task = asyncio.Task.current_task(loop=loop)
if current_task is not None and hasattr(current_task, 'context'):
setattr(task, 'context', current_task.context)
return task | [
"def",
"task_factory",
"(",
"loop",
",",
"coro",
")",
":",
"task",
"=",
"asyncio",
".",
"Task",
"(",
"coro",
",",
"loop",
"=",
"loop",
")",
"if",
"task",
".",
"_source_traceback",
":",
"# flake8: noqa",
"del",
"task",
".",
"_source_traceback",
"[",
"-",
... | Task factory function
Fuction closely mirrors the logic inside of
asyncio.BaseEventLoop.create_task. Then if there is a current
task and the current task has a context then share that context
with the new task | [
"Task",
"factory",
"function"
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/async_context.py#L80-L98 | train | 213,680 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/sampling/sampling_rule.py | SamplingRule.match | def match(self, sampling_req):
"""
Determines whether or not this sampling rule applies to the incoming
request based on some of the request's parameters.
Any ``None`` parameter provided will be considered an implicit match.
"""
if sampling_req is None:
return False
host = sampling_req.get('host', None)
method = sampling_req.get('method', None)
path = sampling_req.get('path', None)
service = sampling_req.get('service', None)
service_type = sampling_req.get('service_type', None)
return (not host or wildcard_match(self._host, host)) \
and (not method or wildcard_match(self._method, method)) \
and (not path or wildcard_match(self._path, path)) \
and (not service or wildcard_match(self._service, service)) \
and (not service_type or wildcard_match(self._service_type, service_type)) | python | def match(self, sampling_req):
"""
Determines whether or not this sampling rule applies to the incoming
request based on some of the request's parameters.
Any ``None`` parameter provided will be considered an implicit match.
"""
if sampling_req is None:
return False
host = sampling_req.get('host', None)
method = sampling_req.get('method', None)
path = sampling_req.get('path', None)
service = sampling_req.get('service', None)
service_type = sampling_req.get('service_type', None)
return (not host or wildcard_match(self._host, host)) \
and (not method or wildcard_match(self._method, method)) \
and (not path or wildcard_match(self._path, path)) \
and (not service or wildcard_match(self._service, service)) \
and (not service_type or wildcard_match(self._service_type, service_type)) | [
"def",
"match",
"(",
"self",
",",
"sampling_req",
")",
":",
"if",
"sampling_req",
"is",
"None",
":",
"return",
"False",
"host",
"=",
"sampling_req",
".",
"get",
"(",
"'host'",
",",
"None",
")",
"method",
"=",
"sampling_req",
".",
"get",
"(",
"'method'",
... | Determines whether or not this sampling rule applies to the incoming
request based on some of the request's parameters.
Any ``None`` parameter provided will be considered an implicit match. | [
"Determines",
"whether",
"or",
"not",
"this",
"sampling",
"rule",
"applies",
"to",
"the",
"incoming",
"request",
"based",
"on",
"some",
"of",
"the",
"request",
"s",
"parameters",
".",
"Any",
"None",
"parameter",
"provided",
"will",
"be",
"considered",
"an",
... | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/sampling/sampling_rule.py#L30-L49 | train | 213,681 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/sampling/sampling_rule.py | SamplingRule.merge | def merge(self, rule):
"""
Migrate all stateful attributes from the old rule
"""
with self._lock:
self._request_count = rule.request_count
self._borrow_count = rule.borrow_count
self._sampled_count = rule.sampled_count
self._reservoir = rule.reservoir
rule.reservoir = None | python | def merge(self, rule):
"""
Migrate all stateful attributes from the old rule
"""
with self._lock:
self._request_count = rule.request_count
self._borrow_count = rule.borrow_count
self._sampled_count = rule.sampled_count
self._reservoir = rule.reservoir
rule.reservoir = None | [
"def",
"merge",
"(",
"self",
",",
"rule",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_request_count",
"=",
"rule",
".",
"request_count",
"self",
".",
"_borrow_count",
"=",
"rule",
".",
"borrow_count",
"self",
".",
"_sampled_count",
"=",
"... | Migrate all stateful attributes from the old rule | [
"Migrate",
"all",
"stateful",
"attributes",
"from",
"the",
"old",
"rule"
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/sampling/sampling_rule.py#L71-L80 | train | 213,682 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/sampling/reservoir.py | Reservoir.borrow_or_take | def borrow_or_take(self, now, can_borrow):
"""
Decide whether to borrow or take one quota from
the reservoir. Return ``False`` if it can neither
borrow nor take. This method is thread-safe.
"""
with self._lock:
return self._borrow_or_take(now, can_borrow) | python | def borrow_or_take(self, now, can_borrow):
"""
Decide whether to borrow or take one quota from
the reservoir. Return ``False`` if it can neither
borrow nor take. This method is thread-safe.
"""
with self._lock:
return self._borrow_or_take(now, can_borrow) | [
"def",
"borrow_or_take",
"(",
"self",
",",
"now",
",",
"can_borrow",
")",
":",
"with",
"self",
".",
"_lock",
":",
"return",
"self",
".",
"_borrow_or_take",
"(",
"now",
",",
"can_borrow",
")"
] | Decide whether to borrow or take one quota from
the reservoir. Return ``False`` if it can neither
borrow nor take. This method is thread-safe. | [
"Decide",
"whether",
"to",
"borrow",
"or",
"take",
"one",
"quota",
"from",
"the",
"reservoir",
".",
"Return",
"False",
"if",
"it",
"can",
"neither",
"borrow",
"nor",
"take",
".",
"This",
"method",
"is",
"thread",
"-",
"safe",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/sampling/reservoir.py#L23-L30 | train | 213,683 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | Entity.close | def close(self, end_time=None):
"""
Close the trace entity by setting `end_time`
and flip the in progress flag to False.
:param int end_time: Epoch in seconds. If not specified
current time will be used.
"""
self._check_ended()
if end_time:
self.end_time = end_time
else:
self.end_time = time.time()
self.in_progress = False | python | def close(self, end_time=None):
"""
Close the trace entity by setting `end_time`
and flip the in progress flag to False.
:param int end_time: Epoch in seconds. If not specified
current time will be used.
"""
self._check_ended()
if end_time:
self.end_time = end_time
else:
self.end_time = time.time()
self.in_progress = False | [
"def",
"close",
"(",
"self",
",",
"end_time",
"=",
"None",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"if",
"end_time",
":",
"self",
".",
"end_time",
"=",
"end_time",
"else",
":",
"self",
".",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"... | Close the trace entity by setting `end_time`
and flip the in progress flag to False.
:param int end_time: Epoch in seconds. If not specified
current time will be used. | [
"Close",
"the",
"trace",
"entity",
"by",
"setting",
"end_time",
"and",
"flip",
"the",
"in",
"progress",
"flag",
"to",
"False",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L58-L72 | train | 213,684 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | Entity.add_subsegment | def add_subsegment(self, subsegment):
"""
Add input subsegment as a child subsegment.
"""
self._check_ended()
subsegment.parent_id = self.id
self.subsegments.append(subsegment) | python | def add_subsegment(self, subsegment):
"""
Add input subsegment as a child subsegment.
"""
self._check_ended()
subsegment.parent_id = self.id
self.subsegments.append(subsegment) | [
"def",
"add_subsegment",
"(",
"self",
",",
"subsegment",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"subsegment",
".",
"parent_id",
"=",
"self",
".",
"id",
"self",
".",
"subsegments",
".",
"append",
"(",
"subsegment",
")"
] | Add input subsegment as a child subsegment. | [
"Add",
"input",
"subsegment",
"as",
"a",
"child",
"subsegment",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L74-L80 | train | 213,685 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | Entity.put_http_meta | def put_http_meta(self, key, value):
"""
Add http related metadata.
:param str key: Currently supported keys are:
* url
* method
* user_agent
* client_ip
* status
* content_length
:param value: status and content_length are int and for other
supported keys string should be used.
"""
self._check_ended()
if value is None:
return
if key == http.STATUS:
if isinstance(value, string_types):
value = int(value)
self.apply_status_code(value)
if key in http.request_keys:
if 'request' not in self.http:
self.http['request'] = {}
self.http['request'][key] = value
elif key in http.response_keys:
if 'response' not in self.http:
self.http['response'] = {}
self.http['response'][key] = value
else:
log.warning("ignoring unsupported key %s in http meta.", key) | python | def put_http_meta(self, key, value):
"""
Add http related metadata.
:param str key: Currently supported keys are:
* url
* method
* user_agent
* client_ip
* status
* content_length
:param value: status and content_length are int and for other
supported keys string should be used.
"""
self._check_ended()
if value is None:
return
if key == http.STATUS:
if isinstance(value, string_types):
value = int(value)
self.apply_status_code(value)
if key in http.request_keys:
if 'request' not in self.http:
self.http['request'] = {}
self.http['request'][key] = value
elif key in http.response_keys:
if 'response' not in self.http:
self.http['response'] = {}
self.http['response'][key] = value
else:
log.warning("ignoring unsupported key %s in http meta.", key) | [
"def",
"put_http_meta",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"key",
"==",
"http",
".",
"STATUS",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_... | Add http related metadata.
:param str key: Currently supported keys are:
* url
* method
* user_agent
* client_ip
* status
* content_length
:param value: status and content_length are int and for other
supported keys string should be used. | [
"Add",
"http",
"related",
"metadata",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L88-L121 | train | 213,686 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | Entity.put_annotation | def put_annotation(self, key, value):
"""
Annotate segment or subsegment with a key-value pair.
Annotations will be indexed for later search query.
:param str key: annotation key
:param object value: annotation value. Any type other than
string/number/bool will be dropped
"""
self._check_ended()
if not isinstance(key, string_types):
log.warning("ignoring non string type annotation key with type %s.", type(key))
return
if not isinstance(value, annotation_value_types):
log.warning("ignoring unsupported annotation value type %s.", type(value))
return
if any(character not in _valid_annotation_key_characters for character in key):
log.warning("ignoring annnotation with unsupported characters in key: '%s'.", key)
return
self.annotations[key] = value | python | def put_annotation(self, key, value):
"""
Annotate segment or subsegment with a key-value pair.
Annotations will be indexed for later search query.
:param str key: annotation key
:param object value: annotation value. Any type other than
string/number/bool will be dropped
"""
self._check_ended()
if not isinstance(key, string_types):
log.warning("ignoring non string type annotation key with type %s.", type(key))
return
if not isinstance(value, annotation_value_types):
log.warning("ignoring unsupported annotation value type %s.", type(value))
return
if any(character not in _valid_annotation_key_characters for character in key):
log.warning("ignoring annnotation with unsupported characters in key: '%s'.", key)
return
self.annotations[key] = value | [
"def",
"put_annotation",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"if",
"not",
"isinstance",
"(",
"key",
",",
"string_types",
")",
":",
"log",
".",
"warning",
"(",
"\"ignoring non string type annotation key with t... | Annotate segment or subsegment with a key-value pair.
Annotations will be indexed for later search query.
:param str key: annotation key
:param object value: annotation value. Any type other than
string/number/bool will be dropped | [
"Annotate",
"segment",
"or",
"subsegment",
"with",
"a",
"key",
"-",
"value",
"pair",
".",
"Annotations",
"will",
"be",
"indexed",
"for",
"later",
"search",
"query",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L123-L146 | train | 213,687 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | Entity.put_metadata | def put_metadata(self, key, value, namespace='default'):
"""
Add metadata to segment or subsegment. Metadata is not indexed
but can be later retrieved by BatchGetTraces API.
:param str namespace: optional. Default namespace is `default`.
It must be a string and prefix `AWS.` is reserved.
:param str key: metadata key under specified namespace
:param object value: any object that can be serialized into JSON string
"""
self._check_ended()
if not isinstance(namespace, string_types):
log.warning("ignoring non string type metadata namespace")
return
if namespace.startswith('AWS.'):
log.warning("Prefix 'AWS.' is reserved, drop metadata with namespace %s", namespace)
return
if self.metadata.get(namespace, None):
self.metadata[namespace][key] = value
else:
self.metadata[namespace] = {key: value} | python | def put_metadata(self, key, value, namespace='default'):
"""
Add metadata to segment or subsegment. Metadata is not indexed
but can be later retrieved by BatchGetTraces API.
:param str namespace: optional. Default namespace is `default`.
It must be a string and prefix `AWS.` is reserved.
:param str key: metadata key under specified namespace
:param object value: any object that can be serialized into JSON string
"""
self._check_ended()
if not isinstance(namespace, string_types):
log.warning("ignoring non string type metadata namespace")
return
if namespace.startswith('AWS.'):
log.warning("Prefix 'AWS.' is reserved, drop metadata with namespace %s", namespace)
return
if self.metadata.get(namespace, None):
self.metadata[namespace][key] = value
else:
self.metadata[namespace] = {key: value} | [
"def",
"put_metadata",
"(",
"self",
",",
"key",
",",
"value",
",",
"namespace",
"=",
"'default'",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"if",
"not",
"isinstance",
"(",
"namespace",
",",
"string_types",
")",
":",
"log",
".",
"warning",
"(",
"... | Add metadata to segment or subsegment. Metadata is not indexed
but can be later retrieved by BatchGetTraces API.
:param str namespace: optional. Default namespace is `default`.
It must be a string and prefix `AWS.` is reserved.
:param str key: metadata key under specified namespace
:param object value: any object that can be serialized into JSON string | [
"Add",
"metadata",
"to",
"segment",
"or",
"subsegment",
".",
"Metadata",
"is",
"not",
"indexed",
"but",
"can",
"be",
"later",
"retrieved",
"by",
"BatchGetTraces",
"API",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L148-L171 | train | 213,688 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | Entity.add_exception | def add_exception(self, exception, stack, remote=False):
"""
Add an exception to trace entities.
:param Exception exception: the catched exception.
:param list stack: the output from python built-in
`traceback.extract_stack()`.
:param bool remote: If False it means it's a client error
instead of a downstream service.
"""
self._check_ended()
self.add_fault_flag()
if hasattr(exception, '_recorded'):
setattr(self, 'cause', getattr(exception, '_cause_id'))
return
exceptions = []
exceptions.append(Throwable(exception, stack, remote))
self.cause['exceptions'] = exceptions
self.cause['working_directory'] = os.getcwd() | python | def add_exception(self, exception, stack, remote=False):
"""
Add an exception to trace entities.
:param Exception exception: the catched exception.
:param list stack: the output from python built-in
`traceback.extract_stack()`.
:param bool remote: If False it means it's a client error
instead of a downstream service.
"""
self._check_ended()
self.add_fault_flag()
if hasattr(exception, '_recorded'):
setattr(self, 'cause', getattr(exception, '_cause_id'))
return
exceptions = []
exceptions.append(Throwable(exception, stack, remote))
self.cause['exceptions'] = exceptions
self.cause['working_directory'] = os.getcwd() | [
"def",
"add_exception",
"(",
"self",
",",
"exception",
",",
"stack",
",",
"remote",
"=",
"False",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"self",
".",
"add_fault_flag",
"(",
")",
"if",
"hasattr",
"(",
"exception",
",",
"'_recorded'",
")",
":",
... | Add an exception to trace entities.
:param Exception exception: the catched exception.
:param list stack: the output from python built-in
`traceback.extract_stack()`.
:param bool remote: If False it means it's a client error
instead of a downstream service. | [
"Add",
"an",
"exception",
"to",
"trace",
"entities",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L210-L231 | train | 213,689 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | Entity.serialize | def serialize(self):
"""
Serialize to JSON document that can be accepted by the
X-Ray backend service. It uses jsonpickle to perform
serialization.
"""
try:
return jsonpickle.encode(self, unpicklable=False)
except Exception:
log.exception("got an exception during serialization") | python | def serialize(self):
"""
Serialize to JSON document that can be accepted by the
X-Ray backend service. It uses jsonpickle to perform
serialization.
"""
try:
return jsonpickle.encode(self, unpicklable=False)
except Exception:
log.exception("got an exception during serialization") | [
"def",
"serialize",
"(",
"self",
")",
":",
"try",
":",
"return",
"jsonpickle",
".",
"encode",
"(",
"self",
",",
"unpicklable",
"=",
"False",
")",
"except",
"Exception",
":",
"log",
".",
"exception",
"(",
"\"got an exception during serialization\"",
")"
] | Serialize to JSON document that can be accepted by the
X-Ray backend service. It uses jsonpickle to perform
serialization. | [
"Serialize",
"to",
"JSON",
"document",
"that",
"can",
"be",
"accepted",
"by",
"the",
"X",
"-",
"Ray",
"backend",
"service",
".",
"It",
"uses",
"jsonpickle",
"to",
"perform",
"serialization",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L247-L256 | train | 213,690 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | Entity._delete_empty_properties | def _delete_empty_properties(self, properties):
"""
Delete empty properties before serialization to avoid
extra keys with empty values in the output json.
"""
if not self.parent_id:
del properties['parent_id']
if not self.subsegments:
del properties['subsegments']
if not self.aws:
del properties['aws']
if not self.http:
del properties['http']
if not self.cause:
del properties['cause']
if not self.annotations:
del properties['annotations']
if not self.metadata:
del properties['metadata']
properties.pop(ORIGIN_TRACE_HEADER_ATTR_KEY, None)
del properties['sampled'] | python | def _delete_empty_properties(self, properties):
"""
Delete empty properties before serialization to avoid
extra keys with empty values in the output json.
"""
if not self.parent_id:
del properties['parent_id']
if not self.subsegments:
del properties['subsegments']
if not self.aws:
del properties['aws']
if not self.http:
del properties['http']
if not self.cause:
del properties['cause']
if not self.annotations:
del properties['annotations']
if not self.metadata:
del properties['metadata']
properties.pop(ORIGIN_TRACE_HEADER_ATTR_KEY, None)
del properties['sampled'] | [
"def",
"_delete_empty_properties",
"(",
"self",
",",
"properties",
")",
":",
"if",
"not",
"self",
".",
"parent_id",
":",
"del",
"properties",
"[",
"'parent_id'",
"]",
"if",
"not",
"self",
".",
"subsegments",
":",
"del",
"properties",
"[",
"'subsegments'",
"]... | Delete empty properties before serialization to avoid
extra keys with empty values in the output json. | [
"Delete",
"empty",
"properties",
"before",
"serialization",
"to",
"avoid",
"extra",
"keys",
"with",
"empty",
"values",
"in",
"the",
"output",
"json",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L258-L279 | train | 213,691 |
aws/aws-xray-sdk-python | aws_xray_sdk/ext/django/conf.py | reload_settings | def reload_settings(*args, **kwargs):
"""
Reload X-Ray user settings upon Django server hot restart
"""
global settings
setting, value = kwargs['setting'], kwargs['value']
if setting == XRAY_NAMESPACE:
settings = XRaySettings(value) | python | def reload_settings(*args, **kwargs):
"""
Reload X-Ray user settings upon Django server hot restart
"""
global settings
setting, value = kwargs['setting'], kwargs['value']
if setting == XRAY_NAMESPACE:
settings = XRaySettings(value) | [
"def",
"reload_settings",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"settings",
"setting",
",",
"value",
"=",
"kwargs",
"[",
"'setting'",
"]",
",",
"kwargs",
"[",
"'value'",
"]",
"if",
"setting",
"==",
"XRAY_NAMESPACE",
":",
"setting... | Reload X-Ray user settings upon Django server hot restart | [
"Reload",
"X",
"-",
"Ray",
"user",
"settings",
"upon",
"Django",
"server",
"hot",
"restart"
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/ext/django/conf.py#L71-L78 | train | 213,692 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/segment.py | Segment.add_subsegment | def add_subsegment(self, subsegment):
"""
Add input subsegment as a child subsegment and increment
reference counter and total subsegments counter.
"""
super(Segment, self).add_subsegment(subsegment)
self.increment() | python | def add_subsegment(self, subsegment):
"""
Add input subsegment as a child subsegment and increment
reference counter and total subsegments counter.
"""
super(Segment, self).add_subsegment(subsegment)
self.increment() | [
"def",
"add_subsegment",
"(",
"self",
",",
"subsegment",
")",
":",
"super",
"(",
"Segment",
",",
"self",
")",
".",
"add_subsegment",
"(",
"subsegment",
")",
"self",
".",
"increment",
"(",
")"
] | Add input subsegment as a child subsegment and increment
reference counter and total subsegments counter. | [
"Add",
"input",
"subsegment",
"as",
"a",
"child",
"subsegment",
"and",
"increment",
"reference",
"counter",
"and",
"total",
"subsegments",
"counter",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/segment.py#L83-L89 | train | 213,693 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/segment.py | Segment.remove_subsegment | def remove_subsegment(self, subsegment):
"""
Remove the reference of input subsegment.
"""
super(Segment, self).remove_subsegment(subsegment)
self.decrement_subsegments_size() | python | def remove_subsegment(self, subsegment):
"""
Remove the reference of input subsegment.
"""
super(Segment, self).remove_subsegment(subsegment)
self.decrement_subsegments_size() | [
"def",
"remove_subsegment",
"(",
"self",
",",
"subsegment",
")",
":",
"super",
"(",
"Segment",
",",
"self",
")",
".",
"remove_subsegment",
"(",
"subsegment",
")",
"self",
".",
"decrement_subsegments_size",
"(",
")"
] | Remove the reference of input subsegment. | [
"Remove",
"the",
"reference",
"of",
"input",
"subsegment",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/segment.py#L126-L131 | train | 213,694 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/segment.py | Segment.set_user | def set_user(self, user):
"""
set user of a segment. One segment can only have one user.
User is indexed and can be later queried.
"""
super(Segment, self)._check_ended()
self.user = user | python | def set_user(self, user):
"""
set user of a segment. One segment can only have one user.
User is indexed and can be later queried.
"""
super(Segment, self)._check_ended()
self.user = user | [
"def",
"set_user",
"(",
"self",
",",
"user",
")",
":",
"super",
"(",
"Segment",
",",
"self",
")",
".",
"_check_ended",
"(",
")",
"self",
".",
"user",
"=",
"user"
] | set user of a segment. One segment can only have one user.
User is indexed and can be later queried. | [
"set",
"user",
"of",
"a",
"segment",
".",
"One",
"segment",
"can",
"only",
"have",
"one",
"user",
".",
"User",
"is",
"indexed",
"and",
"can",
"be",
"later",
"queried",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/segment.py#L133-L139 | train | 213,695 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/segment.py | Segment.set_rule_name | def set_rule_name(self, rule_name):
"""
Add the matched centralized sampling rule name
if a segment is sampled because of that rule.
This method should be only used by the recorder.
"""
if not self.aws.get('xray', None):
self.aws['xray'] = {}
self.aws['xray']['sampling_rule_name'] = rule_name | python | def set_rule_name(self, rule_name):
"""
Add the matched centralized sampling rule name
if a segment is sampled because of that rule.
This method should be only used by the recorder.
"""
if not self.aws.get('xray', None):
self.aws['xray'] = {}
self.aws['xray']['sampling_rule_name'] = rule_name | [
"def",
"set_rule_name",
"(",
"self",
",",
"rule_name",
")",
":",
"if",
"not",
"self",
".",
"aws",
".",
"get",
"(",
"'xray'",
",",
"None",
")",
":",
"self",
".",
"aws",
"[",
"'xray'",
"]",
"=",
"{",
"}",
"self",
".",
"aws",
"[",
"'xray'",
"]",
"... | Add the matched centralized sampling rule name
if a segment is sampled because of that rule.
This method should be only used by the recorder. | [
"Add",
"the",
"matched",
"centralized",
"sampling",
"rule",
"name",
"if",
"a",
"segment",
"is",
"sampled",
"because",
"of",
"that",
"rule",
".",
"This",
"method",
"should",
"be",
"only",
"used",
"by",
"the",
"recorder",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/segment.py#L148-L156 | train | 213,696 |
aws/aws-xray-sdk-python | aws_xray_sdk/ext/util.py | inject_trace_header | def inject_trace_header(headers, entity):
"""
Extract trace id, entity id and sampling decision
from the input entity and inject these information
to headers.
:param dict headers: http headers to inject
:param Entity entity: trace entity that the trace header
value generated from.
"""
if not entity:
return
if hasattr(entity, 'type') and entity.type == 'subsegment':
header = entity.parent_segment.get_origin_trace_header()
else:
header = entity.get_origin_trace_header()
data = header.data if header else None
to_insert = TraceHeader(
root=entity.trace_id,
parent=entity.id,
sampled=entity.sampled,
data=data,
)
value = to_insert.to_header_str()
headers[http.XRAY_HEADER] = value | python | def inject_trace_header(headers, entity):
"""
Extract trace id, entity id and sampling decision
from the input entity and inject these information
to headers.
:param dict headers: http headers to inject
:param Entity entity: trace entity that the trace header
value generated from.
"""
if not entity:
return
if hasattr(entity, 'type') and entity.type == 'subsegment':
header = entity.parent_segment.get_origin_trace_header()
else:
header = entity.get_origin_trace_header()
data = header.data if header else None
to_insert = TraceHeader(
root=entity.trace_id,
parent=entity.id,
sampled=entity.sampled,
data=data,
)
value = to_insert.to_header_str()
headers[http.XRAY_HEADER] = value | [
"def",
"inject_trace_header",
"(",
"headers",
",",
"entity",
")",
":",
"if",
"not",
"entity",
":",
"return",
"if",
"hasattr",
"(",
"entity",
",",
"'type'",
")",
"and",
"entity",
".",
"type",
"==",
"'subsegment'",
":",
"header",
"=",
"entity",
".",
"paren... | Extract trace id, entity id and sampling decision
from the input entity and inject these information
to headers.
:param dict headers: http headers to inject
:param Entity entity: trace entity that the trace header
value generated from. | [
"Extract",
"trace",
"id",
"entity",
"id",
"and",
"sampling",
"decision",
"from",
"the",
"input",
"entity",
"and",
"inject",
"these",
"information",
"to",
"headers",
"."
] | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/ext/util.py#L13-L41 | train | 213,697 |
aws/aws-xray-sdk-python | aws_xray_sdk/ext/util.py | calculate_sampling_decision | def calculate_sampling_decision(trace_header, recorder, sampling_req):
"""
Return 1 or the matched rule name if should sample and 0 if should not.
The sampling decision coming from ``trace_header`` always has
the highest precedence. If the ``trace_header`` doesn't contain
sampling decision then it checks if sampling is enabled or not
in the recorder. If not enbaled it returns 1. Otherwise it uses user
defined sampling rules to decide.
"""
if trace_header.sampled is not None and trace_header.sampled != '?':
return trace_header.sampled
elif not recorder.sampling:
return 1
else:
decision = recorder.sampler.should_trace(sampling_req)
return decision if decision else 0 | python | def calculate_sampling_decision(trace_header, recorder, sampling_req):
"""
Return 1 or the matched rule name if should sample and 0 if should not.
The sampling decision coming from ``trace_header`` always has
the highest precedence. If the ``trace_header`` doesn't contain
sampling decision then it checks if sampling is enabled or not
in the recorder. If not enbaled it returns 1. Otherwise it uses user
defined sampling rules to decide.
"""
if trace_header.sampled is not None and trace_header.sampled != '?':
return trace_header.sampled
elif not recorder.sampling:
return 1
else:
decision = recorder.sampler.should_trace(sampling_req)
return decision if decision else 0 | [
"def",
"calculate_sampling_decision",
"(",
"trace_header",
",",
"recorder",
",",
"sampling_req",
")",
":",
"if",
"trace_header",
".",
"sampled",
"is",
"not",
"None",
"and",
"trace_header",
".",
"sampled",
"!=",
"'?'",
":",
"return",
"trace_header",
".",
"sampled... | Return 1 or the matched rule name if should sample and 0 if should not.
The sampling decision coming from ``trace_header`` always has
the highest precedence. If the ``trace_header`` doesn't contain
sampling decision then it checks if sampling is enabled or not
in the recorder. If not enbaled it returns 1. Otherwise it uses user
defined sampling rules to decide. | [
"Return",
"1",
"or",
"the",
"matched",
"rule",
"name",
"if",
"should",
"sample",
"and",
"0",
"if",
"should",
"not",
".",
"The",
"sampling",
"decision",
"coming",
"from",
"trace_header",
"always",
"has",
"the",
"highest",
"precedence",
".",
"If",
"the",
"tr... | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/ext/util.py#L44-L59 | train | 213,698 |
aws/aws-xray-sdk-python | aws_xray_sdk/ext/util.py | construct_xray_header | def construct_xray_header(headers):
"""
Construct a ``TraceHeader`` object from dictionary headers
of the incoming request. This method should always return
a ``TraceHeader`` object regardless of tracing header's presence
in the incoming request.
"""
header_str = headers.get(http.XRAY_HEADER) or headers.get(http.ALT_XRAY_HEADER)
if header_str:
return TraceHeader.from_header_str(header_str)
else:
return TraceHeader() | python | def construct_xray_header(headers):
"""
Construct a ``TraceHeader`` object from dictionary headers
of the incoming request. This method should always return
a ``TraceHeader`` object regardless of tracing header's presence
in the incoming request.
"""
header_str = headers.get(http.XRAY_HEADER) or headers.get(http.ALT_XRAY_HEADER)
if header_str:
return TraceHeader.from_header_str(header_str)
else:
return TraceHeader() | [
"def",
"construct_xray_header",
"(",
"headers",
")",
":",
"header_str",
"=",
"headers",
".",
"get",
"(",
"http",
".",
"XRAY_HEADER",
")",
"or",
"headers",
".",
"get",
"(",
"http",
".",
"ALT_XRAY_HEADER",
")",
"if",
"header_str",
":",
"return",
"TraceHeader",... | Construct a ``TraceHeader`` object from dictionary headers
of the incoming request. This method should always return
a ``TraceHeader`` object regardless of tracing header's presence
in the incoming request. | [
"Construct",
"a",
"TraceHeader",
"object",
"from",
"dictionary",
"headers",
"of",
"the",
"incoming",
"request",
".",
"This",
"method",
"should",
"always",
"return",
"a",
"TraceHeader",
"object",
"regardless",
"of",
"tracing",
"header",
"s",
"presence",
"in",
"th... | 707358cd3a516d51f2ebf71cf34f00e8d906a667 | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/ext/util.py#L62-L73 | train | 213,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.