summaryrefslogtreecommitdiffstats
path: root/Tests/Server/cmakelib.py
blob: 546ae4cc551dd16e74f3f23e08467092e0b4688b (plain)
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
from __future__ import print_function
import sys, subprocess, json, os, select, shutil, time, socket

termwidth = 150

print_communication = True

def ordered(obj):
  if isinstance(obj, dict):
    return sorted((k, ordered(v)) for k, v in obj.items())
  if isinstance(obj, list):
    return sorted(ordered(x) for x in obj)
  else:
    return obj

def col_print(title, array):
  print()
  print()
  print(title)

  indentwidth = 4
  indent = " " * indentwidth

  if not array:
    print(indent + "<None>")
    return

  padwidth = 2

  maxitemwidth = len(max(array, key=len))

  numCols = max(1, int((termwidth - indentwidth + padwidth) / (maxitemwidth + padwidth)))

  numRows = len(array) // numCols + 1

  pad = " " * padwidth

  for index in range(numRows):
    print(indent + pad.join(item.ljust(maxitemwidth) for item in array[index::numRows]))

filterPacket = lambda x: x

STDIN = 0
PIPE = 1

communicationMethods = [STDIN]

if hasattr(socket, 'AF_UNIX'):
  communicationMethods.append(PIPE)

def defaultExitWithError(proc):
  data = ""
  try:
    while select.select([proc.outPipe], [], [], 3.)[0]:
      data = data + proc.outPipe.read(1)
    if len(data):
      print("Rest of raw buffer from server:")
      printServer(data)
  except:
    pass
  proc.outPipe.close()
  proc.inPipe.close()
  proc.kill()
  sys.exit(1)

exitWithError = lambda proc: defaultExitWithError(proc)

serverTag = "SERVER"

def printServer(*args):
    print(serverTag + ">", *args)
    print()
    sys.stdout.flush()

def printClient(*args):
    print("CLIENT>", *args)
    print()
    sys.stdout.flush()

def waitForRawMessage(cmakeCommand):
  stdoutdata = ""
  payload = ""
  while not cmakeCommand.poll():
    stdoutdataLine = cmakeCommand.outPipe.readline()
    if stdoutdataLine:
      stdoutdata += stdoutdataLine.decode('utf-8')
    else:
      break
    begin = stdoutdata.find('[== "CMake Server" ==[\n')
    end = stdoutdata.find(']== "CMake Server" ==]')

    if begin != -1 and end != -1:
      begin += len('[== "CMake Server" ==[\n')
      payload = stdoutdata[begin:end]
      jsonPayload = json.loads(payload)
      filteredPayload = filterPacket(jsonPayload)
      if print_communication and filteredPayload:
        printServer(filteredPayload)
      if filteredPayload is not None or jsonPayload is None:
          return jsonPayload
      stdoutdata = stdoutdata[(end+len(']== "CMake Server" ==]')):]

# Python2 has no problem writing the output of encodes directly,
# but Python3 returns only 'int's for encode and so must be turned
# into bytes. We use the existence of 'to_bytes' on an int to
# determine which behavior is appropriate. It might be more clear
# to do this in the code which uses the flag, but introducing
# this lookup cost at every byte sent isn't ideal.
has_to_bytes = "to_bytes" in dir(10)

def writeRawData(cmakeCommand, content):
  writeRawData.counter += 1
  payload = """
[== "CMake Server" ==[
%s
]== "CMake Server" ==]
""" % content

  rn = ( writeRawData.counter % 2 ) == 0

  if rn:
    payload = payload.replace('\n', '\r\n')

  if print_communication:
    printClient(content, "(Use \\r\\n:", rn, ")")

  # To stress test how cmake deals with fragmentation in the
  # communication channel, we send only one byte at a time.
  # Certain communication methods / platforms might still buffer
  # it all into one message since its so close together, but in
  # general this will catch places where we assume full buffers
  # come in all at once.
  encoded_payload = payload.encode('utf-8')

  # Python version 3+ can't write ints directly; but 'to_bytes'
  # for int was only added in python 3.2. If this is a 3+ version
  # of python without that conversion function; just write the whole
  # thing out at once.
  if sys.version_info[0] > 2 and not has_to_bytes:
    cmakeCommand.write(encoded_payload)
  else:
    for c in encoded_payload:
      if has_to_bytes:
        c = c.to_bytes(1, byteorder='big')
      cmakeCommand.write(c)

writeRawData.counter = 0

def writePayload(cmakeCommand, obj):
  writeRawData(cmakeCommand, json.dumps(obj))

def getPipeName():
  return "/tmp/server-test-socket"

def attachPipe(cmakeCommand, pipeName):
  time.sleep(1)
  sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  sock.connect(pipeName)
  global serverTag
  serverTag = "SERVER(PIPE)"
  cmakeCommand.outPipe = sock.makefile()
  cmakeCommand.inPipe = sock
  cmakeCommand.write = cmakeCommand.inPipe.sendall

def writeAndFlush(pipe, val):
  pipe.write(val)
  pipe.flush()

def initServerProc(cmakeCommand, comm):
  if comm == PIPE:
    pipeName = getPipeName()
    cmakeCommand = subprocess.Popen([cmakeCommand, "-E", "server", "--experimental", "--pipe=" + pipeName])
    attachPipe(cmakeCommand, pipeName)
  else:
    cmakeCommand = subprocess.Popen([cmakeCommand, "-E", "server", "--experimental", "--debug"],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE)
    cmakeCommand.outPipe = cmakeCommand.stdout
    cmakeCommand.inPipe = cmakeCommand.stdin
    cmakeCommand.write = lambda val: writeAndFlush(cmakeCommand.inPipe, val)

  packet = waitForRawMessage(cmakeCommand)
  if packet == None:
    print("Not in server mode")
    sys.exit(2)

  if packet['type'] != 'hello':
    print("No hello message")
    sys.exit(3)

  return cmakeCommand

def exitProc(cmakeCommand):
  # Tell the server to exit.
  cmakeCommand.stdin.close()
  cmakeCommand.stdout.close()

  # Wait for the server to exit.
  # If this version of python supports it, terminate the server after a timeout.
  try:
    cmakeCommand.wait(timeout=5)
  except TypeError:
    cmakeCommand.wait()
  except:
    cmakeCommand.terminate()
    raise

def waitForMessage(cmakeCommand, expected):
  data = ordered(expected)
  packet = ordered(waitForRawMessage(cmakeCommand))

  if packet != data:
    print ("Received unexpected message; test failed")
    exitWithError(cmakeCommand)
  return packet

def waitForReply(cmakeCommand, originalType, cookie, skipProgress):
  gotResult = False
  while True:
    packet = waitForRawMessage(cmakeCommand)
    t = packet['type']
    if packet['cookie'] != cookie or packet['inReplyTo'] != originalType:
      print("cookie or inReplyTo mismatch")
      sys.exit(4)
    if t == 'message' or t == 'progress':
      if skipProgress:
        continue
    if t == 'reply':
        break
    print("Unrecognized message", packet)
    sys.exit(5)

  return packet

def waitForError(cmakeCommand, originalType, cookie, message):
  packet = waitForRawMessage(cmakeCommand)
  if packet['cookie'] != cookie or packet['type'] != 'error' or packet['inReplyTo'] != originalType or packet['errorMessage'] != message:
    sys.exit(6)

def waitForProgress(cmakeCommand, originalType, cookie, current, message):
  packet = waitForRawMessage(cmakeCommand)
  if packet['cookie'] != cookie or packet['type'] != 'progress' or packet['inReplyTo'] != originalType or packet['progressCurrent'] != current or packet['progressMessage'] != message:
    sys.exit(7)

def handshake(cmakeCommand, major, minor, source, build, generator, extraGenerator):
  version = { 'major': major }
  if minor >= 0:
    version['minor'] = minor

  writePayload(cmakeCommand, { 'type': 'handshake', 'protocolVersion': version,
    'cookie': 'TEST_HANDSHAKE', 'sourceDirectory': source, 'buildDirectory': build,
    'generator': generator, 'extraGenerator': extraGenerator })
  waitForReply(cmakeCommand, 'handshake', 'TEST_HANDSHAKE', False)

def validateGlobalSettings(cmakeCommand, cmakeCommandPath, data):
  packet = waitForReply(cmakeCommand, 'globalSettings', '', False)

  capabilities = packet['capabilities']

  # validate version:
  cmakeoutput = subprocess.check_output([ cmakeCommandPath, "--version" ], universal_newlines=True)
  cmakeVersion = cmakeoutput.splitlines()[0][14:]

  version = capabilities['version']
  versionString = version['string']
  vs = str(version['major']) + '.' + str(version['minor']) + '.' + str(version['patch'])
  if (versionString != vs and not versionString.startswith(vs + '-')):
    sys.exit(8)
  if (versionString != cmakeVersion):
    sys.exit(9)

  # validate generators:
  generatorObjects = capabilities['generators']

  cmakeoutput = subprocess.check_output([ cmakeCommandPath, "--help" ], universal_newlines=True)
  index = cmakeoutput.index('\nGenerators\n\n')
  cmakeGenerators = []
  for line in cmakeoutput[index + 12:].splitlines():
    if not line:
      continue
    if line[0] == '*': # default generator marker
      line = ' ' + line[1:]
    if not line.startswith('  '):
      continue
    if line.startswith('    '):
      continue
    equalPos = line.find('=')
    tmp = ''
    if (equalPos > 0):
      tmp = line[2:equalPos].strip()
    else:
      tmp = line.strip()
    if tmp.endswith(" [arch]"):
      tmp = tmp[0:len(tmp) - 7]
    if (len(tmp) > 0) and (" - " not in tmp):
      cmakeGenerators.append(tmp)

  generators = []
  for genObj in generatorObjects:
    generators.append(genObj['name'])

  generators.sort()
  cmakeGenerators.sort()

  for gen in cmakeGenerators:
    if (not gen in generators):
        sys.exit(10)

  gen = packet['generator']
  if (gen != '' and not (gen in generators)):
    sys.exit(11)

  for i in data:
    print("Validating", i)
    if (packet[i] != data[i]):
      sys.exit(12)

def validateCache(cmakeCommand, data):
  packet = waitForReply(cmakeCommand, 'cache', '', False)

  cache = packet['cache']

  if (data['isEmpty']):
    if (cache != []):
      print('Expected empty cache, but got data.\n')
      sys.exit(1)
    return;

  if (cache == []):
    print('Expected cache contents, but got none.\n')
    sys.exit(1)

  hadHomeDir = False
  for value in cache:
    if (value['key'] == 'CMAKE_HOME_DIRECTORY'):
      hadHomeDir = True

  if (not hadHomeDir):
    print('No CMAKE_HOME_DIRECTORY found in cache.')
    sys.exit(1)

def handleBasicMessage(proc, obj, debug):
  if 'sendRaw' in obj:
    data = obj['sendRaw']
    if debug: print("Sending raw:", data)
    writeRawData(proc, data)
    return True
  elif 'send' in obj:
    data = obj['send']
    if debug: print("Sending:", json.dumps(data))
    writePayload(proc, data)
    return True
  elif 'recv' in obj:
    data = obj['recv']
    if debug: print("Waiting for:", json.dumps(data))
    waitForMessage(proc, data)
    return True
  elif 'message' in obj:
    print("MESSAGE:", obj["message"])
    sys.stdout.flush()
    return True
  return False

def shutdownProc(proc):
  # Tell the server to exit.
  proc.inPipe.close()
  proc.outPipe.close()

  # Wait for the server to exit.
  # If this version of python supports it, terminate the server after a timeout.
  try:
    proc.wait(timeout=5)
  except TypeError:
    proc.wait()
  except:
    proc.terminate()
    raise

  print('cmake-server exited: %d' % proc.returncode)
  sys.exit(proc.returncode)