Skip to content

Commit 3df6885

Browse files
committed
Added Some Studies that i created while testing ZeroMQ
1 parent 86b2f17 commit 3df6885

25 files changed

Lines changed: 4218 additions & 492 deletions

0mq/distributed_client.graphml

Lines changed: 592 additions & 0 deletions
Large diffs are not rendered by default.

0mq/distributed_server.graphml

Lines changed: 520 additions & 0 deletions
Large diffs are not rendered by default.

0mq/firstNode.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# firstNode.py (Client/Orchestrator)
2+
import concore
3+
import time
4+
5+
# --- ZMQ Initialization ---
6+
# This REQ socket connects to Node B (F2)
7+
concore.init_zmq_port(
8+
port_name=f"0x{PORT_F1_F2}_{PORT_NAME_F1_F2}",
9+
port_type="connect",
10+
address="tcp://localhost:" + PORT_F1_F2,
11+
socket_type_str="REQ"
12+
)
13+
# This REQ socket connects to Node C (F3)
14+
concore.init_zmq_port(
15+
port_name=f"0x{PORT_F1_F3}_{PORT_NAME_F1_F3}",
16+
port_type="connect",
17+
address="tcp://localhost:" + PORT_F1_F3,
18+
socket_type_str="REQ"
19+
)
20+
21+
current_value = 0.0
22+
23+
while current_value <= 100:
24+
# --- Step 1: Communicate with Node B ---
25+
print(f"Node A: Sending value {current_value:.2f} to Node B.")
26+
concore.write(f"0x{PORT_F1_F2}_{PORT_NAME_F1_F2}", "value", [current_value])
27+
28+
# Wait for the reply from Node B
29+
value_from_b = concore.read(f"0x{PORT_F1_F2}_{PORT_NAME_F1_F2}", "value", [current_value])
30+
processed_by_b = value_from_b[0]
31+
print(f"Node A: Received processed value {processed_by_b:.2f} from Node B.")
32+
33+
# --- Step 2: Communicate with Node C ---
34+
print(f"Node A: Sending value {processed_by_b:.2f} to Node C.")
35+
concore.write(f"0x{PORT_F1_F3}_{PORT_NAME_F1_F3}", "value", [processed_by_b])
36+
37+
# Wait for the reply from Node C
38+
value_from_c = concore.read(f"0x{PORT_F1_F3}_{PORT_NAME_F1_F3}", "value", [processed_by_b])
39+
current_value = value_from_c[0]
40+
print(f"Node A: Received final value {current_value:.2f} from Node C.")
41+
print("-" * 20)
42+
time.sleep(1) # Slow down the loop for readability
43+
44+
print("\nNode A: Value exceeded 100. Terminating.")
45+
concore.terminate_zmq()

0mq/funbody.dir/concore2.py

Lines changed: 217 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from ast import literal_eval
44
import sys
55
import re
6+
import zmq # Added for ZeroMQ
67

78
#if windows, create script to kill this process
89
# because batch files don't provide easy way to know pid of last command
@@ -12,102 +13,251 @@
1213
with open("concorekill.bat","w") as fpid:
1314
fpid.write("taskkill /F /PID "+str(os.getpid())+"\n")
1415

15-
try:
16-
iport = literal_eval(open("concore.iport").read())
17-
except:
18-
iport = dict()
19-
try:
20-
oport = literal_eval(open("concore.oport").read())
21-
except:
22-
oport = dict()
16+
# --- ZeroMQ Integration Start ---
17+
class ZeroMQPort:
18+
def __init__(self, port_type, address, zmq_socket_type):
19+
self.context = zmq.Context()
20+
self.socket = self.context.socket(zmq_socket_type)
21+
self.port_type = port_type # "bind" or "connect"
22+
self.address = address
23+
if self.port_type == "bind":
24+
self.socket.bind(address)
25+
print(f"ZMQ Port bound to {address}")
26+
else:
27+
self.socket.connect(address)
28+
print(f"ZMQ Port connected to {address}")
29+
30+
# Global ZeroMQ ports registry
31+
zmq_ports = {}
32+
33+
def init_zmq_port(port_name, port_type, address, socket_type_str):
34+
"""
35+
Initializes and registers a ZeroMQ port.
36+
port_name (str): A unique name for this ZMQ port.
37+
port_type (str): "bind" or "connect".
38+
address (str): The ZMQ address (e.g., "tcp://*:5555", "tcp://localhost:5555").
39+
socket_type_str (str): String representation of ZMQ socket type (e.g., "REQ", "REP", "PUB", "SUB").
40+
"""
41+
if port_name in zmq_ports:
42+
print(f"ZMQ Port {port_name} already initialized.")
43+
return # Avoid reinitialization
44+
45+
try:
46+
# Map socket type string to actual ZMQ constant (e.g., zmq.REQ, zmq.REP)
47+
zmq_socket_type = getattr(zmq, socket_type_str.upper())
48+
zmq_ports[port_name] = ZeroMQPort(port_type, address, zmq_socket_type)
49+
print(f"Initialized ZMQ port: {port_name} ({socket_type_str}) on {address}")
50+
except AttributeError:
51+
print(f"Error: Invalid ZMQ socket type string '{socket_type_str}'.")
52+
except zmq.error.ZMQError as e:
53+
print(f"Error initializing ZMQ port {port_name} on {address}: {e}")
54+
except Exception as e:
55+
print(f"An unexpected error occurred during ZMQ port initialization for {port_name}: {e}")
56+
57+
def terminate_zmq():
58+
for port in zmq_ports.values():
59+
try:
60+
port.socket.close()
61+
port.context.term()
62+
except Exception as e:
63+
print(f"Error while terminating ZMQ port {port.address}: {e}")
64+
# --- ZeroMQ Integration End ---
2365

66+
def safe_literal_eval(filename, defaultValue):
67+
try:
68+
with open(filename, "r") as file:
69+
return literal_eval(file.read())
70+
except (FileNotFoundError, SyntaxError, ValueError, Exception) as e:
71+
# Keep print for debugging, but can be made quieter
72+
# print(f"Info: Error reading {filename} or file not found, using default: {e}")
73+
return defaultValue
74+
75+
iport = safe_literal_eval("concore.iport", {})
76+
oport = safe_literal_eval("concore.oport", {})
2477

2578
s = ''
2679
olds = ''
2780
delay = 1
2881
retrycount = 0
2982
inpath = "./in" #must be rel path for local
3083
outpath = "./out"
84+
simtime = 0
3185

3286
#9/21/22
3387
try:
34-
sparams = open(inpath+"1/concore.params").read()
35-
if sparams[0] == '"': #windows keeps "" need to remove
36-
sparams = sparams[1:]
37-
sparams = sparams[0:sparams.find('"')]
38-
if sparams != '{':
39-
print("converting sparams: "+sparams)
40-
sparams = "{'"+re.sub(';',",'",re.sub('=',"':",re.sub(' ','',sparams)))+"}"
41-
print("converted sparams: " + sparams)
42-
try:
43-
params = literal_eval(sparams)
44-
except:
45-
print("bad params: "+sparams)
46-
except:
88+
sparams_path = os.path.join(inpath + "1", "concore.params")
89+
if os.path.exists(sparams_path):
90+
with open(sparams_path, "r") as f:
91+
sparams = f.read()
92+
if sparams: # Ensure sparams is not empty
93+
if sparams[0] == '"' and sparams[-1] == '"': #windows keeps "" need to remove
94+
sparams = sparams[1:-1]
95+
if sparams != '{' and not (sparams.startswith('{') and sparams.endswith('}')): # Check if it needs conversion
96+
print("converting sparams: "+sparams)
97+
sparams = "{'"+re.sub(';',",'",re.sub('=',"':",re.sub(' ','',sparams)))+"}"
98+
print("converted sparams: " + sparams)
99+
try:
100+
params = literal_eval(sparams)
101+
except Exception as e:
102+
print(f"bad params content: {sparams}, error: {e}")
103+
params = dict()
104+
else:
105+
params = dict()
106+
else:
107+
params = dict()
108+
except Exception as e:
109+
# print(f"Info: concore.params not found or error reading, using empty dict: {e}")
47110
params = dict()
111+
48112
#9/30/22
49-
def tryparam(n,i):
50-
try:
51-
return params[n]
52-
except:
53-
return i
113+
def tryparam(n, i):
114+
return params.get(n, i)
54115

55116

56117
#9/12/21
57118
def default_maxtime(default):
58119
global maxtime
59-
try:
60-
maxtime = literal_eval(open(inpath+"1/concore.maxtime").read())
61-
except:
62-
maxtime = default
120+
maxtime_path = os.path.join(inpath + "1", "concore.maxtime")
121+
maxtime = safe_literal_eval(maxtime_path, default)
122+
63123
default_maxtime(100)
64124

65125
def unchanged():
66-
global olds,s
67-
if olds==s:
126+
global olds, s
127+
if olds == s:
68128
s = ''
69129
return True
70-
else:
71-
olds = s
72-
return False
130+
olds = s
131+
return False
132+
133+
def read(port_identifier, name, initstr_val):
134+
global s, simtime, retrycount
135+
136+
default_return_val = initstr_val
137+
if isinstance(initstr_val, str):
138+
try:
139+
default_return_val = literal_eval(initstr_val)
140+
except (SyntaxError, ValueError):
141+
pass
142+
143+
if isinstance(port_identifier, str) and port_identifier in zmq_ports:
144+
zmq_p = zmq_ports[port_identifier]
145+
try:
146+
message = zmq_p.socket.recv_json()
147+
return message
148+
except zmq.error.ZMQError as e:
149+
print(f"ZMQ read error on port {port_identifier} (name: {name}): {e}. Returning default.")
150+
return default_return_val
151+
except Exception as e:
152+
print(f"Unexpected error during ZMQ read on port {port_identifier} (name: {name}): {e}. Returning default.")
153+
return default_return_val
73154

74-
def read(port, name, initstr):
75-
global s,simtime,retrycount
76-
time.sleep(delay)
77155
try:
78-
infile = open(inpath+str(port)+"/"+name);
79-
ins = infile.read()
80-
except:
81-
ins = initstr
82-
while len(ins)==0:
156+
file_port_num = int(port_identifier)
157+
except ValueError:
158+
print(f"Error: Invalid port identifier '{port_identifier}' for file operation. Must be integer or ZMQ name.")
159+
return default_return_val
160+
161+
time.sleep(delay)
162+
file_path = os.path.join(inpath+str(file_port_num), name)
163+
ins = ""
164+
165+
try:
166+
with open(file_path, "r") as infile:
167+
ins = infile.read()
168+
except FileNotFoundError:
169+
ins = str(initstr_val)
170+
except Exception as e:
171+
print(f"Error reading {file_path}: {e}. Using default value.")
172+
return default_return_val
173+
174+
attempts = 0
175+
max_retries = 5
176+
while len(ins) == 0 and attempts < max_retries:
83177
time.sleep(delay)
84-
ins = infile.read()
178+
try:
179+
with open(file_path, "r") as infile:
180+
ins = infile.read()
181+
except Exception as e:
182+
print(f"Retry {attempts + 1}: Error reading {file_path} - {e}")
183+
attempts += 1
85184
retrycount += 1
86-
s += ins
87-
inval = literal_eval(ins)
88-
simtime = max(simtime,inval[0])
89-
return inval[1:]
90-
91-
def write(port, name, val, delta=0):
92-
global outpath,simtime
93-
if isinstance(val,str):
94-
time.sleep(2*delay)
95-
elif isinstance(val,list)==False:
96-
print("mywrite must have list or str")
97-
quit()
185+
186+
if len(ins) == 0:
187+
print(f"Max retries reached for {file_path}, using default value.")
188+
return default_return_val
189+
190+
s += ins
98191
try:
99-
with open(outpath+str(port)+"/"+name,"w") as outfile:
100-
if isinstance(val,list):
101-
outfile.write(str([simtime+delta]+val))
102-
simtime += delta
103-
else:
192+
inval = literal_eval(ins)
193+
if isinstance(inval, list) and len(inval) > 0:
194+
current_simtime_from_file = inval[0]
195+
if isinstance(current_simtime_from_file, (int, float)):
196+
simtime = max(simtime, current_simtime_from_file)
197+
return inval[1:]
198+
else:
199+
print(f"Warning: Unexpected data format in {file_path}: {ins}. Returning raw content or default.")
200+
return inval
201+
except Exception as e:
202+
print(f"Error parsing content from {file_path} ('{ins}'): {e}. Returning default.")
203+
return default_return_val
204+
205+
206+
def write(port_identifier, name, val, delta=0):
207+
global simtime
208+
209+
if isinstance(port_identifier, str) and port_identifier in zmq_ports:
210+
zmq_p = zmq_ports[port_identifier]
211+
try:
212+
zmq_p.socket.send_json(val)
213+
except zmq.error.ZMQError as e:
214+
print(f"ZMQ write error on port {port_identifier} (name: {name}): {e}")
215+
except Exception as e:
216+
print(f"Unexpected error during ZMQ write on port {port_identifier} (name: {name}): {e}")
217+
return
218+
try:
219+
if isinstance(port_identifier, str) and port_identifier in zmq_ports:
220+
file_path = os.path.join("../"+port_identifier, name)
221+
else:
222+
file_port_num = int(port_identifier)
223+
file_path = os.path.join(outpath+str(file_port_num), name)
224+
except ValueError:
225+
print(f"Error: Invalid port identifier '{port_identifier}' for file operation. Must be integer or ZMQ name.")
226+
return
227+
228+
if isinstance(val, str):
229+
time.sleep(2 * delay)
230+
elif not isinstance(val, list):
231+
print(f"File write to {file_path} must have list or str value, got {type(val)}")
232+
return
233+
234+
try:
235+
with open(file_path, "w") as outfile:
236+
if isinstance(val, list):
237+
data_to_write = [simtime + delta] + val
238+
outfile.write(str(data_to_write))
239+
simtime += delta
240+
else:
104241
outfile.write(val)
105-
except:
106-
print("skipping"+outpath+str(port)+"/"+name);
242+
except Exception as e:
243+
print(f"Error writing to {file_path}: {e}")
107244

108-
def initval(simtime_val):
245+
def initval(simtime_val_str):
109246
global simtime
110-
val = literal_eval(simtime_val)
111-
simtime = val[0]
112-
return val[1:]
247+
try:
248+
val = literal_eval(simtime_val_str)
249+
if isinstance(val, list) and len(val) > 0:
250+
first_element = val[0]
251+
if isinstance(first_element, (int, float)):
252+
simtime = first_element
253+
return val[1:]
254+
else:
255+
print(f"Error: First element in initval string '{simtime_val_str}' is not a number. Using data part as is or empty.")
256+
return val[1:] if len(val) > 1 else []
257+
else:
258+
print(f"Error: initval string '{simtime_val_str}' is not a list or is empty. Returning empty list.")
259+
return []
113260

261+
except Exception as e:
262+
print(f"Error parsing simtime_val_str '{simtime_val_str}': {e}. Returning empty list.")
263+
return []

0 commit comments

Comments
 (0)