Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 1 | # |
| 2 | # ex:ts=4:sw=4:sts=4:et |
| 3 | # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- |
| 4 | # |
| 5 | # BitBake Toaster Implementation |
| 6 | # |
| 7 | # Copyright (C) 2014 Intel Corporation |
| 8 | # |
| 9 | # This program is free software; you can redistribute it and/or modify |
| 10 | # it under the terms of the GNU General Public License version 2 as |
| 11 | # published by the Free Software Foundation. |
| 12 | # |
| 13 | # This program is distributed in the hope that it will be useful, |
| 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | # GNU General Public License for more details. |
| 17 | # |
| 18 | # You should have received a copy of the GNU General Public License along |
| 19 | # with this program; if not, write to the Free Software Foundation, Inc., |
| 20 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 21 | |
| 22 | |
| 23 | import os |
| 24 | import sys |
| 25 | import re |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 26 | import shutil |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 27 | from django.db import transaction |
| 28 | from django.db.models import Q |
| 29 | from bldcontrol.models import BuildEnvironment, BRLayer, BRVariable, BRTarget, BRBitbake |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 30 | from orm.models import CustomImageRecipe, Layer, Layer_Version, ProjectLayer |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 31 | import subprocess |
| 32 | |
| 33 | from toastermain import settings |
| 34 | |
| 35 | from bbcontroller import BuildEnvironmentController, ShellCmdException, BuildSetupException |
| 36 | |
| 37 | import logging |
| 38 | logger = logging.getLogger("toaster") |
| 39 | |
| 40 | from pprint import pprint, pformat |
| 41 | |
| 42 | class LocalhostBEController(BuildEnvironmentController): |
| 43 | """ Implementation of the BuildEnvironmentController for the localhost; |
| 44 | this controller manages the default build directory, |
| 45 | the server setup and system start and stop for the localhost-type build environment |
| 46 | |
| 47 | """ |
| 48 | |
| 49 | def __init__(self, be): |
| 50 | super(LocalhostBEController, self).__init__(be) |
| 51 | self.dburl = settings.getDATABASE_URL() |
| 52 | self.pokydirname = None |
| 53 | self.islayerset = False |
| 54 | |
| 55 | def _shellcmd(self, command, cwd = None): |
| 56 | if cwd is None: |
| 57 | cwd = self.be.sourcedir |
| 58 | |
| 59 | logger.debug("lbc_shellcmmd: (%s) %s" % (cwd, command)) |
| 60 | p = subprocess.Popen(command, cwd = cwd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 61 | (out,err) = p.communicate() |
| 62 | p.wait() |
| 63 | if p.returncode: |
| 64 | if len(err) == 0: |
| 65 | err = "command: %s \n%s" % (command, out) |
| 66 | else: |
| 67 | err = "command: %s \n%s" % (command, err) |
| 68 | logger.warn("localhostbecontroller: shellcmd error %s" % err) |
| 69 | raise ShellCmdException(err) |
| 70 | else: |
| 71 | logger.debug("localhostbecontroller: shellcmd success") |
| 72 | return out |
| 73 | |
| 74 | def _setupBE(self): |
| 75 | assert self.pokydirname and os.path.exists(self.pokydirname) |
| 76 | path = self.be.builddir |
| 77 | if not path: |
| 78 | raise Exception("Invalid path creation specified.") |
| 79 | if not os.path.exists(path): |
| 80 | os.makedirs(path, 0755) |
| 81 | self._shellcmd("bash -c \"source %s/oe-init-build-env %s\"" % (self.pokydirname, path)) |
| 82 | # delete the templateconf.cfg; it may come from an unsupported layer configuration |
| 83 | os.remove(os.path.join(path, "conf/templateconf.cfg")) |
| 84 | |
| 85 | |
| 86 | def writeConfFile(self, file_name, variable_list = None, raw = None): |
| 87 | filepath = os.path.join(self.be.builddir, file_name) |
| 88 | with open(filepath, "w") as conffile: |
| 89 | if variable_list is not None: |
| 90 | for i in variable_list: |
| 91 | conffile.write("%s=\"%s\"\n" % (i.name, i.value)) |
| 92 | if raw is not None: |
| 93 | conffile.write(raw) |
| 94 | |
| 95 | |
| 96 | def startBBServer(self): |
| 97 | assert self.pokydirname and os.path.exists(self.pokydirname) |
| 98 | assert self.islayerset |
| 99 | |
| 100 | # find our own toasterui listener/bitbake |
| 101 | from toaster.bldcontrol.management.commands.loadconf import _reduce_canon_path |
| 102 | |
| 103 | own_bitbake = _reduce_canon_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../bin/bitbake")) |
| 104 | |
| 105 | assert os.path.exists(own_bitbake) and os.path.isfile(own_bitbake) |
| 106 | |
| 107 | logger.debug("localhostbecontroller: running the listener at %s" % own_bitbake) |
| 108 | |
| 109 | toaster_ui_log_filepath = os.path.join(self.be.builddir, "toaster_ui.log") |
| 110 | # get the file length; we need to detect the _last_ start of the toaster UI, not the first |
| 111 | toaster_ui_log_filelength = 0 |
| 112 | if os.path.exists(toaster_ui_log_filepath): |
| 113 | with open(toaster_ui_log_filepath, "w") as f: |
| 114 | f.seek(0, 2) # jump to the end |
| 115 | toaster_ui_log_filelength = f.tell() |
| 116 | |
| 117 | cmd = "bash -c \"source %s/oe-init-build-env %s 2>&1 >toaster_server.log && bitbake --read %s/conf/toaster-pre.conf --postread %s/conf/toaster.conf --server-only -t xmlrpc -B 0.0.0.0:0 2>&1 >>toaster_server.log \"" % (self.pokydirname, self.be.builddir, self.be.builddir, self.be.builddir) |
| 118 | |
| 119 | port = "-1" |
| 120 | logger.debug("localhostbecontroller: starting builder \n%s\n" % cmd) |
| 121 | |
| 122 | cmdoutput = self._shellcmd(cmd) |
| 123 | with open(self.be.builddir + "/toaster_server.log", "r") as f: |
| 124 | for i in f.readlines(): |
| 125 | if i.startswith("Bitbake server address"): |
| 126 | port = i.split(" ")[-1] |
| 127 | logger.debug("localhostbecontroller: Found bitbake server port %s" % port) |
| 128 | |
| 129 | cmd = "bash -c \"source %s/oe-init-build-env-memres -1 %s && DATABASE_URL=%s %s --observe-only -u toasterui --remote-server=0.0.0.0:-1 -t xmlrpc\"" % (self.pokydirname, self.be.builddir, self.dburl, own_bitbake) |
| 130 | with open(toaster_ui_log_filepath, "a+") as f: |
| 131 | p = subprocess.Popen(cmd, cwd = self.be.builddir, shell=True, stdout=f, stderr=f) |
| 132 | |
| 133 | def _toaster_ui_started(filepath, filepos = 0): |
| 134 | if not os.path.exists(filepath): |
| 135 | return False |
| 136 | with open(filepath, "r") as f: |
| 137 | f.seek(filepos) |
| 138 | for line in f: |
| 139 | if line.startswith("NOTE: ToasterUI waiting for events"): |
| 140 | return True |
| 141 | return False |
| 142 | |
| 143 | retries = 0 |
| 144 | started = False |
| 145 | while not started and retries < 50: |
| 146 | started = _toaster_ui_started(toaster_ui_log_filepath, toaster_ui_log_filelength) |
| 147 | import time |
| 148 | logger.debug("localhostbecontroller: Waiting bitbake server to start") |
| 149 | time.sleep(0.5) |
| 150 | retries += 1 |
| 151 | |
| 152 | if not started: |
| 153 | toaster_ui_log = open(os.path.join(self.be.builddir, "toaster_ui.log"), "r").read() |
| 154 | toaster_server_log = open(os.path.join(self.be.builddir, "toaster_server.log"), "r").read() |
| 155 | raise BuildSetupException("localhostbecontroller: Bitbake server did not start in 25 seconds, aborting (Error: '%s' '%s')" % (toaster_ui_log, toaster_server_log)) |
| 156 | |
| 157 | logger.debug("localhostbecontroller: Started bitbake server") |
| 158 | |
| 159 | while port == "-1": |
| 160 | # the port specification is "autodetect"; read the bitbake.lock file |
| 161 | with open("%s/bitbake.lock" % self.be.builddir, "r") as f: |
| 162 | for line in f.readlines(): |
| 163 | if ":" in line: |
| 164 | port = line.split(":")[1].strip() |
| 165 | logger.debug("localhostbecontroller: Autodetected bitbake port %s", port) |
| 166 | break |
| 167 | |
| 168 | assert self.be.sourcedir and os.path.exists(self.be.builddir) |
| 169 | self.be.bbaddress = "localhost" |
| 170 | self.be.bbport = port |
| 171 | self.be.bbstate = BuildEnvironment.SERVER_STARTED |
| 172 | self.be.save() |
| 173 | |
| 174 | def stopBBServer(self): |
| 175 | assert self.pokydirname and os.path.exists(self.pokydirname) |
| 176 | assert self.islayerset |
| 177 | self._shellcmd("bash -c \"source %s/oe-init-build-env %s && %s source toaster stop\"" % |
| 178 | (self.pokydirname, self.be.builddir, (lambda: "" if self.be.bbtoken is None else "BBTOKEN=%s" % self.be.bbtoken)())) |
| 179 | self.be.bbstate = BuildEnvironment.SERVER_STOPPED |
| 180 | self.be.save() |
| 181 | logger.debug("localhostbecontroller: Stopped bitbake server") |
| 182 | |
| 183 | def getGitCloneDirectory(self, url, branch): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 184 | """Construct unique clone directory name out of url and branch.""" |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 185 | if branch != "HEAD": |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 186 | return "_toaster_clones/_%s_%s" % (re.sub('[:/@%]', '_', url), branch) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 187 | |
| 188 | # word of attention; this is a localhost-specific issue; only on the localhost we expect to have "HEAD" releases |
| 189 | # which _ALWAYS_ means the current poky checkout |
| 190 | from os.path import dirname as DN |
| 191 | local_checkout_path = DN(DN(DN(DN(DN(os.path.abspath(__file__)))))) |
| 192 | #logger.debug("localhostbecontroller: using HEAD checkout in %s" % local_checkout_path) |
| 193 | return local_checkout_path |
| 194 | |
| 195 | |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 196 | def setLayers(self, bitbakes, layers, targets): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 197 | """ a word of attention: by convention, the first layer for any build will be poky! """ |
| 198 | |
| 199 | assert self.be.sourcedir is not None |
| 200 | assert len(bitbakes) == 1 |
| 201 | # set layers in the layersource |
| 202 | |
| 203 | # 1. get a list of repos with branches, and map dirpaths for each layer |
| 204 | gitrepos = {} |
| 205 | |
| 206 | gitrepos[(bitbakes[0].giturl, bitbakes[0].commit)] = [] |
| 207 | gitrepos[(bitbakes[0].giturl, bitbakes[0].commit)].append( ("bitbake", bitbakes[0].dirpath) ) |
| 208 | |
| 209 | for layer in layers: |
| 210 | # we don't process local URLs |
| 211 | if layer.giturl.startswith("file://"): |
| 212 | continue |
| 213 | if not (layer.giturl, layer.commit) in gitrepos: |
| 214 | gitrepos[(layer.giturl, layer.commit)] = [] |
| 215 | gitrepos[(layer.giturl, layer.commit)].append( (layer.name, layer.dirpath) ) |
| 216 | |
| 217 | |
| 218 | logger.debug("localhostbecontroller, our git repos are %s" % pformat(gitrepos)) |
| 219 | |
| 220 | |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 221 | # 2. Note for future use if the current source directory is a |
| 222 | # checked-out git repos that could match a layer's vcs_url and therefore |
| 223 | # be used to speed up cloning (rather than fetching it again). |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 224 | |
| 225 | cached_layers = {} |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 226 | |
| 227 | try: |
| 228 | for remotes in self._shellcmd("git remote -v", self.be.sourcedir).split("\n"): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 229 | try: |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 230 | remote = remotes.split("\t")[1].split(" ")[0] |
| 231 | if remote not in cached_layers: |
| 232 | cached_layers[remote] = self.be.sourcedir |
| 233 | except IndexError: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 234 | pass |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 235 | except ShellCmdException: |
| 236 | # ignore any errors in collecting git remotes this is an optional |
| 237 | # step |
| 238 | pass |
| 239 | |
| 240 | logger.info("Using pre-checked out source for layer %s", cached_layers) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 241 | |
| 242 | layerlist = [] |
| 243 | |
| 244 | |
| 245 | # 3. checkout the repositories |
| 246 | for giturl, commit in gitrepos.keys(): |
| 247 | localdirname = os.path.join(self.be.sourcedir, self.getGitCloneDirectory(giturl, commit)) |
| 248 | logger.debug("localhostbecontroller: giturl %s:%s checking out in current directory %s" % (giturl, commit, localdirname)) |
| 249 | |
| 250 | # make sure our directory is a git repository |
| 251 | if os.path.exists(localdirname): |
| 252 | localremotes = self._shellcmd("git remote -v", localdirname) |
| 253 | if not giturl in localremotes: |
| 254 | raise BuildSetupException("Existing git repository at %s, but with different remotes ('%s', expected '%s'). Toaster will not continue out of fear of damaging something." % (localdirname, ", ".join(localremotes.split("\n")), giturl)) |
| 255 | else: |
| 256 | if giturl in cached_layers: |
| 257 | logger.debug("localhostbecontroller git-copying %s to %s" % (cached_layers[giturl], localdirname)) |
| 258 | self._shellcmd("git clone \"%s\" \"%s\"" % (cached_layers[giturl], localdirname)) |
| 259 | self._shellcmd("git remote remove origin", localdirname) |
| 260 | self._shellcmd("git remote add origin \"%s\"" % giturl, localdirname) |
| 261 | else: |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 262 | logger.debug("localhostbecontroller: cloning %s in %s" % (giturl, localdirname)) |
| 263 | self._shellcmd('git clone "%s" "%s"' % (giturl, localdirname)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 264 | |
| 265 | # branch magic name "HEAD" will inhibit checkout |
| 266 | if commit != "HEAD": |
| 267 | logger.debug("localhostbecontroller: checking out commit %s to %s " % (commit, localdirname)) |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 268 | ref = commit if re.match('^[a-fA-F0-9]+$', commit) else 'origin/%s' % commit |
| 269 | self._shellcmd('git fetch --all && git reset --hard "%s"' % ref, localdirname) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 270 | |
| 271 | # take the localdirname as poky dir if we can find the oe-init-build-env |
| 272 | if self.pokydirname is None and os.path.exists(os.path.join(localdirname, "oe-init-build-env")): |
| 273 | logger.debug("localhostbecontroller: selected poky dir name %s" % localdirname) |
| 274 | self.pokydirname = localdirname |
| 275 | |
| 276 | # make sure we have a working bitbake |
| 277 | if not os.path.exists(os.path.join(self.pokydirname, 'bitbake')): |
| 278 | logger.debug("localhostbecontroller: checking bitbake into the poky dirname %s " % self.pokydirname) |
| 279 | self._shellcmd("git clone -b \"%s\" \"%s\" \"%s\" " % (bitbakes[0].commit, bitbakes[0].giturl, os.path.join(self.pokydirname, 'bitbake'))) |
| 280 | |
| 281 | # verify our repositories |
| 282 | for name, dirpath in gitrepos[(giturl, commit)]: |
| 283 | localdirpath = os.path.join(localdirname, dirpath) |
| 284 | logger.debug("localhostbecontroller: localdirpath expected '%s'" % localdirpath) |
| 285 | if not os.path.exists(localdirpath): |
| 286 | raise BuildSetupException("Cannot find layer git path '%s' in checked out repository '%s:%s'. Aborting." % (localdirpath, giturl, commit)) |
| 287 | |
| 288 | if name != "bitbake": |
| 289 | layerlist.append(localdirpath.rstrip("/")) |
| 290 | |
| 291 | logger.debug("localhostbecontroller: current layer list %s " % pformat(layerlist)) |
| 292 | |
| 293 | # 4. configure the build environment, so we have a conf/bblayers.conf |
| 294 | assert self.pokydirname is not None |
| 295 | self._setupBE() |
| 296 | |
| 297 | # 5. update the bblayers.conf |
| 298 | bblayerconf = os.path.join(self.be.builddir, "conf/bblayers.conf") |
| 299 | if not os.path.exists(bblayerconf): |
| 300 | raise BuildSetupException("BE is not consistent: bblayers.conf file missing at %s" % bblayerconf) |
| 301 | |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 302 | # 6. create custom layer and add custom recipes to it |
| 303 | layerpath = os.path.join(self.be.sourcedir, "_meta-toaster-custom") |
| 304 | if os.path.isdir(layerpath): |
| 305 | shutil.rmtree(layerpath) # remove leftovers from previous builds |
| 306 | for target in targets: |
| 307 | try: |
| 308 | customrecipe = CustomImageRecipe.objects.get(name=target.target, |
| 309 | project=bitbakes[0].req.project) |
| 310 | except CustomImageRecipe.DoesNotExist: |
| 311 | continue # not a custom recipe, skip |
| 312 | |
| 313 | # create directory structure |
| 314 | for name in ("conf", "recipes"): |
| 315 | path = os.path.join(layerpath, name) |
| 316 | if not os.path.isdir(path): |
| 317 | os.makedirs(path) |
| 318 | |
| 319 | # create layer.oonf |
| 320 | config = os.path.join(layerpath, "conf", "layer.conf") |
| 321 | if not os.path.isfile(config): |
| 322 | with open(config, "w") as conf: |
| 323 | conf.write('BBPATH .= ":${LAYERDIR}"\nBBFILES += "${LAYERDIR}/recipes/*.bb"\n') |
| 324 | |
| 325 | # create recipe |
| 326 | recipe = os.path.join(layerpath, "recipes", "%s.bb" % target.target) |
| 327 | with open(recipe, "w") as recipef: |
| 328 | recipef.write("require %s\n" % customrecipe.base_recipe.recipe.file_path) |
| 329 | packages = [pkg.name for pkg in customrecipe.packages.all()] |
| 330 | if packages: |
| 331 | recipef.write('IMAGE_INSTALL = "%s"\n' % ' '.join(packages)) |
| 332 | |
| 333 | # create *Layer* objects needed for build machinery to work |
| 334 | layer = Layer.objects.get_or_create(name="Toaster Custom layer", |
| 335 | summary="Layer for custom recipes", |
| 336 | vcs_url="file://%s" % layerpath)[0] |
| 337 | breq = target.req |
| 338 | lver = Layer_Version.objects.get_or_create(project=breq.project, layer=layer, |
| 339 | dirpath=layerpath, build=breq.build)[0] |
| 340 | ProjectLayer.objects.get_or_create(project=breq.project, layercommit=lver, |
| 341 | optional=False) |
| 342 | BRLayer.objects.get_or_create(req=breq, name=layer.name, dirpath=layerpath, |
| 343 | giturl="file://%s" % layerpath) |
| 344 | if os.path.isdir(layerpath): |
| 345 | layerlist.append(layerpath) |
| 346 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 347 | BuildEnvironmentController._updateBBLayers(bblayerconf, layerlist) |
| 348 | |
| 349 | self.islayerset = True |
| 350 | return True |
| 351 | |
| 352 | def readServerLogFile(self): |
| 353 | return open(os.path.join(self.be.builddir, "toaster_server.log"), "r").read() |
| 354 | |
| 355 | def release(self): |
| 356 | assert self.be.sourcedir and os.path.exists(self.be.builddir) |
| 357 | import shutil |
| 358 | shutil.rmtree(os.path.join(self.be.sourcedir, "build")) |
| 359 | assert not os.path.exists(self.be.builddir) |
| 360 | |
| 361 | |
| 362 | def triggerBuild(self, bitbake, layers, variables, targets): |
| 363 | # set up the buid environment with the needed layers |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame^] | 364 | self.setLayers(bitbake, layers, targets) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 365 | self.writeConfFile("conf/toaster-pre.conf", variables) |
| 366 | self.writeConfFile("conf/toaster.conf", raw = "INHERIT+=\"toaster buildhistory\"") |
| 367 | |
| 368 | # get the bb server running with the build req id and build env id |
| 369 | bbctrl = self.getBBController() |
| 370 | |
| 371 | # trigger the build command |
| 372 | task = reduce(lambda x, y: x if len(y)== 0 else y, map(lambda y: y.task, targets)) |
| 373 | if len(task) == 0: |
| 374 | task = None |
| 375 | |
| 376 | bbctrl.build(list(map(lambda x:x.target, targets)), task) |
| 377 | |
| 378 | logger.debug("localhostbecontroller: Build launched, exiting. Follow build logs at %s/toaster_ui.log" % self.be.builddir) |
| 379 | |
| 380 | # disconnect from the server |
| 381 | bbctrl.disconnect() |