blob: 6d77ce4786c69fed1a87560ec78671ec573ef8e3 [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#
Brad Bishopc342db32019-05-15 21:57:59 -04006# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -05007#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05008
9"""
10 This module implements a multiprocessing.Process based server for bitbake.
11"""
12
13import bb
14import bb.event
Patrick Williamsc124f4f2015-09-15 14:41:29 -050015import logging
16import multiprocessing
Brad Bishopd7bf8c12018-02-25 22:55:05 -050017import threading
18import array
Patrick Williamsc124f4f2015-09-15 14:41:29 -050019import os
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020import sys
21import time
22import select
Brad Bishopd7bf8c12018-02-25 22:55:05 -050023import socket
24import subprocess
25import errno
26import re
27import datetime
Andrew Geisslerc9f78652020-09-18 14:11:35 -050028import pickle
Patrick Williams213cb262021-08-07 19:21:33 -050029import traceback
Patrick Williamsde0582f2022-04-08 10:23:27 -050030import gc
Andrew Geissler517393d2023-01-13 08:55:19 -060031import stat
Brad Bishopd7bf8c12018-02-25 22:55:05 -050032import bb.server.xmlrpcserver
33from bb import daemonize
34from multiprocessing import queues
Patrick Williamsc124f4f2015-09-15 14:41:29 -050035
36logger = logging.getLogger('BitBake')
37
Brad Bishopd7bf8c12018-02-25 22:55:05 -050038class ProcessTimeout(SystemExit):
39 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -050040
Andrew Geissler5082cc72023-09-11 08:41:39 -040041def currenttime():
42 return datetime.datetime.now().strftime('%H:%M:%S.%f')
43
Andrew Geisslerc9f78652020-09-18 14:11:35 -050044def serverlog(msg):
Andrew Geissler5082cc72023-09-11 08:41:39 -040045 print(str(os.getpid()) + " " + currenttime() + " " + msg)
Andrew Geissler220dafd2023-10-04 10:18:08 -050046 #Seems a flush here triggers filesytem sync like behaviour and long hangs in the server
47 #sys.stdout.flush()
Andrew Geisslerc9f78652020-09-18 14:11:35 -050048
Andrew Geissler517393d2023-01-13 08:55:19 -060049#
50# When we have lockfile issues, try and find infomation about which process is
51# using the lockfile
52#
53def get_lockfile_process_msg(lockfile):
54 # Some systems may not have lsof available
55 procs = None
56 try:
57 procs = subprocess.check_output(["lsof", '-w', lockfile], stderr=subprocess.STDOUT)
58 except subprocess.CalledProcessError:
59 # File was deleted?
60 pass
61 except OSError as e:
62 if e.errno != errno.ENOENT:
63 raise
64 if procs is None:
65 # Fall back to fuser if lsof is unavailable
66 try:
67 procs = subprocess.check_output(["fuser", '-v', lockfile], stderr=subprocess.STDOUT)
68 except subprocess.CalledProcessError:
69 # File was deleted?
70 pass
71 except OSError as e:
72 if e.errno != errno.ENOENT:
73 raise
74 if procs:
75 return procs.decode("utf-8")
76 return None
77
78class idleFinish():
79 def __init__(self, msg):
80 self.msg = msg
81
Andrew Geissler635e0e42020-08-21 15:58:33 -050082class ProcessServer():
Patrick Williamsc124f4f2015-09-15 14:41:29 -050083 profile_filename = "profile.log"
84 profile_processed_filename = "profile.log.processed"
85
Andrew Geisslerc9f78652020-09-18 14:11:35 -050086 def __init__(self, lock, lockname, sock, sockname, server_timeout, xmlrpcinterface):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050087 self.command_channel = False
88 self.command_channel_reply = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050089 self.quit = False
Brad Bishop6e60e8b2018-02-01 10:27:11 -050090 self.heartbeat_seconds = 1 # default, BB_HEARTBEAT_EVENT will be checked once we have a datastore.
91 self.next_heartbeat = time.time()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050092
Brad Bishopd7bf8c12018-02-25 22:55:05 -050093 self.event_handle = None
Andrew Geissler635e0e42020-08-21 15:58:33 -050094 self.hadanyui = False
Brad Bishopd7bf8c12018-02-25 22:55:05 -050095 self.haveui = False
Andrew Geisslerb7d28612020-07-24 16:15:54 -050096 self.maxuiwait = 30
Brad Bishopd7bf8c12018-02-25 22:55:05 -050097 self.xmlrpc = False
98
Andrew Geissler517393d2023-01-13 08:55:19 -060099 self.idle = None
100 # Need a lock for _idlefuns changes
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500101 self._idlefuns = {}
Andrew Geissler517393d2023-01-13 08:55:19 -0600102 self._idlefuncsLock = threading.Lock()
103 self.idle_cond = threading.Condition(self._idlefuncsLock)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500104
105 self.bitbake_lock = lock
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500106 self.bitbake_lock_name = lockname
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500107 self.sock = sock
108 self.sockname = sockname
Andrew Geissler517393d2023-01-13 08:55:19 -0600109 # It is possible the directory may be renamed. Cache the inode of the socket file
110 # so we can tell if things changed.
111 self.sockinode = os.stat(self.sockname)[stat.ST_INO]
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500112
Andrew Geissler635e0e42020-08-21 15:58:33 -0500113 self.server_timeout = server_timeout
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500114 self.timeout = self.server_timeout
Andrew Geissler635e0e42020-08-21 15:58:33 -0500115 self.xmlrpcinterface = xmlrpcinterface
116
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500117 def register_idle_function(self, function, data):
118 """Register a function to be called while the server is idle"""
119 assert hasattr(function, '__call__')
Andrew Geissler517393d2023-01-13 08:55:19 -0600120 with bb.utils.lock_timeout(self._idlefuncsLock):
121 self._idlefuns[function] = data
122 serverlog("Registering idle function %s" % str(function))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500123
124 def run(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500125
126 if self.xmlrpcinterface[0]:
127 self.xmlrpc = bb.server.xmlrpcserver.BitBakeXMLRPCServer(self.xmlrpcinterface, self.cooker, self)
128
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500129 serverlog("Bitbake XMLRPC server address: %s, server port: %s" % (self.xmlrpc.host, self.xmlrpc.port))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500130
131 try:
132 self.bitbake_lock.seek(0)
133 self.bitbake_lock.truncate()
134 if self.xmlrpc:
135 self.bitbake_lock.write("%s %s:%s\n" % (os.getpid(), self.xmlrpc.host, self.xmlrpc.port))
136 else:
137 self.bitbake_lock.write("%s\n" % (os.getpid()))
138 self.bitbake_lock.flush()
139 except Exception as e:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500140 serverlog("Error writing to lock file: %s" % str(e))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500141 pass
142
143 if self.cooker.configuration.profile:
144 try:
145 import cProfile as profile
146 except:
147 import profile
148 prof = profile.Profile()
149
150 ret = profile.Profile.runcall(prof, self.main)
151
152 prof.dump_stats("profile.log")
153 bb.utils.process_profilelog("profile.log")
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500154 serverlog("Raw profiling information saved to profile.log and processed statistics to profile.log.processed")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500155
156 else:
157 ret = self.main()
158
159 return ret
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500160
Andrew Geissler517393d2023-01-13 08:55:19 -0600161 def _idle_check(self):
162 return len(self._idlefuns) == 0 and self.cooker.command.currentAsyncCommand is None
163
164 def wait_for_idle(self, timeout=30):
165 # Wait for the idle loop to have cleared
166 with bb.utils.lock_timeout(self._idlefuncsLock):
167 return self.idle_cond.wait_for(self._idle_check, timeout) is not False
168
169 def set_async_cmd(self, cmd):
170 with bb.utils.lock_timeout(self._idlefuncsLock):
171 ret = self.idle_cond.wait_for(self._idle_check, 30)
172 if ret is False:
173 return False
174 self.cooker.command.currentAsyncCommand = cmd
175 return True
176
177 def clear_async_cmd(self):
178 with bb.utils.lock_timeout(self._idlefuncsLock):
179 self.cooker.command.currentAsyncCommand = None
180 self.idle_cond.notify_all()
181
182 def get_async_cmd(self):
183 with bb.utils.lock_timeout(self._idlefuncsLock):
184 return self.cooker.command.currentAsyncCommand
185
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500186 def main(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500187 self.cooker.pre_serve()
188
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500189 bb.utils.set_process_name("Cooker")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500190
191 ready = []
Brad Bishopf058f492019-01-28 23:50:33 -0500192 newconnections = []
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500193
194 self.controllersock = False
195 fds = [self.sock]
196 if self.xmlrpc:
197 fds.append(self.xmlrpc)
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500198 seendata = False
199 serverlog("Entering server connection loop")
Andrew Geissler517393d2023-01-13 08:55:19 -0600200 serverlog("Lockfile is: %s\nSocket is %s (%s)" % (self.bitbake_lock_name, self.sockname, os.path.exists(self.sockname)))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500201
202 def disconnect_client(self, fds):
Andrew Geissler517393d2023-01-13 08:55:19 -0600203 serverlog("Disconnecting Client (socket: %s)" % os.path.exists(self.sockname))
Brad Bishopf058f492019-01-28 23:50:33 -0500204 if self.controllersock:
205 fds.remove(self.controllersock)
206 self.controllersock.close()
207 self.controllersock = False
208 if self.haveui:
Andrew Geissler517393d2023-01-13 08:55:19 -0600209 # Wait for the idle loop to have cleared (30s max)
210 if not self.wait_for_idle(30):
211 serverlog("Idle loop didn't finish queued commands after 30s, exiting.")
212 self.quit = True
Brad Bishopf058f492019-01-28 23:50:33 -0500213 fds.remove(self.command_channel)
214 bb.event.unregister_UIHhandler(self.event_handle, True)
215 self.command_channel_reply.writer.close()
216 self.event_writer.writer.close()
217 self.command_channel.close()
218 self.command_channel = False
219 del self.event_writer
220 self.lastui = time.time()
221 self.cooker.clientComplete()
222 self.haveui = False
223 ready = select.select(fds,[],[],0)[0]
Andrew Geissler517393d2023-01-13 08:55:19 -0600224 if newconnections and not self.quit:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500225 serverlog("Starting new client")
Brad Bishopf058f492019-01-28 23:50:33 -0500226 conn = newconnections.pop(-1)
227 fds.append(conn)
228 self.controllersock = conn
Andrew Geissler5f350902021-07-23 13:09:54 -0400229 elif not self.timeout and not ready:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500230 serverlog("No timeout, exiting.")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500231 self.quit = True
232
Andrew Geisslerb7d28612020-07-24 16:15:54 -0500233 self.lastui = time.time()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500234 while not self.quit:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500235 if self.sock in ready:
Brad Bishopf058f492019-01-28 23:50:33 -0500236 while select.select([self.sock],[],[],0)[0]:
237 controllersock, address = self.sock.accept()
238 if self.controllersock:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500239 serverlog("Queuing %s (%s)" % (str(ready), str(newconnections)))
Brad Bishopf058f492019-01-28 23:50:33 -0500240 newconnections.append(controllersock)
241 else:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500242 serverlog("Accepting %s (%s)" % (str(ready), str(newconnections)))
Brad Bishopf058f492019-01-28 23:50:33 -0500243 self.controllersock = controllersock
244 fds.append(controllersock)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500245 if self.controllersock in ready:
246 try:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500247 serverlog("Processing Client")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500248 ui_fds = recvfds(self.controllersock, 3)
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500249 serverlog("Connecting Client")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500250
251 # Where to write events to
252 writer = ConnectionWriter(ui_fds[0])
253 self.event_handle = bb.event.register_UIHhandler(writer, True)
254 self.event_writer = writer
255
256 # Where to read commands from
257 reader = ConnectionReader(ui_fds[1])
258 fds.append(reader)
259 self.command_channel = reader
260
261 # Where to send command return values to
262 writer = ConnectionWriter(ui_fds[2])
263 self.command_channel_reply = writer
264
265 self.haveui = True
Andrew Geissler635e0e42020-08-21 15:58:33 -0500266 self.hadanyui = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500267
268 except (EOFError, OSError):
269 disconnect_client(self, fds)
270
Andrew Geisslerb7d28612020-07-24 16:15:54 -0500271 if not self.timeout == -1.0 and not self.haveui and self.timeout and \
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500272 (self.lastui + self.timeout) < time.time():
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500273 serverlog("Server timeout, exiting.")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500274 self.quit = True
275
Andrew Geisslerb7d28612020-07-24 16:15:54 -0500276 # If we don't see a UI connection within maxuiwait, its unlikely we're going to see
277 # one. We have had issue with processes hanging indefinitely so timing out UI-less
278 # servers is useful.
Andrew Geissler635e0e42020-08-21 15:58:33 -0500279 if not self.hadanyui and not self.xmlrpc and not self.timeout and (self.lastui + self.maxuiwait) < time.time():
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500280 serverlog("No UI connection within max timeout, exiting to avoid infinite loop.")
Andrew Geisslerb7d28612020-07-24 16:15:54 -0500281 self.quit = True
282
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500283 if self.command_channel in ready:
284 try:
285 command = self.command_channel.get()
286 except EOFError:
287 # Client connection shutting down
288 ready = []
289 disconnect_client(self, fds)
290 continue
291 if command[0] == "terminateServer":
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500292 self.quit = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500293 continue
294 try:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500295 serverlog("Running command %s" % command)
Andrew Geissler5082cc72023-09-11 08:41:39 -0400296 reply = self.cooker.command.runCommand(command, self)
297 serverlog("Sending reply %s" % repr(reply))
298 self.command_channel_reply.send(reply)
Andrew Geissler517393d2023-01-13 08:55:19 -0600299 serverlog("Command Completed (socket: %s)" % os.path.exists(self.sockname))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500300 except Exception as e:
Patrick Williams213cb262021-08-07 19:21:33 -0500301 stack = traceback.format_exc()
302 serverlog('Exception in server main event loop running command %s (%s)' % (command, stack))
303 logger.exception('Exception in server main event loop running command %s (%s)' % (command, stack))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500304
305 if self.xmlrpc in ready:
306 self.xmlrpc.handle_requests()
307
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500308 if not seendata and hasattr(self.cooker, "data"):
309 heartbeat_event = self.cooker.data.getVar('BB_HEARTBEAT_EVENT')
310 if heartbeat_event:
311 try:
312 self.heartbeat_seconds = float(heartbeat_event)
313 except:
314 bb.warn('Ignoring invalid BB_HEARTBEAT_EVENT=%s, must be a float specifying seconds.' % heartbeat_event)
315
316 self.timeout = self.server_timeout or self.cooker.data.getVar('BB_SERVER_TIMEOUT')
317 try:
318 if self.timeout:
319 self.timeout = float(self.timeout)
320 except:
321 bb.warn('Ignoring invalid BB_SERVER_TIMEOUT=%s, must be a float specifying seconds.' % self.timeout)
322 seendata = True
323
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500324 ready = self.idle_commands(.1, fds)
325
Andrew Geissler517393d2023-01-13 08:55:19 -0600326 if self.idle:
327 self.idle.join()
328
329 serverlog("Exiting (socket: %s)" % os.path.exists(self.sockname))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500330 # Remove the socket file so we don't get any more connections to avoid races
Andrew Geissler517393d2023-01-13 08:55:19 -0600331 # The build directory could have been renamed so if the file isn't the one we created
332 # we shouldn't delete it.
Andrew Geisslerb7d28612020-07-24 16:15:54 -0500333 try:
Andrew Geissler517393d2023-01-13 08:55:19 -0600334 sockinode = os.stat(self.sockname)[stat.ST_INO]
335 if sockinode == self.sockinode:
336 os.unlink(self.sockname)
337 else:
338 serverlog("bitbake.sock inode mismatch (%s vs %s), not deleting." % (sockinode, self.sockinode))
339 except Exception as err:
340 serverlog("Removing socket file '%s' failed (%s)" % (self.sockname, err))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500341 self.sock.close()
342
Andrew Geisslerb7d28612020-07-24 16:15:54 -0500343 try:
Andrew Geissler517393d2023-01-13 08:55:19 -0600344 self.cooker.shutdown(True, idle=False)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400345 self.cooker.notifier.stop()
346 self.cooker.confignotifier.stop()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500347 except:
348 pass
349
350 self.cooker.post_serve()
351
Andrew Geissler9aee5002022-03-30 16:27:02 +0000352 if len(threading.enumerate()) != 1:
353 serverlog("More than one thread left?: " + str(threading.enumerate()))
354
Andrew Geissler635e0e42020-08-21 15:58:33 -0500355 # Flush logs before we release the lock
356 sys.stdout.flush()
357 sys.stderr.flush()
358
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500359 # Finally release the lockfile but warn about other processes holding it open
360 lock = self.bitbake_lock
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500361 lockfile = self.bitbake_lock_name
362
363 def get_lock_contents(lockfile):
364 try:
365 with open(lockfile, "r") as f:
366 return f.readlines()
367 except FileNotFoundError:
368 return None
369
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500370 lock.close()
371 lock = None
372
373 while not lock:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500374 i = 0
375 lock = None
Andrew Geisslerc5535c92023-01-27 16:10:19 -0600376 if not os.path.exists(os.path.basename(lockfile)):
377 serverlog("Lockfile directory gone, exiting.")
378 return
379
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500380 while not lock and i < 30:
381 lock = bb.utils.lockfile(lockfile, shared=False, retry=False, block=False)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500382 if not lock:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500383 newlockcontents = get_lock_contents(lockfile)
Patrick Williamsb542dec2023-06-09 01:26:37 -0500384 if not newlockcontents[0].startswith([f"{os.getpid()}\n", f"{os.getpid()} "]):
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500385 # A new server was started, the lockfile contents changed, we can exit
386 serverlog("Lockfile now contains different contents, exiting: " + str(newlockcontents))
387 return
388 time.sleep(0.1)
389 i += 1
390 if lock:
391 # We hold the lock so we can remove the file (hide stale pid data)
392 # via unlockfile.
393 bb.utils.unlockfile(lock)
394 serverlog("Exiting as we could obtain the lock")
395 return
396
397 if not lock:
Andrew Geissler517393d2023-01-13 08:55:19 -0600398 procs = get_lockfile_process_msg(lockfile)
Andrew Geissler595f6302022-01-24 19:11:47 +0000399 msg = ["Delaying shutdown due to active processes which appear to be holding bitbake.lock"]
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500400 if procs:
Andrew Geissler517393d2023-01-13 08:55:19 -0600401 msg.append(":\n%s" % procs)
Andrew Geissler595f6302022-01-24 19:11:47 +0000402 serverlog("".join(msg))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500403
Andrew Geissler517393d2023-01-13 08:55:19 -0600404 def idle_thread(self):
405 def remove_idle_func(function):
406 with bb.utils.lock_timeout(self._idlefuncsLock):
407 del self._idlefuns[function]
408 self.idle_cond.notify_all()
409
410 while not self.quit:
411 nextsleep = 0.1
412 fds = []
413
Andrew Geissler517393d2023-01-13 08:55:19 -0600414 with bb.utils.lock_timeout(self._idlefuncsLock):
415 items = list(self._idlefuns.items())
416
417 for function, data in items:
418 try:
419 retval = function(self, data, False)
420 if isinstance(retval, idleFinish):
421 serverlog("Removing idle function %s at idleFinish" % str(function))
422 remove_idle_func(function)
423 self.cooker.command.finishAsyncCommand(retval.msg)
424 nextsleep = None
425 elif retval is False:
426 serverlog("Removing idle function %s" % str(function))
427 remove_idle_func(function)
428 nextsleep = None
429 elif retval is True:
430 nextsleep = None
431 elif isinstance(retval, float) and nextsleep:
432 if (retval < nextsleep):
433 nextsleep = retval
434 elif nextsleep is None:
435 continue
436 else:
437 fds = fds + retval
438 except SystemExit:
439 raise
440 except Exception as exc:
441 if not isinstance(exc, bb.BBHandledException):
442 logger.exception('Running idle function')
443 remove_idle_func(function)
444 serverlog("Exception %s broke the idle_thread, exiting" % traceback.format_exc())
445 self.quit = True
446
447 # Create new heartbeat event?
448 now = time.time()
449 if bb.event._heartbeat_enabled and now >= self.next_heartbeat:
450 # We might have missed heartbeats. Just trigger once in
451 # that case and continue after the usual delay.
452 self.next_heartbeat += self.heartbeat_seconds
453 if self.next_heartbeat <= now:
454 self.next_heartbeat = now + self.heartbeat_seconds
455 if hasattr(self.cooker, "data"):
456 heartbeat = bb.event.HeartbeatEvent(now)
457 try:
458 bb.event.fire(heartbeat, self.cooker.data)
459 except Exception as exc:
460 if not isinstance(exc, bb.BBHandledException):
461 logger.exception('Running heartbeat function')
462 serverlog("Exception %s broke in idle_thread, exiting" % traceback.format_exc())
463 self.quit = True
464 if nextsleep and bb.event._heartbeat_enabled and now + nextsleep > self.next_heartbeat:
465 # Shorten timeout so that we we wake up in time for
466 # the heartbeat.
467 nextsleep = self.next_heartbeat - now
468
469 if nextsleep is not None:
470 select.select(fds,[],[],nextsleep)[0]
471
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500472 def idle_commands(self, delay, fds=None):
473 nextsleep = delay
474 if not fds:
475 fds = []
476
Andrew Geissler517393d2023-01-13 08:55:19 -0600477 if not self.idle:
478 self.idle = threading.Thread(target=self.idle_thread)
479 self.idle.start()
Andrew Geissler6aa7eec2023-03-03 12:41:14 -0600480 elif self.idle and not self.idle.is_alive():
481 serverlog("Idle thread terminated, main thread exiting too")
482 bb.error("Idle thread terminated, main thread exiting too")
483 self.quit = True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500484
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500485 if nextsleep is not None:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500486 if self.xmlrpc:
487 nextsleep = self.xmlrpc.get_timeout(nextsleep)
488 try:
489 return select.select(fds,[],[],nextsleep)[0]
490 except InterruptedError:
491 # Ignore EINTR
492 return []
493 else:
494 return select.select(fds,[],[],0)[0]
495
496
497class ServerCommunicator():
498 def __init__(self, connection, recv):
499 self.connection = connection
500 self.recv = recv
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500501
502 def runCommand(self, command):
Patrick Williams705982a2024-01-12 09:51:57 -0600503 try:
504 self.connection.send(command)
505 except BrokenPipeError as e:
506 raise BrokenPipeError("bitbake-server might have died or been forcibly stopped, ie. OOM killed") from e
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500507 if not self.recv.poll(30):
Andrew Geissler5082cc72023-09-11 08:41:39 -0400508 logger.info("No reply from server in 30s (for command %s at %s)" % (command[0], currenttime()))
Andrew Geissler475cb722020-07-10 16:00:51 -0500509 if not self.recv.poll(30):
Andrew Geissler5082cc72023-09-11 08:41:39 -0400510 raise ProcessTimeout("Timeout while waiting for a reply from the bitbake server (60s at %s)" % currenttime())
Patrick Williams705982a2024-01-12 09:51:57 -0600511 try:
512 ret, exc = self.recv.get()
513 except EOFError as e:
514 raise EOFError("bitbake-server might have died or been forcibly stopped, ie. OOM killed") from e
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500515 # Should probably turn all exceptions in exc back into exceptions?
516 # For now, at least handle BBHandledException
517 if exc and ("BBHandledException" in exc or "SystemExit" in exc):
518 raise bb.BBHandledException()
519 return ret, exc
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500520
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500521 def updateFeatureSet(self, featureset):
522 _, error = self.runCommand(["setFeatures", featureset])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500523 if error:
524 logger.error("Unable to set the cooker to the correct featureset: %s" % error)
525 raise BaseException(error)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500526
527 def getEventHandle(self):
528 handle, error = self.runCommand(["getUIHandlerNum"])
529 if error:
530 logger.error("Unable to get UI Handler Number: %s" % error)
531 raise BaseException(error)
532
533 return handle
534
535 def terminateServer(self):
536 self.connection.send(['terminateServer'])
537 return
538
539class BitBakeProcessServerConnection(object):
540 def __init__(self, ui_channel, recv, eq, sock):
541 self.connection = ServerCommunicator(ui_channel, recv)
542 self.events = eq
543 # Save sock so it doesn't get gc'd for the life of our connection
544 self.socket_connection = sock
545
546 def terminate(self):
Andrew Geissler78b72792022-06-14 06:47:25 -0500547 self.events.close()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500548 self.socket_connection.close()
549 self.connection.connection.close()
550 self.connection.recv.close()
551 return
552
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500553start_log_format = '--- Starting bitbake server pid %s at %s ---'
554start_log_datetime_format = '%Y-%m-%d %H:%M:%S.%f'
555
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500556class BitBakeServer(object):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500557
Andrew Geissler517393d2023-01-13 08:55:19 -0600558 def __init__(self, lock, sockname, featureset, server_timeout, xmlrpcinterface, profile):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500559
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500560 self.server_timeout = server_timeout
561 self.xmlrpcinterface = xmlrpcinterface
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500562 self.featureset = featureset
563 self.sockname = sockname
564 self.bitbake_lock = lock
Andrew Geissler517393d2023-01-13 08:55:19 -0600565 self.profile = profile
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500566 self.readypipe, self.readypipein = os.pipe()
567
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800568 # Place the log in the builddirectory alongside the lock file
569 logfile = os.path.join(os.path.dirname(self.bitbake_lock.name), "bitbake-cookerdaemon.log")
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500570 self.logfile = logfile
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800571
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500572 startdatetime = datetime.datetime.now()
573 bb.daemonize.createDaemon(self._startServer, logfile)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500574 self.bitbake_lock.close()
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800575 os.close(self.readypipein)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500576
577 ready = ConnectionReader(self.readypipe)
Brad Bishopf058f492019-01-28 23:50:33 -0500578 r = ready.poll(5)
579 if not r:
580 bb.note("Bitbake server didn't start within 5 seconds, waiting for 90")
581 r = ready.poll(90)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500582 if r:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800583 try:
584 r = ready.get()
585 except EOFError:
Andrew Geisslerd159c7f2021-09-02 21:05:58 -0500586 # Trap the child exiting/closing the pipe and error out
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800587 r = None
Brad Bishopf058f492019-01-28 23:50:33 -0500588 if not r or r[0] != "r":
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500589 ready.close()
Brad Bishopf058f492019-01-28 23:50:33 -0500590 bb.error("Unable to start bitbake server (%s)" % str(r))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500591 if os.path.exists(logfile):
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500592 logstart_re = re.compile(start_log_format % ('([0-9]+)', '([0-9-]+ [0-9:.]+)'))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500593 started = False
594 lines = []
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300595 lastlines = []
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500596 with open(logfile, "r") as f:
597 for line in f:
598 if started:
599 lines.append(line)
600 else:
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300601 lastlines.append(line)
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500602 res = logstart_re.search(line.rstrip())
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500603 if res:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500604 ldatetime = datetime.datetime.strptime(res.group(2), start_log_datetime_format)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500605 if ldatetime >= startdatetime:
606 started = True
607 lines.append(line)
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300608 if len(lastlines) > 60:
609 lastlines = lastlines[-60:]
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500610 if lines:
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300611 if len(lines) > 60:
612 bb.error("Last 60 lines of server log for this session (%s):\n%s" % (logfile, "".join(lines[-60:])))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500613 else:
614 bb.error("Server log for this session (%s):\n%s" % (logfile, "".join(lines)))
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300615 elif lastlines:
616 bb.error("Server didn't start, last 60 loglines (%s):\n%s" % (logfile, "".join(lastlines)))
617 else:
618 bb.error("%s doesn't exist" % logfile)
619
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500620 raise SystemExit(1)
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300621
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500622 ready.close()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500623
624 def _startServer(self):
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500625 os.close(self.readypipe)
626 os.set_inheritable(self.bitbake_lock.fileno(), True)
627 os.set_inheritable(self.readypipein, True)
628 serverscript = os.path.realpath(os.path.dirname(__file__) + "/../../../bin/bitbake-server")
Andrew Geissler220dafd2023-10-04 10:18:08 -0500629 os.execl(sys.executable, sys.executable, serverscript, "decafbad", str(self.bitbake_lock.fileno()), str(self.readypipein), self.logfile, self.bitbake_lock.name, self.sockname, str(self.server_timeout or 0), str(int(self.profile)), str(self.xmlrpcinterface[0]), str(self.xmlrpcinterface[1]))
Brad Bishope2d5b612018-11-23 10:55:50 +1300630
Andrew Geissler517393d2023-01-13 08:55:19 -0600631def execServer(lockfd, readypipeinfd, lockname, sockname, server_timeout, xmlrpcinterface, profile):
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500632
633 import bb.cookerdata
634 import bb.cooker
635
636 serverlog(start_log_format % (os.getpid(), datetime.datetime.now().strftime(start_log_datetime_format)))
637
638 try:
639 bitbake_lock = os.fdopen(lockfd, "w")
640
641 # Create server control socket
642 if os.path.exists(sockname):
Andrew Geissler517393d2023-01-13 08:55:19 -0600643 serverlog("WARNING: removing existing socket file '%s'" % sockname)
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500644 os.unlink(sockname)
645
646 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
647 # AF_UNIX has path length issues so chdir here to workaround
648 cwd = os.getcwd()
Brad Bishop08902b02019-08-20 09:16:51 -0400649 try:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500650 os.chdir(os.path.dirname(sockname))
651 sock.bind(os.path.basename(sockname))
Andrew Geissler635e0e42020-08-21 15:58:33 -0500652 finally:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500653 os.chdir(cwd)
654 sock.listen(1)
655
656 server = ProcessServer(bitbake_lock, lockname, sock, sockname, server_timeout, xmlrpcinterface)
657 writer = ConnectionWriter(readypipeinfd)
658 try:
659 featureset = []
Andrew Geissler517393d2023-01-13 08:55:19 -0600660 cooker = bb.cooker.BBCooker(featureset, server)
661 cooker.configuration.profile = profile
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500662 except bb.BBHandledException:
663 return None
664 writer.send("r")
665 writer.close()
666 server.cooker = cooker
667 serverlog("Started bitbake server pid %d" % os.getpid())
668
669 server.run()
670 finally:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000671 # Flush any messages/errors to the logfile before exit
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500672 sys.stdout.flush()
673 sys.stderr.flush()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500674
675def connectProcessServer(sockname, featureset):
676 # Connect to socket
677 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
678 # AF_UNIX has path length issues so chdir here to workaround
679 cwd = os.getcwd()
680
Brad Bishopf058f492019-01-28 23:50:33 -0500681 readfd = writefd = readfd1 = writefd1 = readfd2 = writefd2 = None
682 eq = command_chan_recv = command_chan = None
683
684 sock.settimeout(10)
685
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500686 try:
Brad Bishope2d5b612018-11-23 10:55:50 +1300687 try:
688 os.chdir(os.path.dirname(sockname))
Brad Bishopf058f492019-01-28 23:50:33 -0500689 finished = False
690 while not finished:
691 try:
692 sock.connect(os.path.basename(sockname))
693 finished = True
694 except IOError as e:
695 if e.errno == errno.EWOULDBLOCK:
696 pass
Richard Purdie3da11142019-02-05 21:34:37 +0000697 raise
Brad Bishope2d5b612018-11-23 10:55:50 +1300698 finally:
699 os.chdir(cwd)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500700
701 # Send an fd for the remote to write events to
702 readfd, writefd = os.pipe()
703 eq = BBUIEventQueue(readfd)
704 # Send an fd for the remote to recieve commands from
705 readfd1, writefd1 = os.pipe()
706 command_chan = ConnectionWriter(writefd1)
707 # Send an fd for the remote to write commands results to
708 readfd2, writefd2 = os.pipe()
709 command_chan_recv = ConnectionReader(readfd2)
710
711 sendfds(sock, [writefd, readfd1, writefd2])
712
713 server_connection = BitBakeProcessServerConnection(command_chan, command_chan_recv, eq, sock)
714
715 # Close the ends of the pipes we won't use
716 for i in [writefd, readfd1, writefd2]:
717 os.close(i)
718
719 server_connection.connection.updateFeatureSet(featureset)
720
721 except (Exception, SystemExit) as e:
722 if command_chan_recv:
723 command_chan_recv.close()
724 if command_chan:
725 command_chan.close()
726 for i in [writefd, readfd1, writefd2]:
727 try:
Brad Bishope2d5b612018-11-23 10:55:50 +1300728 if i:
729 os.close(i)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500730 except OSError:
731 pass
732 sock.close()
733 raise
734
735 return server_connection
736
737def sendfds(sock, fds):
738 '''Send an array of fds over an AF_UNIX socket.'''
739 fds = array.array('i', fds)
740 msg = bytes([len(fds) % 256])
741 sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
742
743def recvfds(sock, size):
744 '''Receive an array of fds over an AF_UNIX socket.'''
745 a = array.array('i')
746 bytes_size = a.itemsize * size
747 msg, ancdata, flags, addr = sock.recvmsg(1, socket.CMSG_LEN(bytes_size))
748 if not msg and not ancdata:
749 raise EOFError
750 try:
751 if len(ancdata) != 1:
752 raise RuntimeError('received %d items of ancdata' %
753 len(ancdata))
754 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
755 if (cmsg_level == socket.SOL_SOCKET and
756 cmsg_type == socket.SCM_RIGHTS):
757 if len(cmsg_data) % a.itemsize != 0:
758 raise ValueError
759 a.frombytes(cmsg_data)
760 assert len(a) % 256 == msg[0]
761 return list(a)
762 except (ValueError, IndexError):
763 pass
764 raise RuntimeError('Invalid data received')
765
766class BBUIEventQueue:
767 def __init__(self, readfd):
768
769 self.eventQueue = []
770 self.eventQueueLock = threading.Lock()
771 self.eventQueueNotify = threading.Event()
772
773 self.reader = ConnectionReader(readfd)
774
775 self.t = threading.Thread()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500776 self.t.run = self.startCallbackHandler
777 self.t.start()
778
779 def getEvent(self):
Andrew Geissler517393d2023-01-13 08:55:19 -0600780 with bb.utils.lock_timeout(self.eventQueueLock):
Andrew Geissler78b72792022-06-14 06:47:25 -0500781 if len(self.eventQueue) == 0:
782 return None
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500783
Andrew Geissler78b72792022-06-14 06:47:25 -0500784 item = self.eventQueue.pop(0)
785 if len(self.eventQueue) == 0:
786 self.eventQueueNotify.clear()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500787
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500788 return item
789
790 def waitEvent(self, delay):
791 self.eventQueueNotify.wait(delay)
792 return self.getEvent()
793
794 def queue_event(self, event):
Andrew Geissler517393d2023-01-13 08:55:19 -0600795 with bb.utils.lock_timeout(self.eventQueueLock):
Andrew Geissler78b72792022-06-14 06:47:25 -0500796 self.eventQueue.append(event)
797 self.eventQueueNotify.set()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500798
799 def send_event(self, event):
800 self.queue_event(pickle.loads(event))
801
802 def startCallbackHandler(self):
803 bb.utils.set_process_name("UIEventQueue")
804 while True:
805 try:
Andrew Geissler78b72792022-06-14 06:47:25 -0500806 ready = self.reader.wait(0.25)
807 if ready:
808 event = self.reader.get()
809 self.queue_event(event)
810 except (EOFError, OSError, TypeError):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500811 # Easiest way to exit is to close the file descriptor to cause an exit
812 break
Andrew Geissler78b72792022-06-14 06:47:25 -0500813
814 def close(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500815 self.reader.close()
Andrew Geissler78b72792022-06-14 06:47:25 -0500816 self.t.join()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500817
818class ConnectionReader(object):
819
820 def __init__(self, fd):
821 self.reader = multiprocessing.connection.Connection(fd, writable=False)
822 self.rlock = multiprocessing.Lock()
823
824 def wait(self, timeout=None):
825 return multiprocessing.connection.wait([self.reader], timeout)
826
827 def poll(self, timeout=None):
828 return self.reader.poll(timeout)
829
830 def get(self):
Andrew Geissler517393d2023-01-13 08:55:19 -0600831 with bb.utils.lock_timeout(self.rlock):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500832 res = self.reader.recv_bytes()
833 return multiprocessing.reduction.ForkingPickler.loads(res)
834
835 def fileno(self):
836 return self.reader.fileno()
837
838 def close(self):
839 return self.reader.close()
840
841
842class ConnectionWriter(object):
843
844 def __init__(self, fd):
845 self.writer = multiprocessing.connection.Connection(fd, readable=False)
846 self.wlock = multiprocessing.Lock()
847 # Why bb.event needs this I have no idea
848 self.event = self
849
Andrew Geissler9aee5002022-03-30 16:27:02 +0000850 def _send(self, obj):
Patrick Williamsde0582f2022-04-08 10:23:27 -0500851 gc.disable()
Andrew Geissler517393d2023-01-13 08:55:19 -0600852 with bb.utils.lock_timeout(self.wlock):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500853 self.writer.send_bytes(obj)
Patrick Williamsde0582f2022-04-08 10:23:27 -0500854 gc.enable()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500855
Andrew Geissler9aee5002022-03-30 16:27:02 +0000856 def send(self, obj):
857 obj = multiprocessing.reduction.ForkingPickler.dumps(obj)
858 # See notes/code in CookerParser
859 # We must not terminate holding this lock else processes will hang.
860 # For SIGTERM, raising afterwards avoids this.
861 # For SIGINT, we don't want to have written partial data to the pipe.
862 # pthread_sigmask block/unblock would be nice but doesn't work, https://bugs.python.org/issue47139
863 process = multiprocessing.current_process()
864 if process and hasattr(process, "queue_signals"):
Andrew Geissler517393d2023-01-13 08:55:19 -0600865 with bb.utils.lock_timeout(process.signal_threadlock):
Andrew Geissler9aee5002022-03-30 16:27:02 +0000866 process.queue_signals = True
867 self._send(obj)
868 process.queue_signals = False
Patrick Williams2a254922023-08-11 09:48:11 -0500869
870 while len(process.signal_received) > 0:
871 sig = process.signal_received.pop()
872 process.handle_sig(sig, None)
Andrew Geissler9aee5002022-03-30 16:27:02 +0000873 else:
874 self._send(obj)
875
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500876 def fileno(self):
877 return self.writer.fileno()
878
879 def close(self):
880 return self.writer.close()