blob: 3d31355fd465e70df349937ac893b2c435c88604 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#
2# BitBake Process based server.
3#
4# Copyright (C) 2010 Bob Foerster <robert@erafx.com>
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License version 2 as
8# published by the Free Software Foundation.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License along
16# with this program; if not, write to the Free Software Foundation, Inc.,
17# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19"""
20 This module implements a multiprocessing.Process based server for bitbake.
21"""
22
23import bb
24import bb.event
Patrick Williamsc124f4f2015-09-15 14:41:29 -050025import logging
26import multiprocessing
Brad Bishopd7bf8c12018-02-25 22:55:05 -050027import threading
28import array
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029import os
Patrick Williamsc124f4f2015-09-15 14:41:29 -050030import sys
31import time
32import select
Brad Bishopd7bf8c12018-02-25 22:55:05 -050033import socket
34import subprocess
35import errno
36import re
37import datetime
38import bb.server.xmlrpcserver
39from bb import daemonize
40from multiprocessing import queues
Patrick Williamsc124f4f2015-09-15 14:41:29 -050041
42logger = logging.getLogger('BitBake')
43
Brad Bishopd7bf8c12018-02-25 22:55:05 -050044class ProcessTimeout(SystemExit):
45 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -050046
Brad Bishopd7bf8c12018-02-25 22:55:05 -050047class ProcessServer(multiprocessing.Process):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050048 profile_filename = "profile.log"
49 profile_processed_filename = "profile.log.processed"
50
Brad Bishopd7bf8c12018-02-25 22:55:05 -050051 def __init__(self, lock, sock, sockname):
52 multiprocessing.Process.__init__(self)
53 self.command_channel = False
54 self.command_channel_reply = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050055 self.quit = False
Brad Bishop6e60e8b2018-02-01 10:27:11 -050056 self.heartbeat_seconds = 1 # default, BB_HEARTBEAT_EVENT will be checked once we have a datastore.
57 self.next_heartbeat = time.time()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050058
Brad Bishopd7bf8c12018-02-25 22:55:05 -050059 self.event_handle = None
60 self.haveui = False
61 self.lastui = False
62 self.xmlrpc = False
63
64 self._idlefuns = {}
65
66 self.bitbake_lock = lock
67 self.sock = sock
68 self.sockname = sockname
69
70 def register_idle_function(self, function, data):
71 """Register a function to be called while the server is idle"""
72 assert hasattr(function, '__call__')
73 self._idlefuns[function] = data
Patrick Williamsc124f4f2015-09-15 14:41:29 -050074
75 def run(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050076
77 if self.xmlrpcinterface[0]:
78 self.xmlrpc = bb.server.xmlrpcserver.BitBakeXMLRPCServer(self.xmlrpcinterface, self.cooker, self)
79
80 print("Bitbake XMLRPC server address: %s, server port: %s" % (self.xmlrpc.host, self.xmlrpc.port))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050081
Brad Bishop6e60e8b2018-02-01 10:27:11 -050082 heartbeat_event = self.cooker.data.getVar('BB_HEARTBEAT_EVENT')
83 if heartbeat_event:
84 try:
85 self.heartbeat_seconds = float(heartbeat_event)
86 except:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050087 bb.warn('Ignoring invalid BB_HEARTBEAT_EVENT=%s, must be a float specifying seconds.' % heartbeat_event)
Brad Bishopd7bf8c12018-02-25 22:55:05 -050088
89 self.timeout = self.server_timeout or self.cooker.data.getVar('BB_SERVER_TIMEOUT')
90 try:
91 if self.timeout:
92 self.timeout = float(self.timeout)
93 except:
94 bb.warn('Ignoring invalid BB_SERVER_TIMEOUT=%s, must be a float specifying seconds.' % self.timeout)
95
96
97 try:
98 self.bitbake_lock.seek(0)
99 self.bitbake_lock.truncate()
100 if self.xmlrpc:
101 self.bitbake_lock.write("%s %s:%s\n" % (os.getpid(), self.xmlrpc.host, self.xmlrpc.port))
102 else:
103 self.bitbake_lock.write("%s\n" % (os.getpid()))
104 self.bitbake_lock.flush()
105 except Exception as e:
106 print("Error writing to lock file: %s" % str(e))
107 pass
108
109 if self.cooker.configuration.profile:
110 try:
111 import cProfile as profile
112 except:
113 import profile
114 prof = profile.Profile()
115
116 ret = profile.Profile.runcall(prof, self.main)
117
118 prof.dump_stats("profile.log")
119 bb.utils.process_profilelog("profile.log")
120 print("Raw profiling information saved to profile.log and processed statistics to profile.log.processed")
121
122 else:
123 ret = self.main()
124
125 return ret
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500126
127 def main(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500128 self.cooker.pre_serve()
129
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500130 bb.utils.set_process_name("Cooker")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500131
132 ready = []
133
134 self.controllersock = False
135 fds = [self.sock]
136 if self.xmlrpc:
137 fds.append(self.xmlrpc)
138 print("Entering server connection loop")
139
140 def disconnect_client(self, fds):
141 if not self.haveui:
142 return
143 print("Disconnecting Client")
144 fds.remove(self.controllersock)
145 fds.remove(self.command_channel)
146 bb.event.unregister_UIHhandler(self.event_handle, True)
147 self.command_channel_reply.writer.close()
148 self.event_writer.writer.close()
149 del self.event_writer
150 self.controllersock.close()
151 self.controllersock = False
152 self.haveui = False
153 self.lastui = time.time()
154 self.cooker.clientComplete()
155 if self.timeout is None:
156 print("No timeout, exiting.")
157 self.quit = True
158
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500159 while not self.quit:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500160 if self.sock in ready:
161 self.controllersock, address = self.sock.accept()
162 if self.haveui:
163 print("Dropping connection attempt as we have a UI %s" % (str(ready)))
164 self.controllersock.close()
165 else:
166 print("Accepting %s" % (str(ready)))
167 fds.append(self.controllersock)
168 if self.controllersock in ready:
169 try:
170 print("Connecting Client")
171 ui_fds = recvfds(self.controllersock, 3)
172
173 # Where to write events to
174 writer = ConnectionWriter(ui_fds[0])
175 self.event_handle = bb.event.register_UIHhandler(writer, True)
176 self.event_writer = writer
177
178 # Where to read commands from
179 reader = ConnectionReader(ui_fds[1])
180 fds.append(reader)
181 self.command_channel = reader
182
183 # Where to send command return values to
184 writer = ConnectionWriter(ui_fds[2])
185 self.command_channel_reply = writer
186
187 self.haveui = True
188
189 except (EOFError, OSError):
190 disconnect_client(self, fds)
191
192 if not self.timeout == -1.0 and not self.haveui and self.lastui and self.timeout and \
193 (self.lastui + self.timeout) < time.time():
194 print("Server timeout, exiting.")
195 self.quit = True
196
197 if self.command_channel in ready:
198 try:
199 command = self.command_channel.get()
200 except EOFError:
201 # Client connection shutting down
202 ready = []
203 disconnect_client(self, fds)
204 continue
205 if command[0] == "terminateServer":
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500206 self.quit = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500207 continue
208 try:
209 print("Running command %s" % command)
210 self.command_channel_reply.send(self.cooker.command.runCommand(command))
211 except Exception as e:
212 logger.exception('Exception in server main event loop running command %s (%s)' % (command, str(e)))
213
214 if self.xmlrpc in ready:
215 self.xmlrpc.handle_requests()
216
217 ready = self.idle_commands(.1, fds)
218
219 print("Exiting")
220 # Remove the socket file so we don't get any more connections to avoid races
221 os.unlink(self.sockname)
222 self.sock.close()
223
224 try:
225 self.cooker.shutdown(True)
226 except:
227 pass
228
229 self.cooker.post_serve()
230
231 # Finally release the lockfile but warn about other processes holding it open
232 lock = self.bitbake_lock
233 lockfile = lock.name
234 lock.close()
235 lock = None
236
237 while not lock:
238 with bb.utils.timeout(3):
239 lock = bb.utils.lockfile(lockfile, shared=False, retry=False, block=True)
240 if not lock:
241 # Some systems may not have lsof available
242 procs = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500243 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500244 procs = subprocess.check_output(["lsof", '-w', lockfile], stderr=subprocess.STDOUT)
245 except OSError as e:
246 if e.errno != errno.ENOENT:
247 raise
248 if procs is None:
249 # Fall back to fuser if lsof is unavailable
250 try:
251 procs = subprocess.check_output(["fuser", '-v', lockfile], stderr=subprocess.STDOUT)
252 except OSError as e:
253 if e.errno != errno.ENOENT:
254 raise
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500255
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500256 msg = "Delaying shutdown due to active processes which appear to be holding bitbake.lock"
257 if procs:
258 msg += ":\n%s" % str(procs)
259 print(msg)
260 return
261 # We hold the lock so we can remove the file (hide stale pid data)
262 bb.utils.remove(lockfile)
263 bb.utils.unlockfile(lock)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500264
265 def idle_commands(self, delay, fds=None):
266 nextsleep = delay
267 if not fds:
268 fds = []
269
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600270 for function, data in list(self._idlefuns.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500271 try:
272 retval = function(self, data, False)
273 if retval is False:
274 del self._idlefuns[function]
275 nextsleep = None
276 elif retval is True:
277 nextsleep = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600278 elif isinstance(retval, float) and nextsleep:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500279 if (retval < nextsleep):
280 nextsleep = retval
281 elif nextsleep is None:
282 continue
283 else:
284 fds = fds + retval
285 except SystemExit:
286 raise
287 except Exception as exc:
288 if not isinstance(exc, bb.BBHandledException):
289 logger.exception('Running idle function')
290 del self._idlefuns[function]
291 self.quit = True
292
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500293 # Create new heartbeat event?
294 now = time.time()
295 if now >= self.next_heartbeat:
296 # We might have missed heartbeats. Just trigger once in
297 # that case and continue after the usual delay.
298 self.next_heartbeat += self.heartbeat_seconds
299 if self.next_heartbeat <= now:
300 self.next_heartbeat = now + self.heartbeat_seconds
301 heartbeat = bb.event.HeartbeatEvent(now)
302 bb.event.fire(heartbeat, self.cooker.data)
303 if nextsleep and now + nextsleep > self.next_heartbeat:
304 # Shorten timeout so that we we wake up in time for
305 # the heartbeat.
306 nextsleep = self.next_heartbeat - now
307
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500308 if nextsleep is not None:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500309 if self.xmlrpc:
310 nextsleep = self.xmlrpc.get_timeout(nextsleep)
311 try:
312 return select.select(fds,[],[],nextsleep)[0]
313 except InterruptedError:
314 # Ignore EINTR
315 return []
316 else:
317 return select.select(fds,[],[],0)[0]
318
319
320class ServerCommunicator():
321 def __init__(self, connection, recv):
322 self.connection = connection
323 self.recv = recv
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500324
325 def runCommand(self, command):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500326 self.connection.send(command)
327 if not self.recv.poll(30):
328 raise ProcessTimeout("Timeout while waiting for a reply from the bitbake server")
329 return self.recv.get()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500330
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500331 def updateFeatureSet(self, featureset):
332 _, error = self.runCommand(["setFeatures", featureset])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500333 if error:
334 logger.error("Unable to set the cooker to the correct featureset: %s" % error)
335 raise BaseException(error)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500336
337 def getEventHandle(self):
338 handle, error = self.runCommand(["getUIHandlerNum"])
339 if error:
340 logger.error("Unable to get UI Handler Number: %s" % error)
341 raise BaseException(error)
342
343 return handle
344
345 def terminateServer(self):
346 self.connection.send(['terminateServer'])
347 return
348
349class BitBakeProcessServerConnection(object):
350 def __init__(self, ui_channel, recv, eq, sock):
351 self.connection = ServerCommunicator(ui_channel, recv)
352 self.events = eq
353 # Save sock so it doesn't get gc'd for the life of our connection
354 self.socket_connection = sock
355
356 def terminate(self):
357 self.socket_connection.close()
358 self.connection.connection.close()
359 self.connection.recv.close()
360 return
361
362class BitBakeServer(object):
363 start_log_format = '--- Starting bitbake server pid %s at %s ---'
364 start_log_datetime_format = '%Y-%m-%d %H:%M:%S.%f'
365
366 def __init__(self, lock, sockname, configuration, featureset):
367
368 self.configuration = configuration
369 self.featureset = featureset
370 self.sockname = sockname
371 self.bitbake_lock = lock
372 self.readypipe, self.readypipein = os.pipe()
373
374 # Create server control socket
375 if os.path.exists(sockname):
376 os.unlink(sockname)
377
378 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
379 # AF_UNIX has path length issues so chdir here to workaround
380 cwd = os.getcwd()
381 logfile = os.path.join(cwd, "bitbake-cookerdaemon.log")
382
383 try:
384 os.chdir(os.path.dirname(sockname))
385 self.sock.bind(os.path.basename(sockname))
386 finally:
387 os.chdir(cwd)
388 self.sock.listen(1)
389
390 os.set_inheritable(self.sock.fileno(), True)
391 startdatetime = datetime.datetime.now()
392 bb.daemonize.createDaemon(self._startServer, logfile)
393 self.sock.close()
394 self.bitbake_lock.close()
395
396 ready = ConnectionReader(self.readypipe)
397 r = ready.poll(30)
398 if r:
399 r = ready.get()
400 if not r or r != "ready":
401 ready.close()
402 bb.error("Unable to start bitbake server")
403 if os.path.exists(logfile):
404 logstart_re = re.compile(self.start_log_format % ('([0-9]+)', '([0-9-]+ [0-9:.]+)'))
405 started = False
406 lines = []
407 with open(logfile, "r") as f:
408 for line in f:
409 if started:
410 lines.append(line)
411 else:
412 res = logstart_re.match(line.rstrip())
413 if res:
414 ldatetime = datetime.datetime.strptime(res.group(2), self.start_log_datetime_format)
415 if ldatetime >= startdatetime:
416 started = True
417 lines.append(line)
418 if lines:
419 if len(lines) > 10:
420 bb.error("Last 10 lines of server log for this session (%s):\n%s" % (logfile, "".join(lines[-10:])))
421 else:
422 bb.error("Server log for this session (%s):\n%s" % (logfile, "".join(lines)))
423 raise SystemExit(1)
424 ready.close()
425 os.close(self.readypipein)
426
427 def _startServer(self):
428 print(self.start_log_format % (os.getpid(), datetime.datetime.now().strftime(self.start_log_datetime_format)))
429 server = ProcessServer(self.bitbake_lock, self.sock, self.sockname)
430 self.configuration.setServerRegIdleCallback(server.register_idle_function)
431 writer = ConnectionWriter(self.readypipein)
432 try:
433 self.cooker = bb.cooker.BBCooker(self.configuration, self.featureset)
434 writer.send("ready")
435 except:
436 writer.send("fail")
437 raise
438 finally:
439 os.close(self.readypipein)
440 server.cooker = self.cooker
441 server.server_timeout = self.configuration.server_timeout
442 server.xmlrpcinterface = self.configuration.xmlrpcinterface
443 print("Started bitbake server pid %d" % os.getpid())
444 server.start()
445
446def connectProcessServer(sockname, featureset):
447 # Connect to socket
448 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
449 # AF_UNIX has path length issues so chdir here to workaround
450 cwd = os.getcwd()
451
452 try:
453 os.chdir(os.path.dirname(sockname))
454 sock.connect(os.path.basename(sockname))
455 finally:
456 os.chdir(cwd)
457
458 readfd = writefd = readfd1 = writefd1 = readfd2 = writefd2 = None
459 eq = command_chan_recv = command_chan = None
460
461 try:
462
463 # Send an fd for the remote to write events to
464 readfd, writefd = os.pipe()
465 eq = BBUIEventQueue(readfd)
466 # Send an fd for the remote to recieve commands from
467 readfd1, writefd1 = os.pipe()
468 command_chan = ConnectionWriter(writefd1)
469 # Send an fd for the remote to write commands results to
470 readfd2, writefd2 = os.pipe()
471 command_chan_recv = ConnectionReader(readfd2)
472
473 sendfds(sock, [writefd, readfd1, writefd2])
474
475 server_connection = BitBakeProcessServerConnection(command_chan, command_chan_recv, eq, sock)
476
477 # Close the ends of the pipes we won't use
478 for i in [writefd, readfd1, writefd2]:
479 os.close(i)
480
481 server_connection.connection.updateFeatureSet(featureset)
482
483 except (Exception, SystemExit) as e:
484 if command_chan_recv:
485 command_chan_recv.close()
486 if command_chan:
487 command_chan.close()
488 for i in [writefd, readfd1, writefd2]:
489 try:
490 os.close(i)
491 except OSError:
492 pass
493 sock.close()
494 raise
495
496 return server_connection
497
498def sendfds(sock, fds):
499 '''Send an array of fds over an AF_UNIX socket.'''
500 fds = array.array('i', fds)
501 msg = bytes([len(fds) % 256])
502 sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
503
504def recvfds(sock, size):
505 '''Receive an array of fds over an AF_UNIX socket.'''
506 a = array.array('i')
507 bytes_size = a.itemsize * size
508 msg, ancdata, flags, addr = sock.recvmsg(1, socket.CMSG_LEN(bytes_size))
509 if not msg and not ancdata:
510 raise EOFError
511 try:
512 if len(ancdata) != 1:
513 raise RuntimeError('received %d items of ancdata' %
514 len(ancdata))
515 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
516 if (cmsg_level == socket.SOL_SOCKET and
517 cmsg_type == socket.SCM_RIGHTS):
518 if len(cmsg_data) % a.itemsize != 0:
519 raise ValueError
520 a.frombytes(cmsg_data)
521 assert len(a) % 256 == msg[0]
522 return list(a)
523 except (ValueError, IndexError):
524 pass
525 raise RuntimeError('Invalid data received')
526
527class BBUIEventQueue:
528 def __init__(self, readfd):
529
530 self.eventQueue = []
531 self.eventQueueLock = threading.Lock()
532 self.eventQueueNotify = threading.Event()
533
534 self.reader = ConnectionReader(readfd)
535
536 self.t = threading.Thread()
537 self.t.setDaemon(True)
538 self.t.run = self.startCallbackHandler
539 self.t.start()
540
541 def getEvent(self):
542 self.eventQueueLock.acquire()
543
544 if len(self.eventQueue) == 0:
545 self.eventQueueLock.release()
546 return None
547
548 item = self.eventQueue.pop(0)
549
550 if len(self.eventQueue) == 0:
551 self.eventQueueNotify.clear()
552
553 self.eventQueueLock.release()
554 return item
555
556 def waitEvent(self, delay):
557 self.eventQueueNotify.wait(delay)
558 return self.getEvent()
559
560 def queue_event(self, event):
561 self.eventQueueLock.acquire()
562 self.eventQueue.append(event)
563 self.eventQueueNotify.set()
564 self.eventQueueLock.release()
565
566 def send_event(self, event):
567 self.queue_event(pickle.loads(event))
568
569 def startCallbackHandler(self):
570 bb.utils.set_process_name("UIEventQueue")
571 while True:
572 try:
573 self.reader.wait()
574 event = self.reader.get()
575 self.queue_event(event)
576 except EOFError:
577 # Easiest way to exit is to close the file descriptor to cause an exit
578 break
579 self.reader.close()
580
581class ConnectionReader(object):
582
583 def __init__(self, fd):
584 self.reader = multiprocessing.connection.Connection(fd, writable=False)
585 self.rlock = multiprocessing.Lock()
586
587 def wait(self, timeout=None):
588 return multiprocessing.connection.wait([self.reader], timeout)
589
590 def poll(self, timeout=None):
591 return self.reader.poll(timeout)
592
593 def get(self):
594 with self.rlock:
595 res = self.reader.recv_bytes()
596 return multiprocessing.reduction.ForkingPickler.loads(res)
597
598 def fileno(self):
599 return self.reader.fileno()
600
601 def close(self):
602 return self.reader.close()
603
604
605class ConnectionWriter(object):
606
607 def __init__(self, fd):
608 self.writer = multiprocessing.connection.Connection(fd, readable=False)
609 self.wlock = multiprocessing.Lock()
610 # Why bb.event needs this I have no idea
611 self.event = self
612
613 def send(self, obj):
614 obj = multiprocessing.reduction.ForkingPickler.dumps(obj)
615 with self.wlock:
616 self.writer.send_bytes(obj)
617
618 def fileno(self):
619 return self.writer.fileno()
620
621 def close(self):
622 return self.writer.close()