-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
96 lines (69 loc) · 2.43 KB
/
main.py
File metadata and controls
96 lines (69 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from kazoo.client import KazooClient
import argparse
import subprocess
from functools import partial
from kazoo.exceptions import NoNodeException
parser = argparse.ArgumentParser(description='Lab 7 - Zookeeper')
parser.add_argument("--port", type=int, default=2181, help="Zookeeper port")
parser.add_argument("--exec", type=str, default="python gui.py", help="Command to start other process")
args = parser.parse_args()
WATCHED_NODE = "/a"
zk = KazooClient(hosts=f"127.0.0.1:{args.port}")
process = None
children_set = set()
# avoid first call on ChildrenWatch when children are registered and avoid displaying nodes count when creating /a node
def avoid_first_function_call(function):
first_call = True
def closure(*args_, **kwargs):
nonlocal first_call
if first_call:
first_call = False
return
return function(*args_, **kwargs)
return closure
@zk.DataWatch(WATCHED_NODE)
def watch_node(_data, _stat, event):
if event is None:
return
global process
if event.type == "CREATED":
process = subprocess.Popen(args.exec.split(" "))
zk.ChildrenWatch(WATCHED_NODE)(partial(avoid_first_function_call(watch_children), path=WATCHED_NODE))
elif event.type == "DELETED":
if process is not None:
process.kill()
process = None
def watch_children(children, path):
for child in children:
child_path = f"{path}/{child}"
if child_path not in children_set:
zk.ChildrenWatch(child_path)(partial(avoid_first_function_call(watch_children), path=child_path))
children_set.add(child_path)
print(f"Nodes count: {get_nodes_count(WATCHED_NODE)}")
def get_nodes_count(node):
try:
children = zk.get_children(node)
count = 1
for child in children:
count += get_nodes_count(f"{node}/{child}")
return count - 1
except NoNodeException:
return 0
def print_tree(node, depth=0):
try:
children = zk.get_children(node)
print(" " * depth + "/" + node.strip("/").split("/")[-1])
for child in children:
print_tree(f"{node}/{child}", depth + 1)
except NoNodeException:
return
if __name__ == '__main__':
zk.start()
while True:
command = input()
if command == "quit":
break
elif command == "print":
print_tree(WATCHED_NODE)
zk.stop()
zk.close()