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 |
| 26 | from django.db import transaction |
| 27 | from django.db.models import Q |
| 28 | from bldcontrol.models import BuildEnvironment, BRLayer, BRVariable, BRTarget, BRBitbake |
| 29 | import subprocess |
| 30 | |
| 31 | from toastermain import settings |
| 32 | |
| 33 | from bbcontroller import BuildEnvironmentController, ShellCmdException, BuildSetupException |
| 34 | |
| 35 | import logging |
| 36 | logger = logging.getLogger("toaster") |
| 37 | |
| 38 | from pprint import pprint, pformat |
| 39 | |
| 40 | class LocalhostBEController(BuildEnvironmentController): |
| 41 | """ Implementation of the BuildEnvironmentController for the localhost; |
| 42 | this controller manages the default build directory, |
| 43 | the server setup and system start and stop for the localhost-type build environment |
| 44 | |
| 45 | """ |
| 46 | |
| 47 | def __init__(self, be): |
| 48 | super(LocalhostBEController, self).__init__(be) |
| 49 | self.dburl = settings.getDATABASE_URL() |
| 50 | self.pokydirname = None |
| 51 | self.islayerset = False |
| 52 | |
| 53 | def _shellcmd(self, command, cwd = None): |
| 54 | if cwd is None: |
| 55 | cwd = self.be.sourcedir |
| 56 | |
| 57 | logger.debug("lbc_shellcmmd: (%s) %s" % (cwd, command)) |
| 58 | p = subprocess.Popen(command, cwd = cwd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 59 | (out,err) = p.communicate() |
| 60 | p.wait() |
| 61 | if p.returncode: |
| 62 | if len(err) == 0: |
| 63 | err = "command: %s \n%s" % (command, out) |
| 64 | else: |
| 65 | err = "command: %s \n%s" % (command, err) |
| 66 | logger.warn("localhostbecontroller: shellcmd error %s" % err) |
| 67 | raise ShellCmdException(err) |
| 68 | else: |
| 69 | logger.debug("localhostbecontroller: shellcmd success") |
| 70 | return out |
| 71 | |
| 72 | def _setupBE(self): |
| 73 | assert self.pokydirname and os.path.exists(self.pokydirname) |
| 74 | path = self.be.builddir |
| 75 | if not path: |
| 76 | raise Exception("Invalid path creation specified.") |
| 77 | if not os.path.exists(path): |
| 78 | os.makedirs(path, 0755) |
| 79 | self._shellcmd("bash -c \"source %s/oe-init-build-env %s\"" % (self.pokydirname, path)) |
| 80 | # delete the templateconf.cfg; it may come from an unsupported layer configuration |
| 81 | os.remove(os.path.join(path, "conf/templateconf.cfg")) |
| 82 | |
| 83 | |
| 84 | def writeConfFile(self, file_name, variable_list = None, raw = None): |
| 85 | filepath = os.path.join(self.be.builddir, file_name) |
| 86 | with open(filepath, "w") as conffile: |
| 87 | if variable_list is not None: |
| 88 | for i in variable_list: |
| 89 | conffile.write("%s=\"%s\"\n" % (i.name, i.value)) |
| 90 | if raw is not None: |
| 91 | conffile.write(raw) |
| 92 | |
| 93 | |
| 94 | def startBBServer(self): |
| 95 | assert self.pokydirname and os.path.exists(self.pokydirname) |
| 96 | assert self.islayerset |
| 97 | |
| 98 | # find our own toasterui listener/bitbake |
| 99 | from toaster.bldcontrol.management.commands.loadconf import _reduce_canon_path |
| 100 | |
| 101 | own_bitbake = _reduce_canon_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../bin/bitbake")) |
| 102 | |
| 103 | assert os.path.exists(own_bitbake) and os.path.isfile(own_bitbake) |
| 104 | |
| 105 | logger.debug("localhostbecontroller: running the listener at %s" % own_bitbake) |
| 106 | |
| 107 | toaster_ui_log_filepath = os.path.join(self.be.builddir, "toaster_ui.log") |
| 108 | # get the file length; we need to detect the _last_ start of the toaster UI, not the first |
| 109 | toaster_ui_log_filelength = 0 |
| 110 | if os.path.exists(toaster_ui_log_filepath): |
| 111 | with open(toaster_ui_log_filepath, "w") as f: |
| 112 | f.seek(0, 2) # jump to the end |
| 113 | toaster_ui_log_filelength = f.tell() |
| 114 | |
| 115 | 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) |
| 116 | |
| 117 | port = "-1" |
| 118 | logger.debug("localhostbecontroller: starting builder \n%s\n" % cmd) |
| 119 | |
| 120 | cmdoutput = self._shellcmd(cmd) |
| 121 | with open(self.be.builddir + "/toaster_server.log", "r") as f: |
| 122 | for i in f.readlines(): |
| 123 | if i.startswith("Bitbake server address"): |
| 124 | port = i.split(" ")[-1] |
| 125 | logger.debug("localhostbecontroller: Found bitbake server port %s" % port) |
| 126 | |
| 127 | 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) |
| 128 | with open(toaster_ui_log_filepath, "a+") as f: |
| 129 | p = subprocess.Popen(cmd, cwd = self.be.builddir, shell=True, stdout=f, stderr=f) |
| 130 | |
| 131 | def _toaster_ui_started(filepath, filepos = 0): |
| 132 | if not os.path.exists(filepath): |
| 133 | return False |
| 134 | with open(filepath, "r") as f: |
| 135 | f.seek(filepos) |
| 136 | for line in f: |
| 137 | if line.startswith("NOTE: ToasterUI waiting for events"): |
| 138 | return True |
| 139 | return False |
| 140 | |
| 141 | retries = 0 |
| 142 | started = False |
| 143 | while not started and retries < 50: |
| 144 | started = _toaster_ui_started(toaster_ui_log_filepath, toaster_ui_log_filelength) |
| 145 | import time |
| 146 | logger.debug("localhostbecontroller: Waiting bitbake server to start") |
| 147 | time.sleep(0.5) |
| 148 | retries += 1 |
| 149 | |
| 150 | if not started: |
| 151 | toaster_ui_log = open(os.path.join(self.be.builddir, "toaster_ui.log"), "r").read() |
| 152 | toaster_server_log = open(os.path.join(self.be.builddir, "toaster_server.log"), "r").read() |
| 153 | raise BuildSetupException("localhostbecontroller: Bitbake server did not start in 25 seconds, aborting (Error: '%s' '%s')" % (toaster_ui_log, toaster_server_log)) |
| 154 | |
| 155 | logger.debug("localhostbecontroller: Started bitbake server") |
| 156 | |
| 157 | while port == "-1": |
| 158 | # the port specification is "autodetect"; read the bitbake.lock file |
| 159 | with open("%s/bitbake.lock" % self.be.builddir, "r") as f: |
| 160 | for line in f.readlines(): |
| 161 | if ":" in line: |
| 162 | port = line.split(":")[1].strip() |
| 163 | logger.debug("localhostbecontroller: Autodetected bitbake port %s", port) |
| 164 | break |
| 165 | |
| 166 | assert self.be.sourcedir and os.path.exists(self.be.builddir) |
| 167 | self.be.bbaddress = "localhost" |
| 168 | self.be.bbport = port |
| 169 | self.be.bbstate = BuildEnvironment.SERVER_STARTED |
| 170 | self.be.save() |
| 171 | |
| 172 | def stopBBServer(self): |
| 173 | assert self.pokydirname and os.path.exists(self.pokydirname) |
| 174 | assert self.islayerset |
| 175 | self._shellcmd("bash -c \"source %s/oe-init-build-env %s && %s source toaster stop\"" % |
| 176 | (self.pokydirname, self.be.builddir, (lambda: "" if self.be.bbtoken is None else "BBTOKEN=%s" % self.be.bbtoken)())) |
| 177 | self.be.bbstate = BuildEnvironment.SERVER_STOPPED |
| 178 | self.be.save() |
| 179 | logger.debug("localhostbecontroller: Stopped bitbake server") |
| 180 | |
| 181 | def getGitCloneDirectory(self, url, branch): |
| 182 | """ Utility that returns the last component of a git path as directory |
| 183 | """ |
| 184 | import re |
| 185 | components = re.split(r'[:\.\/]', url) |
| 186 | base = components[-2] if components[-1] == "git" else components[-1] |
| 187 | |
| 188 | if branch != "HEAD": |
| 189 | return "_%s_%s.toaster_cloned" % (base, branch) |
| 190 | |
| 191 | |
| 192 | # word of attention; this is a localhost-specific issue; only on the localhost we expect to have "HEAD" releases |
| 193 | # which _ALWAYS_ means the current poky checkout |
| 194 | from os.path import dirname as DN |
| 195 | local_checkout_path = DN(DN(DN(DN(DN(os.path.abspath(__file__)))))) |
| 196 | #logger.debug("localhostbecontroller: using HEAD checkout in %s" % local_checkout_path) |
| 197 | return local_checkout_path |
| 198 | |
| 199 | |
| 200 | def setLayers(self, bitbakes, layers): |
| 201 | """ a word of attention: by convention, the first layer for any build will be poky! """ |
| 202 | |
| 203 | assert self.be.sourcedir is not None |
| 204 | assert len(bitbakes) == 1 |
| 205 | # set layers in the layersource |
| 206 | |
| 207 | # 1. get a list of repos with branches, and map dirpaths for each layer |
| 208 | gitrepos = {} |
| 209 | |
| 210 | gitrepos[(bitbakes[0].giturl, bitbakes[0].commit)] = [] |
| 211 | gitrepos[(bitbakes[0].giturl, bitbakes[0].commit)].append( ("bitbake", bitbakes[0].dirpath) ) |
| 212 | |
| 213 | for layer in layers: |
| 214 | # we don't process local URLs |
| 215 | if layer.giturl.startswith("file://"): |
| 216 | continue |
| 217 | if not (layer.giturl, layer.commit) in gitrepos: |
| 218 | gitrepos[(layer.giturl, layer.commit)] = [] |
| 219 | gitrepos[(layer.giturl, layer.commit)].append( (layer.name, layer.dirpath) ) |
| 220 | |
| 221 | |
| 222 | logger.debug("localhostbecontroller, our git repos are %s" % pformat(gitrepos)) |
| 223 | |
| 224 | |
| 225 | # 2. find checked-out git repos in the sourcedir directory that may help faster cloning |
| 226 | |
| 227 | cached_layers = {} |
| 228 | for ldir in os.listdir(self.be.sourcedir): |
| 229 | fldir = os.path.join(self.be.sourcedir, ldir) |
| 230 | if os.path.isdir(fldir): |
| 231 | try: |
| 232 | for line in self._shellcmd("git remote -v", fldir).split("\n"): |
| 233 | try: |
| 234 | remote = line.split("\t")[1].split(" ")[0] |
| 235 | if remote not in cached_layers: |
| 236 | cached_layers[remote] = fldir |
| 237 | except IndexError: |
| 238 | pass |
| 239 | except ShellCmdException: |
| 240 | # ignore any errors in collecting git remotes |
| 241 | pass |
| 242 | |
| 243 | layerlist = [] |
| 244 | |
| 245 | |
| 246 | # 3. checkout the repositories |
| 247 | for giturl, commit in gitrepos.keys(): |
| 248 | localdirname = os.path.join(self.be.sourcedir, self.getGitCloneDirectory(giturl, commit)) |
| 249 | logger.debug("localhostbecontroller: giturl %s:%s checking out in current directory %s" % (giturl, commit, localdirname)) |
| 250 | |
| 251 | # make sure our directory is a git repository |
| 252 | if os.path.exists(localdirname): |
| 253 | localremotes = self._shellcmd("git remote -v", localdirname) |
| 254 | if not giturl in localremotes: |
| 255 | 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)) |
| 256 | else: |
| 257 | if giturl in cached_layers: |
| 258 | logger.debug("localhostbecontroller git-copying %s to %s" % (cached_layers[giturl], localdirname)) |
| 259 | self._shellcmd("git clone \"%s\" \"%s\"" % (cached_layers[giturl], localdirname)) |
| 260 | self._shellcmd("git remote remove origin", localdirname) |
| 261 | self._shellcmd("git remote add origin \"%s\"" % giturl, localdirname) |
| 262 | else: |
| 263 | logger.debug("localhostbecontroller: cloning %s:%s in %s" % (giturl, commit, localdirname)) |
| 264 | self._shellcmd("git clone \"%s\" --single-branch --branch \"%s\" \"%s\"" % (giturl, commit, localdirname)) |
| 265 | |
| 266 | # branch magic name "HEAD" will inhibit checkout |
| 267 | if commit != "HEAD": |
| 268 | logger.debug("localhostbecontroller: checking out commit %s to %s " % (commit, localdirname)) |
| 269 | self._shellcmd("git fetch --all && git checkout \"%s\" && git rebase \"origin/%s\"" % (commit, commit) , localdirname) |
| 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 | |
| 302 | BuildEnvironmentController._updateBBLayers(bblayerconf, layerlist) |
| 303 | |
| 304 | self.islayerset = True |
| 305 | return True |
| 306 | |
| 307 | def readServerLogFile(self): |
| 308 | return open(os.path.join(self.be.builddir, "toaster_server.log"), "r").read() |
| 309 | |
| 310 | def release(self): |
| 311 | assert self.be.sourcedir and os.path.exists(self.be.builddir) |
| 312 | import shutil |
| 313 | shutil.rmtree(os.path.join(self.be.sourcedir, "build")) |
| 314 | assert not os.path.exists(self.be.builddir) |
| 315 | |
| 316 | |
| 317 | def triggerBuild(self, bitbake, layers, variables, targets): |
| 318 | # set up the buid environment with the needed layers |
| 319 | self.setLayers(bitbake, layers) |
| 320 | self.writeConfFile("conf/toaster-pre.conf", variables) |
| 321 | self.writeConfFile("conf/toaster.conf", raw = "INHERIT+=\"toaster buildhistory\"") |
| 322 | |
| 323 | # get the bb server running with the build req id and build env id |
| 324 | bbctrl = self.getBBController() |
| 325 | |
| 326 | # trigger the build command |
| 327 | task = reduce(lambda x, y: x if len(y)== 0 else y, map(lambda y: y.task, targets)) |
| 328 | if len(task) == 0: |
| 329 | task = None |
| 330 | |
| 331 | bbctrl.build(list(map(lambda x:x.target, targets)), task) |
| 332 | |
| 333 | logger.debug("localhostbecontroller: Build launched, exiting. Follow build logs at %s/toaster_ui.log" % self.be.builddir) |
| 334 | |
| 335 | # disconnect from the server |
| 336 | bbctrl.disconnect() |