-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcnc.py
170 lines (149 loc) · 5.69 KB
/
cnc.py
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
from __future__ import print_function
import zmq
import msgpack
import subprocess
from threading import Thread
import sys
try:
# py2
from Queue import Queue, Empty
except ImportError:
# py3
from queue import Queue, Empty
# Apparently, there's not a really simple clean way of doing
# non-blocking reads from subprocess PIPEs, so we launch a thread for
# each pipe and jam lines into a queue.
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
#print('Read from pipe:', line)
queue.put(line)
out.close()
def main(addr):
context = zmq.Context()
socket = context.socket(zmq.REP)
print('Binding', addr)
socket.bind(addr)
# processes we have launched
launched_procs = []
# pid -> (proc, stdoutq, stderrq)
captive_procs = {}
# use a poller with timeout to periodically check whether
# launched_procs have terminated...
poll = zmq.Poller()
poll.register(socket, zmq.POLLIN)
while True:
#print('Waiting for request...')
events = poll.poll(timeout=5000)
if len(events) == 0:
# timed out
for p in launched_procs:
print('Checking child pid', p.pid)
if p.poll() is not None:
print('Child PID', p.pid, 'terminated with', p.returncode)
launched_procs.remove(p)
continue
msg = socket.recv()
print('Received:', msg)
msg = msgpack.unpackb(msg)
print('Got', msg)
reply = (-1000, '', 'did not understand request')
try:
func = msg[0]
print('Function:', func)
func = func.decode()
if func == 'run':
cmd = msg[1]
print('Running command:', cmd)
#res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
# timeout=?
#reply = (res.returncode, res.stdout, res.stderr)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, executable='/bin/bash', close_fds=True)
(stdout,stderr) = proc.communicate()
reply = (proc.returncode, stdout, stderr)
print('Got result:', reply)
elif func == 'launch':
cmd = msg[1]
captive = False
if len(msg) > 2:
captive = msg[2]
print('Launching command:', cmd, 'captive?', captive)
#p = subprocess.Popen(cmd, shell=True, stdin=subprocess.DEVNULL)
if not captive:
p = subprocess.Popen(cmd, shell=True, executable='/bin/bash', close_fds=True)
launched_procs.append(p)
else:
print('Running command:', cmd)
p = subprocess.Popen(cmd, shell=True, executable='/bin/bash', close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
qout = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, qout))
t.daemon = True
t.start()
qerr = Queue()
t = Thread(target=enqueue_output, args=(p.stderr, qerr))
t.daemon = True
t.start()
captive_procs[p.pid] = (p, qout, qerr)
reply = (0, p.pid, '')
print('Got result:', reply)
elif func == 'read_proc':
pid = msg[1]
if not pid in captive_procs:
print('PID', pid, 'not in captive processes')
print('keys:', captive_procs.keys())
reply = (None, None, None)
else:
(proc, qout, qerr) = captive_procs[pid]
# done yet? set returncode
proc.poll()
out = []
try:
while True:
s = qout.get_nowait()
out.append(s)
except Empty:
pass
#print('Got from queue:', out)
#out = '\n'.join(out)
out = ''.join(out)
err = []
try:
while True:
s = qout.get_nowait()
err.append(s)
except Empty:
pass
#print('Got from err queue:', err)
#err = '\n'.join(err)
err = ''.join(err)
reply = (proc.returncode, out, err)
elif func == 'kill':
pid = msg[1]
if not pid in captive_procs:
print('Request to kill PID', pid, 'not in captive procs; ignore')
reply = None
else:
proc = captive_procs[pid]
proc.terminate()
reply = True
elif func == 'quit':
print('Quitting!')
return 0
else:
print('Unknown function "%s"' % func)
except:
import traceback
traceback.print_exc()
# Send reply
msg = msgpack.packb(reply)
socket.send(msg)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--address', default='tcp://*:9999')
parser.add_argument('--port', default=0)
opt = parser.parse_args()
if opt.port:
addr = 'tcp://*:' + str(opt.port)
else:
addr = opt.address
sys.exit(main(addr))