Parent: [e0bf30] (diff)

Download this file

cmdtalk.py    235 lines (203 with data), 7.8 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
 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#################################
# Copyright (C) 2016 J.F.Dockes
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
########################################################
# Command communication module and utilities. See commands in cmdtalk.h
#
# All data is binary. This is important for Python3
# All parameter names are converted to and processed as str/unicode
from __future__ import print_function
import sys
import os
import tempfile
import shutil
import getopt
import traceback
PY3 = sys.version > '3'
if PY3:
def makebytes(data):
if isinstance(data, bytes):
return data
else:
return data.encode("UTF-8")
else:
def makebytes(data):
if isinstance(data, unicode):
return data.encode("UTF-8")
else:
return data
############################################
# CmdTalk implements the
# communication protocol with the master process. It calls an external
# method to use the args and produce return data.
class CmdTalk:
def __init__(self, outfile=sys.stdout, infile=sys.stdin, exitfunc=None):
try:
self.myname = os.path.basename(sys.argv[0])
except:
self.myname = "???"
self.outfile = outfile
self.infile = infile
self.exitfunc = exitfunc
self.fields = {}
if sys.platform == "win32":
import msvcrt
msvcrt.setmode(self.outfile.fileno(), os.O_BINARY)
msvcrt.setmode(self.infile.fileno(), os.O_BINARY)
self.debugfile = None
if self.debugfile:
self.errfout = open(self.debugfile, "a")
else:
self.errfout = sys.stderr
def log(self, s, doexit = 0, exitvalue = 1):
print("CMDTALK: %s: %s" % (self.myname, s), file=self.errfout)
if doexit:
if self.exitfunc:
self.exitfunc(exitvalue)
sys.exit(exitvalue)
def breakwrite(self, outfile, data):
if sys.platform != "win32":
outfile.write(data)
else:
# On windows, writing big chunks can fail with a "not enough space"
# error. Seems a combined windows/python bug, depending on versions.
# See https://bugs.python.org/issue11395
# In any case, just break it up
total = len(data)
bs = 4*1024
offset = 0
while total > 0:
if total < bs:
tow = total
else:
tow = bs
#self.log("Total %d Writing %d to stdout: %s" % (total,tow,data[offset:offset+tow]))
outfile.write(data[offset:offset+tow])
offset += tow
total -= tow
# Read single parameter from process input: line with param name and size
# followed by data. The param name is returned as str/unicode, the data
# as bytes
def readparam(self):
if PY3:
inf = self.infile.buffer
else:
inf = self.infile
s = inf.readline()
if s == b'':
if self.exitfunc:
self.exitfunc(0)
sys.exit(0)
s = s.rstrip(b'\n')
if s == b'':
return ('', b'')
l = s.split()
if len(l) != 2:
self.log(b'bad line: [' + s + b']', 1, 1)
paramname = l[0].decode('ASCII').rstrip(':')
paramsize = int(l[1])
if paramsize > 0:
paramdata = inf.read(paramsize)
if len(paramdata) != paramsize:
self.log("Bad read: wanted %d, got %d" %
(paramsize, len(paramdata)), 1, 1)
else:
paramdata = b''
if PY3:
paramdata = paramdata.decode('utf-8')
#self.log("paramname [%s] paramsize %d value [%s]" %
# (paramname, paramsize, paramdata))
return (paramname, paramdata)
if PY3:
def senditem(self, nm, data):
data = makebytes(data)
l = len(data)
self.outfile.buffer.write(makebytes("%s: %d\n" % (nm, l)))
self.breakwrite(self.outfile.buffer, data)
else:
def senditem(self, nm, data):
data = makebytes(data)
l = len(data)
self.outfile.write(makebytes("%s: %d\n" % (nm, l)))
self.breakwrite(self.outfile, data)
# Send answer: document, ipath, possible eof.
def answer(self, outfields):
for nm,value in outfields.items():
#self.log("Senditem: [%s] -> [%s]" % (nm, value))
self.senditem(nm, value)
# End of message
print(file=self.outfile)
self.outfile.flush()
#self.log("done writing data")
# Call processor with input params, send result
def processmessage(self, processor, params):
# In normal usage we try to recover from processor errors, but
# we sometimes want to see the real stack trace when testing
safeexec = True
if safeexec:
try:
outfields = processor.process(params)
except Exception as err:
self.log("processmessage: processor raised: [%s]" % err)
traceback.print_exc()
outfields = {}
outfields["cmdtalkstatus"] = "1"
outfields["cmdtalkerrstr"] = str(err)
else:
outfields = processor.process(params)
self.answer(outfields)
# Loop on messages from our master
def mainloop(self, processor):
while 1:
#self.log("waiting for command")
params = dict()
# Read at most 10 parameters (normally 1 or 2), stop at empty line
# End of message is signalled by empty paramname
for i in range(10):
paramname, paramdata = self.readparam()
if paramname == "":
break
params[paramname] = paramdata
# Got message, act on it
self.processmessage(processor, params)
# Common main routine for testing: either run the normal protocol
# engine or a local loop.
def main(proto, processor):
if len(sys.argv) == 1:
proto.mainloop(processor)
# mainloop does not return. Just in case
sys.exit(1)
# Not running the main loop: run one processor call for debugging
def usage():
print("Usage: cmdtalk.py pname pvalue [pname pvalue...]",
file=sys.stderr)
sys.exit(1)
def debprint(out, s):
proto.breakwrite(out, makebytes(s+'\n'))
args = sys.argv[1:]
if len(args) == 0 or len(args) % 2 != 0:
usage()
params = dict()
for i in range(len(args)/2):
params[args[2*i]] = args[2*i+1]
res = processor.process(params)
ioout = sys.stdout.buffer if PY3 else sys.stdout
for nm,value in res.items():
#self.log("Senditem: [%s] -> [%s]" % (nm, value))
bdata = makebytes(value)
debprint(ioout, "%s->" % nm)
proto.breakwrite(ioout, bdata)
ioout.write(b'\n')