blob: bf96207edcb3b76fb6e61dc546786429c558a815 [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001#!/usr/bin/env python3
Brad Bishopc342db32019-05-15 21:57:59 -04002#
3# SPDX-License-Identifier: GPL-2.0-only
4#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05005
6import os
7import sys
8import warnings
Andrew Geissler5199d832021-09-24 16:47:35 -05009warnings.simplefilter("default")
Patrick Williamsc124f4f2015-09-15 14:41:29 -050010sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])), 'lib'))
11from bb import fetch2
12import logging
13import bb
14import select
15import errno
16import signal
Patrick Williamsc0f7c042017-02-23 20:41:17 -060017import pickle
Brad Bishop37a0e4d2017-12-04 01:01:44 -050018import traceback
19import queue
Patrick Williams93c203f2021-10-06 16:15:23 -050020import shlex
21import subprocess
Patrick Williamsf1e5d692016-03-30 15:21:19 -050022from multiprocessing import Lock
Brad Bishop37a0e4d2017-12-04 01:01:44 -050023from threading import Thread
Patrick Williamsc124f4f2015-09-15 14:41:29 -050024
Patrick Williamsc0f7c042017-02-23 20:41:17 -060025if sys.getfilesystemencoding() != "utf-8":
Brad Bishopd7bf8c12018-02-25 22:55:05 -050026 sys.exit("Please use a locale setting which supports UTF-8 (such as LANG=en_US.UTF-8).\nPython can't change the filesystem locale after loading so we need a UTF-8 when Python starts or things won't work.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -060027
Patrick Williamsc124f4f2015-09-15 14:41:29 -050028# Users shouldn't be running this code directly
29if len(sys.argv) != 2 or not sys.argv[1].startswith("decafbad"):
30 print("bitbake-worker is meant for internal execution by bitbake itself, please don't use it standalone.")
31 sys.exit(1)
32
33profiling = False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050034if sys.argv[1].startswith("decafbadbad"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050035 profiling = True
36 try:
37 import cProfile as profile
38 except:
39 import profile
40
41# Unbuffer stdout to avoid log truncation in the event
42# of an unorderly exit as well as to provide timely
43# updates to log files for use with tail
44try:
45 if sys.stdout.name == '<stdout>':
Patrick Williamsc0f7c042017-02-23 20:41:17 -060046 import fcntl
47 fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
48 fl |= os.O_SYNC
49 fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)
50 #sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050051except:
52 pass
53
54logger = logging.getLogger("BitBake")
55
Patrick Williamsc124f4f2015-09-15 14:41:29 -050056worker_pipe = sys.stdout.fileno()
57bb.utils.nonblockingfd(worker_pipe)
Patrick Williamsf1e5d692016-03-30 15:21:19 -050058# Need to guard against multiprocessing being used in child processes
59# and multiple processes trying to write to the parent at the same time
60worker_pipe_lock = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -050061
62handler = bb.event.LogHandler()
63logger.addHandler(handler)
64
65if 0:
66 # Code to write out a log file of all events passing through the worker
67 logfilename = "/tmp/workerlogfile"
68 format_str = "%(levelname)s: %(message)s"
69 conlogformat = bb.msg.BBLogFormatter(format_str)
70 consolelog = logging.FileHandler(logfilename)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050071 consolelog.setFormatter(conlogformat)
72 logger.addHandler(consolelog)
73
Brad Bishop37a0e4d2017-12-04 01:01:44 -050074worker_queue = queue.Queue()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050075
76def worker_fire(event, d):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060077 data = b"<event>" + pickle.dumps(event) + b"</event>"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050078 worker_fire_prepickled(data)
79
80def worker_fire_prepickled(event):
81 global worker_queue
82
Brad Bishop37a0e4d2017-12-04 01:01:44 -050083 worker_queue.put(event)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050084
Brad Bishop37a0e4d2017-12-04 01:01:44 -050085#
86# We can end up with write contention with the cooker, it can be trying to send commands
87# and we can be trying to send event data back. Therefore use a separate thread for writing
88# back data to cooker.
89#
90worker_thread_exit = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050091
Brad Bishop37a0e4d2017-12-04 01:01:44 -050092def worker_flush(worker_queue):
93 worker_queue_int = b""
94 global worker_pipe, worker_thread_exit
Patrick Williamsc124f4f2015-09-15 14:41:29 -050095
Brad Bishop37a0e4d2017-12-04 01:01:44 -050096 while True:
97 try:
98 worker_queue_int = worker_queue_int + worker_queue.get(True, 1)
99 except queue.Empty:
100 pass
101 while (worker_queue_int or not worker_queue.empty()):
102 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500103 (_, ready, _) = select.select([], [worker_pipe], [], 1)
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500104 if not worker_queue.empty():
105 worker_queue_int = worker_queue_int + worker_queue.get()
106 written = os.write(worker_pipe, worker_queue_int)
107 worker_queue_int = worker_queue_int[written:]
108 except (IOError, OSError) as e:
109 if e.errno != errno.EAGAIN and e.errno != errno.EPIPE:
110 raise
111 if worker_thread_exit and worker_queue.empty() and not worker_queue_int:
112 return
113
114worker_thread = Thread(target=worker_flush, args=(worker_queue,))
115worker_thread.start()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500116
117def worker_child_fire(event, d):
118 global worker_pipe
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500119 global worker_pipe_lock
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500120
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600121 data = b"<event>" + pickle.dumps(event) + b"</event>"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500122 try:
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500123 worker_pipe_lock.acquire()
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600124 while(len(data)):
125 written = worker_pipe.write(data)
126 data = data[written:]
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500127 worker_pipe_lock.release()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500128 except IOError:
129 sigterm_handler(None, None)
130 raise
131
132bb.event.worker_fire = worker_fire
133
134lf = None
135#lf = open("/tmp/workercommandlog", "w+")
136def workerlog_write(msg):
137 if lf:
138 lf.write(msg)
139 lf.flush()
140
141def sigterm_handler(signum, frame):
142 signal.signal(signal.SIGTERM, signal.SIG_DFL)
143 os.killpg(0, signal.SIGTERM)
144 sys.exit()
145
Brad Bishop19323692019-04-05 15:28:33 -0400146def fork_off_task(cfg, data, databuilder, workerdata, fn, task, taskname, taskhash, unihash, appends, taskdepdata, extraconfigdata, quieterrors=False, dry_run_exec=False):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500147 # We need to setup the environment BEFORE the fork, since
148 # a fork() or exec*() activates PSEUDO...
149
150 envbackup = {}
Patrick Williams93c203f2021-10-06 16:15:23 -0500151 fakeroot = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500152 fakeenv = {}
153 umask = None
154
155 taskdep = workerdata["taskdeps"][fn]
156 if 'umask' in taskdep and taskname in taskdep['umask']:
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600157 umask = taskdep['umask'][taskname]
158 elif workerdata["umask"]:
159 umask = workerdata["umask"]
160 if umask:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500161 # umask might come in as a number or text string..
162 try:
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600163 umask = int(umask, 8)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500164 except TypeError:
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600165 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500166
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500167 dry_run = cfg.dry_run or dry_run_exec
168
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500169 # We can't use the fakeroot environment in a dry run as it possibly hasn't been built
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500170 if 'fakeroot' in taskdep and taskname in taskdep['fakeroot'] and not dry_run:
Patrick Williams93c203f2021-10-06 16:15:23 -0500171 fakeroot = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500172 envvars = (workerdata["fakerootenv"][fn] or "").split()
173 for key, value in (var.split('=') for var in envvars):
174 envbackup[key] = os.environ.get(key)
175 os.environ[key] = value
176 fakeenv[key] = value
177
178 fakedirs = (workerdata["fakerootdirs"][fn] or "").split()
179 for p in fakedirs:
180 bb.utils.mkdirhier(p)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600181 logger.debug2('Running %s:%s under fakeroot, fakedirs: %s' %
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500182 (fn, taskname, ', '.join(fakedirs)))
183 else:
184 envvars = (workerdata["fakerootnoenv"][fn] or "").split()
185 for key, value in (var.split('=') for var in envvars):
186 envbackup[key] = os.environ.get(key)
187 os.environ[key] = value
188 fakeenv[key] = value
189
190 sys.stdout.flush()
191 sys.stderr.flush()
192
193 try:
194 pipein, pipeout = os.pipe()
195 pipein = os.fdopen(pipein, 'rb', 4096)
196 pipeout = os.fdopen(pipeout, 'wb', 0)
197 pid = os.fork()
198 except OSError as e:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600199 logger.critical("fork failed: %d (%s)" % (e.errno, e.strerror))
200 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500201
202 if pid == 0:
203 def child():
204 global worker_pipe
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500205 global worker_pipe_lock
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500206 pipein.close()
207
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500208 bb.utils.signal_on_parent_exit("SIGTERM")
209
210 # Save out the PID so that the event can include it the
211 # events
212 bb.event.worker_pid = os.getpid()
213 bb.event.worker_fire = worker_child_fire
214 worker_pipe = pipeout
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500215 worker_pipe_lock = Lock()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500216
217 # Make the child the process group leader and ensure no
218 # child process will be controlled by the current terminal
219 # This ensures signals sent to the controlling terminal like Ctrl+C
220 # don't stop the child processes.
221 os.setsid()
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500222
223 signal.signal(signal.SIGTERM, sigterm_handler)
224 # Let SIGHUP exit as SIGTERM
225 signal.signal(signal.SIGHUP, sigterm_handler)
226
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500227 # No stdin
228 newsi = os.open(os.devnull, os.O_RDWR)
229 os.dup2(newsi, sys.stdin.fileno())
230
231 if umask:
232 os.umask(umask)
233
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500234 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600235 bb_cache = bb.cache.NoCache(databuilder)
236 (realfn, virtual, mc) = bb.cache.virtualfn2realfn(fn)
237 the_data = databuilder.mcdata[mc]
238 the_data.setVar("BB_WORKERCONTEXT", "1")
239 the_data.setVar("BB_TASKDEPDATA", taskdepdata)
Andrew Geisslereff27472021-10-29 15:35:00 -0500240 the_data.setVar('BB_CURRENTTASK', taskname.replace("do_", ""))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500241 if cfg.limited_deps:
242 the_data.setVar("BB_LIMITEDDEPS", "1")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600243 the_data.setVar("BUILDNAME", workerdata["buildname"])
244 the_data.setVar("DATE", workerdata["date"])
245 the_data.setVar("TIME", workerdata["time"])
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500246 for varname, value in extraconfigdata.items():
247 the_data.setVar(varname, value)
248
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600249 bb.parse.siggen.set_taskdata(workerdata["sigdata"])
Brad Bishop08902b02019-08-20 09:16:51 -0400250 if "newhashes" in workerdata:
251 bb.parse.siggen.set_taskhashes(workerdata["newhashes"])
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600252 ret = 0
253
254 the_data = bb_cache.loadDataFull(fn, appends)
Brad Bishop19323692019-04-05 15:28:33 -0400255 the_data.setVar('BB_TASKHASH', taskhash)
256 the_data.setVar('BB_UNIHASH', unihash)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500257
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500258 bb.utils.set_process_name("%s:%s" % (the_data.getVar("PN"), taskname.replace("do_", "")))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500259
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500260 # exported_vars() returns a generator which *cannot* be passed to os.environ.update()
261 # successfully. We also need to unset anything from the environment which shouldn't be there
262 exports = bb.data.exported_vars(the_data)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600263
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500264 bb.utils.empty_environment()
265 for e, v in exports:
266 os.environ[e] = v
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500268 for e in fakeenv:
269 os.environ[e] = fakeenv[e]
270 the_data.setVar(e, fakeenv[e])
271 the_data.setVarFlag(e, 'export', "1")
272
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500273 task_exports = the_data.getVarFlag(taskname, 'exports')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600274 if task_exports:
275 for e in task_exports.split():
276 the_data.setVarFlag(e, 'export', '1')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500277 v = the_data.getVar(e)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600278 if v is not None:
279 os.environ[e] = v
280
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500281 if quieterrors:
282 the_data.setVarFlag(taskname, "quieterrors", "1")
283
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500284 except Exception:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500285 if not quieterrors:
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500286 logger.critical(traceback.format_exc())
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500287 os._exit(1)
288 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500289 if dry_run:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500290 return 0
Andrew Geisslereff27472021-10-29 15:35:00 -0500291 try:
292 ret = bb.build.exec_task(fn, taskname, the_data, cfg.profile)
293 finally:
294 if fakeroot:
295 fakerootcmd = shlex.split(the_data.getVar("FAKEROOTCMD"))
296 subprocess.run(fakerootcmd + ['-S'], check=True, stdout=subprocess.PIPE)
Patrick Williams93c203f2021-10-06 16:15:23 -0500297 return ret
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500298 except:
299 os._exit(1)
300 if not profiling:
301 os._exit(child())
302 else:
303 profname = "profile-%s.log" % (fn.replace("/", "-") + "-" + taskname)
304 prof = profile.Profile()
305 try:
306 ret = profile.Profile.runcall(prof, child)
307 finally:
308 prof.dump_stats(profname)
309 bb.utils.process_profilelog(profname)
310 os._exit(ret)
311 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600312 for key, value in iter(envbackup.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500313 if value is None:
314 del os.environ[key]
315 else:
316 os.environ[key] = value
317
318 return pid, pipein, pipeout
319
320class runQueueWorkerPipe():
321 """
322 Abstraction for a pipe between a worker thread and the worker server
323 """
324 def __init__(self, pipein, pipeout):
325 self.input = pipein
326 if pipeout:
327 pipeout.close()
328 bb.utils.nonblockingfd(self.input)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600329 self.queue = b""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500330
331 def read(self):
332 start = len(self.queue)
333 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600334 self.queue = self.queue + (self.input.read(102400) or b"")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500335 except (OSError, IOError) as e:
336 if e.errno != errno.EAGAIN:
337 raise
338
339 end = len(self.queue)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600340 index = self.queue.find(b"</event>")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500341 while index != -1:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600342 msg = self.queue[:index+8]
343 assert msg.startswith(b"<event>") and msg.count(b"<event>") == 1
344 worker_fire_prepickled(msg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500345 self.queue = self.queue[index+8:]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600346 index = self.queue.find(b"</event>")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500347 return (end > start)
348
349 def close(self):
350 while self.read():
351 continue
352 if len(self.queue) > 0:
353 print("Warning, worker child left partial message: %s" % self.queue)
354 self.input.close()
355
356normalexit = False
357
358class BitbakeWorker(object):
359 def __init__(self, din):
360 self.input = din
361 bb.utils.nonblockingfd(self.input)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600362 self.queue = b""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500363 self.cookercfg = None
364 self.databuilder = None
365 self.data = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500366 self.extraconfigdata = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500367 self.build_pids = {}
368 self.build_pipes = {}
369
370 signal.signal(signal.SIGTERM, self.sigterm_exception)
371 # Let SIGHUP exit as SIGTERM
372 signal.signal(signal.SIGHUP, self.sigterm_exception)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500373 if "beef" in sys.argv[1]:
374 bb.utils.set_process_name("Worker (Fakeroot)")
375 else:
376 bb.utils.set_process_name("Worker")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500377
378 def sigterm_exception(self, signum, stackframe):
379 if signum == signal.SIGTERM:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500380 bb.warn("Worker received SIGTERM, shutting down...")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500381 elif signum == signal.SIGHUP:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500382 bb.warn("Worker received SIGHUP, shutting down...")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500383 self.handle_finishnow(None)
384 signal.signal(signal.SIGTERM, signal.SIG_DFL)
385 os.kill(os.getpid(), signal.SIGTERM)
386
387 def serve(self):
388 while True:
389 (ready, _, _) = select.select([self.input] + [i.input for i in self.build_pipes.values()], [] , [], 1)
390 if self.input in ready:
391 try:
392 r = self.input.read()
393 if len(r) == 0:
394 # EOF on pipe, server must have terminated
395 self.sigterm_exception(signal.SIGTERM, None)
396 self.queue = self.queue + r
397 except (OSError, IOError):
398 pass
399 if len(self.queue):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600400 self.handle_item(b"cookerconfig", self.handle_cookercfg)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500401 self.handle_item(b"extraconfigdata", self.handle_extraconfigdata)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600402 self.handle_item(b"workerdata", self.handle_workerdata)
Brad Bishop08902b02019-08-20 09:16:51 -0400403 self.handle_item(b"newtaskhashes", self.handle_newtaskhashes)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600404 self.handle_item(b"runtask", self.handle_runtask)
405 self.handle_item(b"finishnow", self.handle_finishnow)
406 self.handle_item(b"ping", self.handle_ping)
407 self.handle_item(b"quit", self.handle_quit)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500408
409 for pipe in self.build_pipes:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500410 if self.build_pipes[pipe].input in ready:
411 self.build_pipes[pipe].read()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500412 if len(self.build_pids):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500413 while self.process_waitpid():
414 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500415
416
417 def handle_item(self, item, func):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600418 if self.queue.startswith(b"<" + item + b">"):
419 index = self.queue.find(b"</" + item + b">")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500420 while index != -1:
Andrew Geisslereff27472021-10-29 15:35:00 -0500421 try:
422 func(self.queue[(len(item) + 2):index])
423 except pickle.UnpicklingError:
424 workerlog_write("Unable to unpickle data: %s\n" % ":".join("{:02x}".format(c) for c in self.queue))
425 raise
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500426 self.queue = self.queue[(index + len(item) + 3):]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600427 index = self.queue.find(b"</" + item + b">")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500428
429 def handle_cookercfg(self, data):
430 self.cookercfg = pickle.loads(data)
431 self.databuilder = bb.cookerdata.CookerDataBuilder(self.cookercfg, worker=True)
432 self.databuilder.parseBaseConfiguration()
433 self.data = self.databuilder.data
434
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500435 def handle_extraconfigdata(self, data):
436 self.extraconfigdata = pickle.loads(data)
437
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500438 def handle_workerdata(self, data):
439 self.workerdata = pickle.loads(data)
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500440 bb.build.verboseShellLogging = self.workerdata["build_verbose_shell"]
441 bb.build.verboseStdoutLogging = self.workerdata["build_verbose_stdout"]
Andrew Geissler82c905d2020-04-13 13:39:40 -0500442 bb.msg.loggerDefaultLogLevel = self.workerdata["logdefaultlevel"]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500443 bb.msg.loggerDefaultDomains = self.workerdata["logdefaultdomain"]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600444 for mc in self.databuilder.mcdata:
445 self.databuilder.mcdata[mc].setVar("PRSERV_HOST", self.workerdata["prhost"])
Brad Bishopa34c0302019-09-23 22:34:48 -0400446 self.databuilder.mcdata[mc].setVar("BB_HASHSERVE", self.workerdata["hashservaddr"])
Brad Bishop08902b02019-08-20 09:16:51 -0400447
448 def handle_newtaskhashes(self, data):
449 self.workerdata["newhashes"] = pickle.loads(data)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500450
451 def handle_ping(self, _):
452 workerlog_write("Handling ping\n")
453
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600454 logger.warning("Pong from bitbake-worker!")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500455
456 def handle_quit(self, data):
457 workerlog_write("Handling quit\n")
458
459 global normalexit
460 normalexit = True
461 sys.exit(0)
462
463 def handle_runtask(self, data):
Brad Bishop19323692019-04-05 15:28:33 -0400464 fn, task, taskname, taskhash, unihash, quieterrors, appends, taskdepdata, dry_run_exec = pickle.loads(data)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500465 workerlog_write("Handling runtask %s %s %s\n" % (task, fn, taskname))
466
Brad Bishop19323692019-04-05 15:28:33 -0400467 pid, pipein, pipeout = fork_off_task(self.cookercfg, self.data, self.databuilder, self.workerdata, fn, task, taskname, taskhash, unihash, appends, taskdepdata, self.extraconfigdata, quieterrors, dry_run_exec)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500468
469 self.build_pids[pid] = task
470 self.build_pipes[pid] = runQueueWorkerPipe(pipein, pipeout)
471
472 def process_waitpid(self):
473 """
474 Return none is there are no processes awaiting result collection, otherwise
475 collect the process exit codes and close the information pipe.
476 """
477 try:
478 pid, status = os.waitpid(-1, os.WNOHANG)
479 if pid == 0 or os.WIFSTOPPED(status):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500480 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500481 except OSError:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500482 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500483
484 workerlog_write("Exit code of %s for pid %s\n" % (status, pid))
485
486 if os.WIFEXITED(status):
487 status = os.WEXITSTATUS(status)
488 elif os.WIFSIGNALED(status):
489 # Per shell conventions for $?, when a process exits due to
490 # a signal, we return an exit code of 128 + SIGNUM
491 status = 128 + os.WTERMSIG(status)
492
493 task = self.build_pids[pid]
494 del self.build_pids[pid]
495
496 self.build_pipes[pid].close()
497 del self.build_pipes[pid]
498
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600499 worker_fire_prepickled(b"<exitcode>" + pickle.dumps((task, status)) + b"</exitcode>")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500500
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500501 return True
502
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500503 def handle_finishnow(self, _):
504 if self.build_pids:
505 logger.info("Sending SIGTERM to remaining %s tasks", len(self.build_pids))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600506 for k, v in iter(self.build_pids.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500507 try:
508 os.kill(-k, signal.SIGTERM)
509 os.waitpid(-1, 0)
510 except:
511 pass
512 for pipe in self.build_pipes:
513 self.build_pipes[pipe].read()
514
515try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600516 worker = BitbakeWorker(os.fdopen(sys.stdin.fileno(), 'rb'))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500517 if not profiling:
518 worker.serve()
519 else:
520 profname = "profile-worker.log"
521 prof = profile.Profile()
522 try:
523 profile.Profile.runcall(prof, worker.serve)
524 finally:
525 prof.dump_stats(profname)
526 bb.utils.process_profilelog(profname)
527except BaseException as e:
528 if not normalexit:
529 import traceback
530 sys.stderr.write(traceback.format_exc())
531 sys.stderr.write(str(e))
Andrew Geissler5199d832021-09-24 16:47:35 -0500532finally:
533 worker_thread_exit = True
534 worker_thread.join()
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500535
Andrew Geisslerd159c7f2021-09-02 21:05:58 -0500536workerlog_write("exiting")
Andrew Geissler5199d832021-09-24 16:47:35 -0500537if not normalexit:
538 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500539sys.exit(0)