buildinfohelper.py 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  1. #
  2. # BitBake ToasterUI Implementation
  3. #
  4. # Copyright (C) 2013 Intel Corporation
  5. #
  6. # SPDX-License-Identifier: GPL-2.0-only
  7. #
  8. import sys
  9. import bb
  10. import re
  11. import os
  12. import django
  13. from django.utils import timezone
  14. import toaster
  15. # Add toaster module to the search path to help django.setup() find the right
  16. # modules
  17. sys.path.insert(0, os.path.dirname(toaster.__file__))
  18. #Set the DJANGO_SETTINGS_MODULE if it's not already set
  19. os.environ["DJANGO_SETTINGS_MODULE"] =\
  20. os.environ.get("DJANGO_SETTINGS_MODULE",
  21. "toaster.toastermain.settings")
  22. # Setup django framework (needs to be done before importing modules)
  23. django.setup()
  24. from orm.models import Build, Task, Recipe, Layer_Version, Layer, Target, LogMessage, HelpText
  25. from orm.models import Target_Image_File, TargetKernelFile, TargetSDKFile
  26. from orm.models import Variable, VariableHistory
  27. from orm.models import Package, Package_File, Target_Installed_Package, Target_File
  28. from orm.models import Task_Dependency, Package_Dependency
  29. from orm.models import Recipe_Dependency, Provides
  30. from orm.models import Project, CustomImagePackage
  31. from orm.models import signal_runbuilds
  32. from bldcontrol.models import BuildEnvironment, BuildRequest
  33. from bldcontrol.models import BRLayer
  34. from bldcontrol import bbcontroller
  35. from bb.msg import BBLogFormatter as formatter
  36. from django.db import models
  37. from pprint import pformat
  38. import logging
  39. from datetime import datetime, timedelta
  40. from django.db import transaction, connection
  41. # pylint: disable=invalid-name
  42. # the logger name is standard throughout BitBake
  43. logger = logging.getLogger("ToasterLogger")
  44. class NotExisting(Exception):
  45. pass
  46. class ORMWrapper(object):
  47. """ This class creates the dictionaries needed to store information in the database
  48. following the format defined by the Django models. It is also used to save this
  49. information in the database.
  50. """
  51. def __init__(self):
  52. self.layer_version_objects = []
  53. self.layer_version_built = []
  54. self.task_objects = {}
  55. self.recipe_objects = {}
  56. @staticmethod
  57. def _build_key(**kwargs):
  58. key = "0"
  59. for k in sorted(kwargs.keys()):
  60. if isinstance(kwargs[k], models.Model):
  61. key += "-%d" % kwargs[k].id
  62. else:
  63. key += "-%s" % str(kwargs[k])
  64. return key
  65. def _cached_get_or_create(self, clazz, **kwargs):
  66. """ This is a memory-cached get_or_create. We assume that the objects will not be created in the
  67. database through any other means.
  68. """
  69. assert issubclass(clazz, models.Model), "_cached_get_or_create needs to get the class as first argument"
  70. key = ORMWrapper._build_key(**kwargs)
  71. dictname = "objects_%s" % clazz.__name__
  72. if not dictname in vars(self).keys():
  73. vars(self)[dictname] = {}
  74. created = False
  75. if not key in vars(self)[dictname].keys():
  76. vars(self)[dictname][key], created = \
  77. clazz.objects.get_or_create(**kwargs)
  78. return (vars(self)[dictname][key], created)
  79. def _cached_get(self, clazz, **kwargs):
  80. """ This is a memory-cached get. We assume that the objects will not change in the database between gets.
  81. """
  82. assert issubclass(clazz, models.Model), "_cached_get needs to get the class as first argument"
  83. key = ORMWrapper._build_key(**kwargs)
  84. dictname = "objects_%s" % clazz.__name__
  85. if not dictname in vars(self).keys():
  86. vars(self)[dictname] = {}
  87. if not key in vars(self)[dictname].keys():
  88. vars(self)[dictname][key] = clazz.objects.get(**kwargs)
  89. return vars(self)[dictname][key]
  90. def get_similar_target_with_image_files(self, target):
  91. """
  92. Get a Target object "similar" to target; i.e. with the same target
  93. name ('core-image-minimal' etc.) and machine.
  94. """
  95. return target.get_similar_target_with_image_files()
  96. def get_similar_target_with_sdk_files(self, target):
  97. return target.get_similar_target_with_sdk_files()
  98. def clone_image_artifacts(self, target_from, target_to):
  99. target_to.clone_image_artifacts_from(target_from)
  100. def clone_sdk_artifacts(self, target_from, target_to):
  101. target_to.clone_sdk_artifacts_from(target_from)
  102. def _timestamp_to_datetime(self, secs):
  103. """
  104. Convert timestamp in seconds to Python datetime
  105. """
  106. return timezone.make_aware(datetime(1970, 1, 1) + timedelta(seconds=secs))
  107. # pylint: disable=no-self-use
  108. # we disable detection of no self use in functions because the methods actually work on the object
  109. # even if they don't touch self anywhere
  110. # pylint: disable=bad-continuation
  111. # we do not follow the python conventions for continuation indentation due to long lines here
  112. def get_or_create_build_object(self, brbe):
  113. prj = None
  114. buildrequest = None
  115. if brbe is not None:
  116. # Toaster-triggered build
  117. logger.debug(1, "buildinfohelper: brbe is %s" % brbe)
  118. br, _ = brbe.split(":")
  119. buildrequest = BuildRequest.objects.get(pk=br)
  120. prj = buildrequest.project
  121. else:
  122. # CLI build
  123. prj = Project.objects.get_or_create_default_project()
  124. logger.debug(1, "buildinfohelper: project is not specified, defaulting to %s" % prj)
  125. if buildrequest is not None:
  126. # reuse existing Build object
  127. build = buildrequest.build
  128. build.project = prj
  129. build.save()
  130. else:
  131. # create new Build object
  132. now = timezone.now()
  133. build = Build.objects.create(
  134. project=prj,
  135. started_on=now,
  136. completed_on=now,
  137. build_name='')
  138. logger.debug(1, "buildinfohelper: build is created %s" % build)
  139. if buildrequest is not None:
  140. buildrequest.build = build
  141. buildrequest.save()
  142. return build
  143. def update_build(self, build, data_dict):
  144. for key in data_dict:
  145. setattr(build, key, data_dict[key])
  146. build.save()
  147. @staticmethod
  148. def get_or_create_targets(target_info):
  149. """
  150. NB get_or_create() is used here because for Toaster-triggered builds,
  151. we already created the targets when the build was triggered.
  152. """
  153. result = []
  154. for target in target_info['targets']:
  155. task = ''
  156. if ':' in target:
  157. target, task = target.split(':', 1)
  158. if task.startswith('do_'):
  159. task = task[3:]
  160. if task == 'build':
  161. task = ''
  162. obj, _ = Target.objects.get_or_create(build=target_info['build'],
  163. target=target,
  164. task=task)
  165. result.append(obj)
  166. return result
  167. def update_build_stats_and_outcome(self, build, errors, warnings, taskfailures):
  168. assert isinstance(build,Build)
  169. assert isinstance(errors, int)
  170. assert isinstance(warnings, int)
  171. if build.outcome == Build.CANCELLED:
  172. return
  173. try:
  174. if build.buildrequest.state == BuildRequest.REQ_CANCELLING:
  175. return
  176. except AttributeError:
  177. # We may not have a buildrequest if this is a command line build
  178. pass
  179. outcome = Build.SUCCEEDED
  180. if errors or taskfailures:
  181. outcome = Build.FAILED
  182. build.completed_on = timezone.now()
  183. build.outcome = outcome
  184. build.save()
  185. signal_runbuilds()
  186. def update_target_set_license_manifest(self, target, license_manifest_path):
  187. target.license_manifest_path = license_manifest_path
  188. target.save()
  189. def update_target_set_package_manifest(self, target, package_manifest_path):
  190. target.package_manifest_path = package_manifest_path
  191. target.save()
  192. def update_task_object(self, build, task_name, recipe_name, task_stats):
  193. """
  194. Find the task for build which matches the recipe and task name
  195. to be stored
  196. """
  197. task_to_update = Task.objects.get(
  198. build = build,
  199. task_name = task_name,
  200. recipe__name = recipe_name
  201. )
  202. if 'started' in task_stats and 'ended' in task_stats:
  203. task_to_update.started = self._timestamp_to_datetime(task_stats['started'])
  204. task_to_update.ended = self._timestamp_to_datetime(task_stats['ended'])
  205. task_to_update.elapsed_time = (task_stats['ended'] - task_stats['started'])
  206. task_to_update.cpu_time_user = task_stats.get('cpu_time_user')
  207. task_to_update.cpu_time_system = task_stats.get('cpu_time_system')
  208. if 'disk_io_read' in task_stats and 'disk_io_write' in task_stats:
  209. task_to_update.disk_io_read = task_stats['disk_io_read']
  210. task_to_update.disk_io_write = task_stats['disk_io_write']
  211. task_to_update.disk_io = task_stats['disk_io_read'] + task_stats['disk_io_write']
  212. task_to_update.save()
  213. def get_update_task_object(self, task_information, must_exist = False):
  214. assert 'build' in task_information
  215. assert 'recipe' in task_information
  216. assert 'task_name' in task_information
  217. # we use must_exist info for database look-up optimization
  218. task_object, created = self._cached_get_or_create(Task,
  219. build=task_information['build'],
  220. recipe=task_information['recipe'],
  221. task_name=task_information['task_name']
  222. )
  223. if created and must_exist:
  224. task_information['debug'] = "build id %d, recipe id %d" % (task_information['build'].pk, task_information['recipe'].pk)
  225. raise NotExisting("Task object created when expected to exist", task_information)
  226. object_changed = False
  227. for v in vars(task_object):
  228. if v in task_information.keys():
  229. if vars(task_object)[v] != task_information[v]:
  230. vars(task_object)[v] = task_information[v]
  231. object_changed = True
  232. # update setscene-related information if the task has a setscene
  233. if task_object.outcome == Task.OUTCOME_COVERED and 1 == task_object.get_related_setscene().count():
  234. task_object.outcome = Task.OUTCOME_CACHED
  235. object_changed = True
  236. outcome_task_setscene = Task.objects.get(task_executed=True, build = task_object.build,
  237. recipe = task_object.recipe, task_name=task_object.task_name+"_setscene").outcome
  238. if outcome_task_setscene == Task.OUTCOME_SUCCESS:
  239. task_object.sstate_result = Task.SSTATE_RESTORED
  240. object_changed = True
  241. elif outcome_task_setscene == Task.OUTCOME_FAILED:
  242. task_object.sstate_result = Task.SSTATE_FAILED
  243. object_changed = True
  244. if object_changed:
  245. task_object.save()
  246. return task_object
  247. def get_update_recipe_object(self, recipe_information, must_exist = False):
  248. assert 'layer_version' in recipe_information
  249. assert 'file_path' in recipe_information
  250. assert 'pathflags' in recipe_information
  251. assert not recipe_information['file_path'].startswith("/") # we should have layer-relative paths at all times
  252. def update_recipe_obj(recipe_object):
  253. object_changed = False
  254. for v in vars(recipe_object):
  255. if v in recipe_information.keys():
  256. object_changed = True
  257. vars(recipe_object)[v] = recipe_information[v]
  258. if object_changed:
  259. recipe_object.save()
  260. recipe, created = self._cached_get_or_create(Recipe, layer_version=recipe_information['layer_version'],
  261. file_path=recipe_information['file_path'], pathflags = recipe_information['pathflags'])
  262. update_recipe_obj(recipe)
  263. built_recipe = None
  264. # Create a copy of the recipe for historical puposes and update it
  265. for built_layer in self.layer_version_built:
  266. if built_layer.layer == recipe_information['layer_version'].layer:
  267. built_recipe, c = self._cached_get_or_create(Recipe,
  268. layer_version=built_layer,
  269. file_path=recipe_information['file_path'],
  270. pathflags = recipe_information['pathflags'])
  271. update_recipe_obj(built_recipe)
  272. break
  273. # If we're in analysis mode or if this is a custom recipe
  274. # then we are wholly responsible for the data
  275. # and therefore we return the 'real' recipe rather than the build
  276. # history copy of the recipe.
  277. if recipe_information['layer_version'].build is not None and \
  278. recipe_information['layer_version'].build.project == \
  279. Project.objects.get_or_create_default_project():
  280. return recipe
  281. if built_recipe is None:
  282. return recipe
  283. return built_recipe
  284. def get_update_layer_version_object(self, build_obj, layer_obj, layer_version_information):
  285. if isinstance(layer_obj, Layer_Version):
  286. # We already found our layer version for this build so just
  287. # update it with the new build information
  288. logger.debug("We found our layer from toaster")
  289. layer_obj.local_path = layer_version_information['local_path']
  290. layer_obj.save()
  291. self.layer_version_objects.append(layer_obj)
  292. # create a new copy of this layer version as a snapshot for
  293. # historical purposes
  294. layer_copy, c = Layer_Version.objects.get_or_create(
  295. build=build_obj,
  296. layer=layer_obj.layer,
  297. release=layer_obj.release,
  298. branch=layer_version_information['branch'],
  299. commit=layer_version_information['commit'],
  300. local_path=layer_version_information['local_path'],
  301. )
  302. logger.debug("Created new layer version %s for build history",
  303. layer_copy.layer.name)
  304. self.layer_version_built.append(layer_copy)
  305. return layer_obj
  306. assert isinstance(build_obj, Build)
  307. assert isinstance(layer_obj, Layer)
  308. assert 'branch' in layer_version_information
  309. assert 'commit' in layer_version_information
  310. assert 'priority' in layer_version_information
  311. assert 'local_path' in layer_version_information
  312. # If we're doing a command line build then associate this new layer with the
  313. # project to avoid it 'contaminating' toaster data
  314. project = None
  315. if build_obj.project == Project.objects.get_or_create_default_project():
  316. project = build_obj.project
  317. layer_version_object, _ = Layer_Version.objects.get_or_create(
  318. build = build_obj,
  319. layer = layer_obj,
  320. branch = layer_version_information['branch'],
  321. commit = layer_version_information['commit'],
  322. priority = layer_version_information['priority'],
  323. local_path = layer_version_information['local_path'],
  324. project=project)
  325. self.layer_version_objects.append(layer_version_object)
  326. return layer_version_object
  327. def get_update_layer_object(self, layer_information, brbe):
  328. assert 'name' in layer_information
  329. assert 'layer_index_url' in layer_information
  330. # From command line builds we have no brbe as the request is directly
  331. # from bitbake
  332. if brbe is None:
  333. # If we don't have git commit sha then we're using a non-git
  334. # layer so set the layer_source_dir to identify it as such
  335. if not layer_information['version']['commit']:
  336. local_source_dir = layer_information["local_path"]
  337. else:
  338. local_source_dir = None
  339. layer_object, _ = \
  340. Layer.objects.get_or_create(
  341. name=layer_information['name'],
  342. local_source_dir=local_source_dir,
  343. layer_index_url=layer_information['layer_index_url'])
  344. return layer_object
  345. else:
  346. br_id, be_id = brbe.split(":")
  347. # Find the layer version by matching the layer event information
  348. # against the metadata we have in Toaster
  349. try:
  350. br_layer = BRLayer.objects.get(req=br_id,
  351. name=layer_information['name'])
  352. return br_layer.layer_version
  353. except (BRLayer.MultipleObjectsReturned, BRLayer.DoesNotExist):
  354. # There are multiple of the same layer name or the name
  355. # hasn't been determined by the toaster.bbclass layer
  356. # so let's filter by the local_path
  357. bc = bbcontroller.getBuildEnvironmentController(pk=be_id)
  358. for br_layer in BRLayer.objects.filter(req=br_id):
  359. if br_layer.giturl and \
  360. layer_information['local_path'].endswith(
  361. bc.getGitCloneDirectory(br_layer.giturl,
  362. br_layer.commit)):
  363. return br_layer.layer_version
  364. if br_layer.local_source_dir == \
  365. layer_information['local_path']:
  366. return br_layer.layer_version
  367. # We've reached the end of our search and couldn't find the layer
  368. # we can continue but some data may be missing
  369. raise NotExisting("Unidentified layer %s" %
  370. pformat(layer_information))
  371. def save_target_file_information(self, build_obj, target_obj, filedata):
  372. assert isinstance(build_obj, Build)
  373. assert isinstance(target_obj, Target)
  374. dirs = filedata['dirs']
  375. files = filedata['files']
  376. syms = filedata['syms']
  377. # always create the root directory as a special case;
  378. # note that this is never displayed, so the owner, group,
  379. # size, permission are irrelevant
  380. tf_obj = Target_File.objects.create(target = target_obj,
  381. path = '/',
  382. size = 0,
  383. owner = '',
  384. group = '',
  385. permission = '',
  386. inodetype = Target_File.ITYPE_DIRECTORY)
  387. tf_obj.save()
  388. # insert directories, ordered by name depth
  389. for d in sorted(dirs, key=lambda x:len(x[-1].split("/"))):
  390. (user, group, size) = d[1:4]
  391. permission = d[0][1:]
  392. path = d[4].lstrip(".")
  393. # we already created the root directory, so ignore any
  394. # entry for it
  395. if len(path) == 0:
  396. continue
  397. parent_path = "/".join(path.split("/")[:len(path.split("/")) - 1])
  398. if len(parent_path) == 0:
  399. parent_path = "/"
  400. parent_obj = self._cached_get(Target_File, target = target_obj, path = parent_path, inodetype = Target_File.ITYPE_DIRECTORY)
  401. tf_obj = Target_File.objects.create(
  402. target = target_obj,
  403. path = path,
  404. size = size,
  405. inodetype = Target_File.ITYPE_DIRECTORY,
  406. permission = permission,
  407. owner = user,
  408. group = group,
  409. directory = parent_obj)
  410. # we insert files
  411. for d in files:
  412. (user, group, size) = d[1:4]
  413. permission = d[0][1:]
  414. path = d[4].lstrip(".")
  415. parent_path = "/".join(path.split("/")[:len(path.split("/")) - 1])
  416. inodetype = Target_File.ITYPE_REGULAR
  417. if d[0].startswith('b'):
  418. inodetype = Target_File.ITYPE_BLOCK
  419. if d[0].startswith('c'):
  420. inodetype = Target_File.ITYPE_CHARACTER
  421. if d[0].startswith('p'):
  422. inodetype = Target_File.ITYPE_FIFO
  423. tf_obj = Target_File.objects.create(
  424. target = target_obj,
  425. path = path,
  426. size = size,
  427. inodetype = inodetype,
  428. permission = permission,
  429. owner = user,
  430. group = group)
  431. parent_obj = self._cached_get(Target_File, target = target_obj, path = parent_path, inodetype = Target_File.ITYPE_DIRECTORY)
  432. tf_obj.directory = parent_obj
  433. tf_obj.save()
  434. # we insert symlinks
  435. for d in syms:
  436. (user, group, size) = d[1:4]
  437. permission = d[0][1:]
  438. path = d[4].lstrip(".")
  439. filetarget_path = d[6]
  440. parent_path = "/".join(path.split("/")[:len(path.split("/")) - 1])
  441. if not filetarget_path.startswith("/"):
  442. # we have a relative path, get a normalized absolute one
  443. filetarget_path = parent_path + "/" + filetarget_path
  444. fcp = filetarget_path.split("/")
  445. fcpl = []
  446. for i in fcp:
  447. if i == "..":
  448. fcpl.pop()
  449. else:
  450. fcpl.append(i)
  451. filetarget_path = "/".join(fcpl)
  452. try:
  453. filetarget_obj = Target_File.objects.get(target = target_obj, path = filetarget_path)
  454. except Target_File.DoesNotExist:
  455. # we might have an invalid link; no way to detect this. just set it to None
  456. filetarget_obj = None
  457. parent_obj = Target_File.objects.get(target = target_obj, path = parent_path, inodetype = Target_File.ITYPE_DIRECTORY)
  458. tf_obj = Target_File.objects.create(
  459. target = target_obj,
  460. path = path,
  461. size = size,
  462. inodetype = Target_File.ITYPE_SYMLINK,
  463. permission = permission,
  464. owner = user,
  465. group = group,
  466. directory = parent_obj,
  467. sym_target = filetarget_obj)
  468. def save_target_package_information(self, build_obj, target_obj, packagedict, pkgpnmap, recipes, built_package=False):
  469. assert isinstance(build_obj, Build)
  470. assert isinstance(target_obj, Target)
  471. errormsg = ""
  472. for p in packagedict:
  473. # Search name swtiches round the installed name vs package name
  474. # by default installed name == package name
  475. searchname = p
  476. if p not in pkgpnmap:
  477. logger.warning("Image packages list contains %p, but is"
  478. " missing from all packages list where the"
  479. " metadata comes from. Skipping...", p)
  480. continue
  481. if 'OPKGN' in pkgpnmap[p].keys():
  482. searchname = pkgpnmap[p]['OPKGN']
  483. built_recipe = recipes[pkgpnmap[p]['PN']]
  484. if built_package:
  485. packagedict[p]['object'], created = Package.objects.get_or_create( build = build_obj, name = searchname )
  486. recipe = built_recipe
  487. else:
  488. packagedict[p]['object'], created = \
  489. CustomImagePackage.objects.get_or_create(name=searchname)
  490. # Clear the Package_Dependency objects as we're going to update
  491. # the CustomImagePackage with the latest dependency information
  492. packagedict[p]['object'].package_dependencies_target.all().delete()
  493. packagedict[p]['object'].package_dependencies_source.all().delete()
  494. try:
  495. recipe = self._cached_get(
  496. Recipe,
  497. name=built_recipe.name,
  498. layer_version__build=None,
  499. layer_version__release=
  500. built_recipe.layer_version.release,
  501. file_path=built_recipe.file_path,
  502. version=built_recipe.version
  503. )
  504. except (Recipe.DoesNotExist,
  505. Recipe.MultipleObjectsReturned) as e:
  506. logger.info("We did not find one recipe for the"
  507. "configuration data package %s %s" % (p, e))
  508. continue
  509. if created or packagedict[p]['object'].size == -1: # save the data anyway we can, not just if it was not created here; bug [YOCTO #6887]
  510. # fill in everything we can from the runtime-reverse package data
  511. try:
  512. packagedict[p]['object'].recipe = recipe
  513. packagedict[p]['object'].version = pkgpnmap[p]['PV']
  514. packagedict[p]['object'].installed_name = p
  515. packagedict[p]['object'].revision = pkgpnmap[p]['PR']
  516. packagedict[p]['object'].license = pkgpnmap[p]['LICENSE']
  517. packagedict[p]['object'].section = pkgpnmap[p]['SECTION']
  518. packagedict[p]['object'].summary = pkgpnmap[p]['SUMMARY']
  519. packagedict[p]['object'].description = pkgpnmap[p]['DESCRIPTION']
  520. packagedict[p]['object'].size = int(pkgpnmap[p]['PKGSIZE'])
  521. # no files recorded for this package, so save files info
  522. packagefile_objects = []
  523. for targetpath in pkgpnmap[p]['FILES_INFO']:
  524. targetfilesize = pkgpnmap[p]['FILES_INFO'][targetpath]
  525. packagefile_objects.append(Package_File( package = packagedict[p]['object'],
  526. path = targetpath,
  527. size = targetfilesize))
  528. if len(packagefile_objects):
  529. Package_File.objects.bulk_create(packagefile_objects)
  530. except KeyError as e:
  531. errormsg += " stpi: Key error, package %s key %s \n" % ( p, e )
  532. # save disk installed size
  533. packagedict[p]['object'].installed_size = packagedict[p]['size']
  534. packagedict[p]['object'].save()
  535. if built_package:
  536. Target_Installed_Package.objects.create(target = target_obj, package = packagedict[p]['object'])
  537. packagedeps_objs = []
  538. pattern_so = re.compile(r'.*\.so(\.\d*)?$')
  539. pattern_lib = re.compile(r'.*\-suffix(\d*)?$')
  540. pattern_ko = re.compile(r'^kernel-module-.*')
  541. for p in packagedict:
  542. for (px,deptype) in packagedict[p]['depends']:
  543. if deptype == 'depends':
  544. tdeptype = Package_Dependency.TYPE_TRDEPENDS
  545. elif deptype == 'recommends':
  546. tdeptype = Package_Dependency.TYPE_TRECOMMENDS
  547. try:
  548. # Skip known non-package objects like libraries and kernel modules
  549. if pattern_so.match(px) or pattern_lib.match(px):
  550. logger.info("Toaster does not add library file dependencies to packages (%s,%s)", p, px)
  551. continue
  552. if pattern_ko.match(px):
  553. logger.info("Toaster does not add kernel module dependencies to packages (%s,%s)", p, px)
  554. continue
  555. packagedeps_objs.append(Package_Dependency(
  556. package = packagedict[p]['object'],
  557. depends_on = packagedict[px]['object'],
  558. dep_type = tdeptype,
  559. target = target_obj))
  560. except KeyError as e:
  561. logger.warning("Could not add dependency to the package %s "
  562. "because %s is an unknown package", p, px)
  563. if len(packagedeps_objs) > 0:
  564. Package_Dependency.objects.bulk_create(packagedeps_objs)
  565. else:
  566. logger.info("No package dependencies created")
  567. if len(errormsg) > 0:
  568. logger.warning("buildinfohelper: target_package_info could not identify recipes: \n%s", errormsg)
  569. def save_target_image_file_information(self, target_obj, file_name, file_size):
  570. Target_Image_File.objects.create(target=target_obj,
  571. file_name=file_name, file_size=file_size)
  572. def save_target_kernel_file(self, target_obj, file_name, file_size):
  573. """
  574. Save kernel file (bzImage, modules*) information for a Target target_obj.
  575. """
  576. TargetKernelFile.objects.create(target=target_obj,
  577. file_name=file_name, file_size=file_size)
  578. def save_target_sdk_file(self, target_obj, file_name, file_size):
  579. """
  580. Save SDK artifacts to the database, associating them with a
  581. Target object.
  582. """
  583. TargetSDKFile.objects.create(target=target_obj, file_name=file_name,
  584. file_size=file_size)
  585. def create_logmessage(self, log_information):
  586. assert 'build' in log_information
  587. assert 'level' in log_information
  588. assert 'message' in log_information
  589. log_object = LogMessage.objects.create(
  590. build = log_information['build'],
  591. level = log_information['level'],
  592. message = log_information['message'])
  593. for v in vars(log_object):
  594. if v in log_information.keys():
  595. vars(log_object)[v] = log_information[v]
  596. return log_object.save()
  597. def save_build_package_information(self, build_obj, package_info, recipes,
  598. built_package):
  599. # assert isinstance(build_obj, Build)
  600. if not 'PN' in package_info.keys():
  601. # no package data to save (e.g. 'OPKGN'="lib64-*"|"lib32-*")
  602. return None
  603. # create and save the object
  604. pname = package_info['PKG']
  605. built_recipe = recipes[package_info['PN']]
  606. if 'OPKGN' in package_info.keys():
  607. pname = package_info['OPKGN']
  608. if built_package:
  609. bp_object, _ = Package.objects.get_or_create( build = build_obj,
  610. name = pname )
  611. recipe = built_recipe
  612. else:
  613. bp_object, created = \
  614. CustomImagePackage.objects.get_or_create(name=pname)
  615. try:
  616. recipe = self._cached_get(Recipe,
  617. name=built_recipe.name,
  618. layer_version__build=None,
  619. file_path=built_recipe.file_path,
  620. version=built_recipe.version)
  621. except (Recipe.DoesNotExist, Recipe.MultipleObjectsReturned):
  622. logger.debug("We did not find one recipe for the configuration"
  623. "data package %s" % pname)
  624. return
  625. bp_object.installed_name = package_info['PKG']
  626. bp_object.recipe = recipe
  627. bp_object.version = package_info['PKGV']
  628. bp_object.revision = package_info['PKGR']
  629. bp_object.summary = package_info['SUMMARY']
  630. bp_object.description = package_info['DESCRIPTION']
  631. bp_object.size = int(package_info['PKGSIZE'])
  632. bp_object.section = package_info['SECTION']
  633. bp_object.license = package_info['LICENSE']
  634. bp_object.save()
  635. # save any attached file information
  636. packagefile_objects = []
  637. for path in package_info['FILES_INFO']:
  638. packagefile_objects.append(Package_File( package = bp_object,
  639. path = path,
  640. size = package_info['FILES_INFO'][path] ))
  641. if len(packagefile_objects):
  642. Package_File.objects.bulk_create(packagefile_objects)
  643. def _po_byname(p):
  644. if built_package:
  645. pkg, created = Package.objects.get_or_create(build=build_obj,
  646. name=p)
  647. else:
  648. pkg, created = CustomImagePackage.objects.get_or_create(name=p)
  649. if created:
  650. pkg.size = -1
  651. pkg.save()
  652. return pkg
  653. packagedeps_objs = []
  654. # save soft dependency information
  655. if 'RDEPENDS' in package_info and package_info['RDEPENDS']:
  656. for p in bb.utils.explode_deps(package_info['RDEPENDS']):
  657. packagedeps_objs.append(Package_Dependency( package = bp_object,
  658. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RDEPENDS))
  659. if 'RPROVIDES' in package_info and package_info['RPROVIDES']:
  660. for p in bb.utils.explode_deps(package_info['RPROVIDES']):
  661. packagedeps_objs.append(Package_Dependency( package = bp_object,
  662. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RPROVIDES))
  663. if 'RRECOMMENDS' in package_info and package_info['RRECOMMENDS']:
  664. for p in bb.utils.explode_deps(package_info['RRECOMMENDS']):
  665. packagedeps_objs.append(Package_Dependency( package = bp_object,
  666. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RRECOMMENDS))
  667. if 'RSUGGESTS' in package_info and package_info['RSUGGESTS']:
  668. for p in bb.utils.explode_deps(package_info['RSUGGESTS']):
  669. packagedeps_objs.append(Package_Dependency( package = bp_object,
  670. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RSUGGESTS))
  671. if 'RREPLACES' in package_info and package_info['RREPLACES']:
  672. for p in bb.utils.explode_deps(package_info['RREPLACES']):
  673. packagedeps_objs.append(Package_Dependency( package = bp_object,
  674. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RREPLACES))
  675. if 'RCONFLICTS' in package_info and package_info['RCONFLICTS']:
  676. for p in bb.utils.explode_deps(package_info['RCONFLICTS']):
  677. packagedeps_objs.append(Package_Dependency( package = bp_object,
  678. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RCONFLICTS))
  679. if len(packagedeps_objs) > 0:
  680. Package_Dependency.objects.bulk_create(packagedeps_objs)
  681. return bp_object
  682. def save_build_variables(self, build_obj, vardump):
  683. assert isinstance(build_obj, Build)
  684. for k in vardump:
  685. desc = vardump[k]['doc']
  686. if desc is None:
  687. var_words = [word for word in k.split('_')]
  688. root_var = "_".join([word for word in var_words if word.isupper()])
  689. if root_var and root_var != k and root_var in vardump:
  690. desc = vardump[root_var]['doc']
  691. if desc is None:
  692. desc = ''
  693. if len(desc):
  694. HelpText.objects.get_or_create(build=build_obj,
  695. area=HelpText.VARIABLE,
  696. key=k, text=desc)
  697. if not bool(vardump[k]['func']):
  698. value = vardump[k]['v']
  699. if value is None:
  700. value = ''
  701. variable_obj = Variable.objects.create( build = build_obj,
  702. variable_name = k,
  703. variable_value = value,
  704. description = desc)
  705. varhist_objects = []
  706. for vh in vardump[k]['history']:
  707. if not 'documentation.conf' in vh['file']:
  708. varhist_objects.append(VariableHistory( variable = variable_obj,
  709. file_name = vh['file'],
  710. line_number = vh['line'],
  711. operation = vh['op']))
  712. if len(varhist_objects):
  713. VariableHistory.objects.bulk_create(varhist_objects)
  714. class MockEvent(object):
  715. """ This object is used to create event, for which normal event-processing methods can
  716. be used, out of data that is not coming via an actual event
  717. """
  718. def __init__(self):
  719. self.msg = None
  720. self.levelno = None
  721. self.taskname = None
  722. self.taskhash = None
  723. self.pathname = None
  724. self.lineno = None
  725. def getMessage(self):
  726. """
  727. Simulate LogRecord message return
  728. """
  729. return self.msg
  730. class BuildInfoHelper(object):
  731. """ This class gathers the build information from the server and sends it
  732. towards the ORM wrapper for storing in the database
  733. It is instantiated once per build
  734. Keeps in memory all data that needs matching before writing it to the database
  735. """
  736. # tasks which produce image files; note we include '', as we set
  737. # the task for a target to '' (i.e. 'build') if no target is
  738. # explicitly defined
  739. IMAGE_GENERATING_TASKS = ['', 'build', 'image', 'populate_sdk_ext']
  740. # pylint: disable=protected-access
  741. # the code will look into the protected variables of the event; no easy way around this
  742. # pylint: disable=bad-continuation
  743. # we do not follow the python conventions for continuation indentation due to long lines here
  744. def __init__(self, server, has_build_history = False, brbe = None):
  745. self.internal_state = {}
  746. self.internal_state['taskdata'] = {}
  747. self.internal_state['targets'] = []
  748. self.task_order = 0
  749. self.autocommit_step = 1
  750. self.server = server
  751. # we use manual transactions if the database doesn't autocommit on us
  752. if not connection.features.autocommits_when_autocommit_is_off:
  753. transaction.set_autocommit(False)
  754. self.orm_wrapper = ORMWrapper()
  755. self.has_build_history = has_build_history
  756. self.tmp_dir = self.server.runCommand(["getVariable", "TMPDIR"])[0]
  757. # this is set for Toaster-triggered builds by localhostbecontroller
  758. # via toasterui
  759. self.brbe = brbe
  760. self.project = None
  761. logger.debug(1, "buildinfohelper: Build info helper inited %s" % vars(self))
  762. ###################
  763. ## methods to convert event/external info into objects that the ORM layer uses
  764. def _ensure_build(self):
  765. """
  766. Ensure the current build object exists and is up to date with
  767. data on the bitbake server
  768. """
  769. if not 'build' in self.internal_state or not self.internal_state['build']:
  770. # create the Build object
  771. self.internal_state['build'] = \
  772. self.orm_wrapper.get_or_create_build_object(self.brbe)
  773. build = self.internal_state['build']
  774. # update missing fields on the Build object with found data
  775. build_info = {}
  776. # set to True if at least one field is going to be set
  777. changed = False
  778. if not build.build_name:
  779. build_name = self.server.runCommand(["getVariable", "BUILDNAME"])[0]
  780. # only reset the build name if the one on the server is actually
  781. # a valid value for the build_name field
  782. if build_name is not None:
  783. build_info['build_name'] = build_name
  784. changed = True
  785. if not build.machine:
  786. build_info['machine'] = self.server.runCommand(["getVariable", "MACHINE"])[0]
  787. changed = True
  788. if not build.distro:
  789. build_info['distro'] = self.server.runCommand(["getVariable", "DISTRO"])[0]
  790. changed = True
  791. if not build.distro_version:
  792. build_info['distro_version'] = self.server.runCommand(["getVariable", "DISTRO_VERSION"])[0]
  793. changed = True
  794. if not build.bitbake_version:
  795. build_info['bitbake_version'] = self.server.runCommand(["getVariable", "BB_VERSION"])[0]
  796. changed = True
  797. if changed:
  798. self.orm_wrapper.update_build(self.internal_state['build'], build_info)
  799. def _get_task_information(self, event, recipe):
  800. assert 'taskname' in vars(event)
  801. self._ensure_build()
  802. task_information = {}
  803. task_information['build'] = self.internal_state['build']
  804. task_information['outcome'] = Task.OUTCOME_NA
  805. task_information['recipe'] = recipe
  806. task_information['task_name'] = event.taskname
  807. try:
  808. # some tasks don't come with a hash. and that's ok
  809. task_information['sstate_checksum'] = event.taskhash
  810. except AttributeError:
  811. pass
  812. return task_information
  813. def _get_layer_version_for_dependency(self, pathRE):
  814. """ Returns the layer in the toaster db that has a full regex
  815. match to the pathRE. pathRE - the layer path passed as a regex in the
  816. event. It is created in cooker.py as a collection for the layer
  817. priorities.
  818. """
  819. self._ensure_build()
  820. def _sort_longest_path(layer_version):
  821. assert isinstance(layer_version, Layer_Version)
  822. return len(layer_version.local_path)
  823. # Our paths don't append a trailing slash
  824. if pathRE.endswith("/"):
  825. pathRE = pathRE[:-1]
  826. p = re.compile(pathRE)
  827. path=re.sub(r'[$^]',r'',pathRE)
  828. # Heuristics: we always match recipe to the deepest layer path in
  829. # the discovered layers
  830. for lvo in sorted(self.orm_wrapper.layer_version_objects,
  831. reverse=True, key=_sort_longest_path):
  832. if p.fullmatch(os.path.abspath(lvo.local_path)):
  833. return lvo
  834. if lvo.layer.local_source_dir:
  835. if p.fullmatch(os.path.abspath(lvo.layer.local_source_dir)):
  836. return lvo
  837. if 0 == path.find(lvo.local_path):
  838. # sub-layer path inside existing layer
  839. return lvo
  840. # if we get here, we didn't read layers correctly;
  841. # dump whatever information we have on the error log
  842. logger.warning("Could not match layer dependency for path %s : %s",
  843. pathRE,
  844. self.orm_wrapper.layer_version_objects)
  845. return None
  846. def _get_layer_version_for_path(self, path):
  847. self._ensure_build()
  848. def _slkey_interactive(layer_version):
  849. assert isinstance(layer_version, Layer_Version)
  850. return len(layer_version.local_path)
  851. # Heuristics: we always match recipe to the deepest layer path in the discovered layers
  852. for lvo in sorted(self.orm_wrapper.layer_version_objects, reverse=True, key=_slkey_interactive):
  853. # we can match to the recipe file path
  854. if path.startswith(lvo.local_path):
  855. return lvo
  856. if lvo.layer.local_source_dir and \
  857. path.startswith(lvo.layer.local_source_dir):
  858. return lvo
  859. #if we get here, we didn't read layers correctly; dump whatever information we have on the error log
  860. logger.warning("Could not match layer version for recipe path %s : %s", path, self.orm_wrapper.layer_version_objects)
  861. #mockup the new layer
  862. unknown_layer, _ = Layer.objects.get_or_create(name="Unidentified layer", layer_index_url="")
  863. unknown_layer_version_obj, _ = Layer_Version.objects.get_or_create(layer = unknown_layer, build = self.internal_state['build'])
  864. # append it so we don't run into this error again and again
  865. self.orm_wrapper.layer_version_objects.append(unknown_layer_version_obj)
  866. return unknown_layer_version_obj
  867. def _get_recipe_information_from_taskfile(self, taskfile):
  868. localfilepath = taskfile.split(":")[-1]
  869. filepath_flags = ":".join(sorted(taskfile.split(":")[:-1]))
  870. layer_version_obj = self._get_layer_version_for_path(localfilepath)
  871. recipe_info = {}
  872. recipe_info['layer_version'] = layer_version_obj
  873. recipe_info['file_path'] = localfilepath
  874. recipe_info['pathflags'] = filepath_flags
  875. if recipe_info['file_path'].startswith(recipe_info['layer_version'].local_path):
  876. recipe_info['file_path'] = recipe_info['file_path'][len(recipe_info['layer_version'].local_path):].lstrip("/")
  877. else:
  878. raise RuntimeError("Recipe file path %s is not under layer version at %s" % (recipe_info['file_path'], recipe_info['layer_version'].local_path))
  879. return recipe_info
  880. def _get_path_information(self, task_object):
  881. self._ensure_build()
  882. assert isinstance(task_object, Task)
  883. build_stats_format = "{tmpdir}/buildstats/{buildname}/{package}/"
  884. build_stats_path = []
  885. for t in self.internal_state['targets']:
  886. buildname = self.internal_state['build'].build_name
  887. pe, pv = task_object.recipe.version.split(":",1)
  888. if len(pe) > 0:
  889. package = task_object.recipe.name + "-" + pe + "_" + pv
  890. else:
  891. package = task_object.recipe.name + "-" + pv
  892. build_stats_path.append(build_stats_format.format(tmpdir=self.tmp_dir,
  893. buildname=buildname,
  894. package=package))
  895. return build_stats_path
  896. ################################
  897. ## external available methods to store information
  898. @staticmethod
  899. def _get_data_from_event(event):
  900. evdata = None
  901. if '_localdata' in vars(event):
  902. evdata = event._localdata
  903. elif 'data' in vars(event):
  904. evdata = event.data
  905. else:
  906. raise Exception("Event with neither _localdata or data properties")
  907. return evdata
  908. def store_layer_info(self, event):
  909. layerinfos = BuildInfoHelper._get_data_from_event(event)
  910. self.internal_state['lvs'] = {}
  911. for layer in layerinfos:
  912. try:
  913. self.internal_state['lvs'][self.orm_wrapper.get_update_layer_object(layerinfos[layer], self.brbe)] = layerinfos[layer]['version']
  914. self.internal_state['lvs'][self.orm_wrapper.get_update_layer_object(layerinfos[layer], self.brbe)]['local_path'] = layerinfos[layer]['local_path']
  915. except NotExisting as nee:
  916. logger.warning("buildinfohelper: cannot identify layer exception:%s ", nee)
  917. def store_started_build(self):
  918. self._ensure_build()
  919. def save_build_log_file_path(self, build_log_path):
  920. self._ensure_build()
  921. if not self.internal_state['build'].cooker_log_path:
  922. data_dict = {'cooker_log_path': build_log_path}
  923. self.orm_wrapper.update_build(self.internal_state['build'], data_dict)
  924. def save_build_targets(self, event):
  925. self._ensure_build()
  926. # create target information
  927. assert '_pkgs' in vars(event)
  928. target_information = {}
  929. target_information['targets'] = event._pkgs
  930. target_information['build'] = self.internal_state['build']
  931. self.internal_state['targets'] = self.orm_wrapper.get_or_create_targets(target_information)
  932. def save_build_layers_and_variables(self):
  933. self._ensure_build()
  934. build_obj = self.internal_state['build']
  935. # save layer version information for this build
  936. if not 'lvs' in self.internal_state:
  937. logger.error("Layer version information not found; Check if the bitbake server was configured to inherit toaster.bbclass.")
  938. else:
  939. for layer_obj in self.internal_state['lvs']:
  940. self.orm_wrapper.get_update_layer_version_object(build_obj, layer_obj, self.internal_state['lvs'][layer_obj])
  941. del self.internal_state['lvs']
  942. # Save build configuration
  943. data = self.server.runCommand(["getAllKeysWithFlags", ["doc", "func"]])[0]
  944. # convert the paths from absolute to relative to either the build directory or layer checkouts
  945. path_prefixes = []
  946. if self.brbe is not None:
  947. _, be_id = self.brbe.split(":")
  948. be = BuildEnvironment.objects.get(pk = be_id)
  949. path_prefixes.append(be.builddir)
  950. for layer in sorted(self.orm_wrapper.layer_version_objects, key = lambda x:len(x.local_path), reverse=True):
  951. path_prefixes.append(layer.local_path)
  952. # we strip the prefixes
  953. for k in data:
  954. if not bool(data[k]['func']):
  955. for vh in data[k]['history']:
  956. if not 'documentation.conf' in vh['file']:
  957. abs_file_name = vh['file']
  958. for pp in path_prefixes:
  959. if abs_file_name.startswith(pp + "/"):
  960. # preserve layer name in relative path
  961. vh['file']=abs_file_name[pp.rfind("/")+1:]
  962. break
  963. # save the variables
  964. self.orm_wrapper.save_build_variables(build_obj, data)
  965. return self.brbe
  966. def set_recipes_to_parse(self, num_recipes):
  967. """
  968. Set the number of recipes which need to be parsed for this build.
  969. This is set the first time ParseStarted is received by toasterui.
  970. """
  971. self._ensure_build()
  972. self.internal_state['build'].recipes_to_parse = num_recipes
  973. self.internal_state['build'].save()
  974. def set_recipes_parsed(self, num_recipes):
  975. """
  976. Set the number of recipes parsed so far for this build; this is updated
  977. each time a ParseProgress or ParseCompleted event is received by
  978. toasterui.
  979. """
  980. self._ensure_build()
  981. if num_recipes <= self.internal_state['build'].recipes_to_parse:
  982. self.internal_state['build'].recipes_parsed = num_recipes
  983. self.internal_state['build'].save()
  984. def update_target_image_file(self, event):
  985. evdata = BuildInfoHelper._get_data_from_event(event)
  986. for t in self.internal_state['targets']:
  987. if t.is_image:
  988. output_files = list(evdata.keys())
  989. for output in output_files:
  990. if t.target in output and 'rootfs' in output and not output.endswith(".manifest"):
  991. self.orm_wrapper.save_target_image_file_information(t, output, evdata[output])
  992. def update_artifact_image_file(self, event):
  993. self._ensure_build()
  994. evdata = BuildInfoHelper._get_data_from_event(event)
  995. for artifact_path in evdata.keys():
  996. self.orm_wrapper.save_artifact_information(
  997. self.internal_state['build'], artifact_path,
  998. evdata[artifact_path])
  999. def update_build_information(self, event, errors, warnings, taskfailures):
  1000. self._ensure_build()
  1001. self.orm_wrapper.update_build_stats_and_outcome(
  1002. self.internal_state['build'], errors, warnings, taskfailures)
  1003. def store_started_task(self, event):
  1004. assert isinstance(event, (bb.runqueue.sceneQueueTaskStarted, bb.runqueue.runQueueTaskStarted, bb.runqueue.runQueueTaskSkipped))
  1005. assert 'taskfile' in vars(event)
  1006. localfilepath = event.taskfile.split(":")[-1]
  1007. assert localfilepath.startswith("/")
  1008. identifier = event.taskfile + ":" + event.taskname
  1009. recipe_information = self._get_recipe_information_from_taskfile(event.taskfile)
  1010. recipe = self.orm_wrapper.get_update_recipe_object(recipe_information, True)
  1011. task_information = self._get_task_information(event, recipe)
  1012. task_information['outcome'] = Task.OUTCOME_NA
  1013. if isinstance(event, bb.runqueue.runQueueTaskSkipped):
  1014. assert 'reason' in vars(event)
  1015. task_information['task_executed'] = False
  1016. if event.reason == "covered":
  1017. task_information['outcome'] = Task.OUTCOME_COVERED
  1018. if event.reason == "existing":
  1019. task_information['outcome'] = Task.OUTCOME_PREBUILT
  1020. else:
  1021. task_information['task_executed'] = True
  1022. if 'noexec' in vars(event) and event.noexec:
  1023. task_information['task_executed'] = False
  1024. task_information['outcome'] = Task.OUTCOME_EMPTY
  1025. task_information['script_type'] = Task.CODING_NA
  1026. # do not assign order numbers to scene tasks
  1027. if not isinstance(event, bb.runqueue.sceneQueueTaskStarted):
  1028. self.task_order += 1
  1029. task_information['order'] = self.task_order
  1030. self.orm_wrapper.get_update_task_object(task_information)
  1031. self.internal_state['taskdata'][identifier] = {
  1032. 'outcome': task_information['outcome'],
  1033. }
  1034. def store_tasks_stats(self, event):
  1035. self._ensure_build()
  1036. task_data = BuildInfoHelper._get_data_from_event(event)
  1037. for (task_file, task_name, task_stats, recipe_name) in task_data:
  1038. build = self.internal_state['build']
  1039. self.orm_wrapper.update_task_object(build, task_name, recipe_name, task_stats)
  1040. def update_and_store_task(self, event):
  1041. assert 'taskfile' in vars(event)
  1042. localfilepath = event.taskfile.split(":")[-1]
  1043. assert localfilepath.startswith("/")
  1044. identifier = event.taskfile + ":" + event.taskname
  1045. if not identifier in self.internal_state['taskdata']:
  1046. if isinstance(event, bb.build.TaskBase):
  1047. # we do a bit of guessing
  1048. candidates = [x for x in self.internal_state['taskdata'].keys() if x.endswith(identifier)]
  1049. if len(candidates) == 1:
  1050. identifier = candidates[0]
  1051. elif len(candidates) > 1 and hasattr(event,'_package'):
  1052. if 'native-' in event._package:
  1053. identifier = 'native:' + identifier
  1054. if 'nativesdk-' in event._package:
  1055. identifier = 'nativesdk:' + identifier
  1056. candidates = [x for x in self.internal_state['taskdata'].keys() if x.endswith(identifier)]
  1057. if len(candidates) == 1:
  1058. identifier = candidates[0]
  1059. assert identifier in self.internal_state['taskdata']
  1060. identifierlist = identifier.split(":")
  1061. realtaskfile = ":".join(identifierlist[0:len(identifierlist)-1])
  1062. recipe_information = self._get_recipe_information_from_taskfile(realtaskfile)
  1063. recipe = self.orm_wrapper.get_update_recipe_object(recipe_information, True)
  1064. task_information = self._get_task_information(event,recipe)
  1065. task_information['outcome'] = self.internal_state['taskdata'][identifier]['outcome']
  1066. if 'logfile' in vars(event):
  1067. task_information['logfile'] = event.logfile
  1068. if '_message' in vars(event):
  1069. task_information['message'] = event._message
  1070. if 'taskflags' in vars(event):
  1071. # with TaskStarted, we get even more information
  1072. if 'python' in event.taskflags.keys() and event.taskflags['python'] == '1':
  1073. task_information['script_type'] = Task.CODING_PYTHON
  1074. else:
  1075. task_information['script_type'] = Task.CODING_SHELL
  1076. if task_information['outcome'] == Task.OUTCOME_NA:
  1077. if isinstance(event, (bb.runqueue.runQueueTaskCompleted, bb.runqueue.sceneQueueTaskCompleted)):
  1078. task_information['outcome'] = Task.OUTCOME_SUCCESS
  1079. del self.internal_state['taskdata'][identifier]
  1080. if isinstance(event, (bb.runqueue.runQueueTaskFailed, bb.runqueue.sceneQueueTaskFailed)):
  1081. task_information['outcome'] = Task.OUTCOME_FAILED
  1082. del self.internal_state['taskdata'][identifier]
  1083. if not connection.features.autocommits_when_autocommit_is_off:
  1084. # we force a sync point here, to get the progress bar to show
  1085. if self.autocommit_step % 3 == 0:
  1086. transaction.set_autocommit(True)
  1087. transaction.set_autocommit(False)
  1088. self.autocommit_step += 1
  1089. self.orm_wrapper.get_update_task_object(task_information, True) # must exist
  1090. def store_missed_state_tasks(self, event):
  1091. for (fn, taskname, taskhash, sstatefile) in BuildInfoHelper._get_data_from_event(event)['missed']:
  1092. # identifier = fn + taskname + "_setscene"
  1093. recipe_information = self._get_recipe_information_from_taskfile(fn)
  1094. recipe = self.orm_wrapper.get_update_recipe_object(recipe_information)
  1095. mevent = MockEvent()
  1096. mevent.taskname = taskname
  1097. mevent.taskhash = taskhash
  1098. task_information = self._get_task_information(mevent,recipe)
  1099. task_information['start_time'] = timezone.now()
  1100. task_information['outcome'] = Task.OUTCOME_NA
  1101. task_information['sstate_checksum'] = taskhash
  1102. task_information['sstate_result'] = Task.SSTATE_MISS
  1103. task_information['path_to_sstate_obj'] = sstatefile
  1104. self.orm_wrapper.get_update_task_object(task_information)
  1105. for (fn, taskname, taskhash, sstatefile) in BuildInfoHelper._get_data_from_event(event)['found']:
  1106. # identifier = fn + taskname + "_setscene"
  1107. recipe_information = self._get_recipe_information_from_taskfile(fn)
  1108. recipe = self.orm_wrapper.get_update_recipe_object(recipe_information)
  1109. mevent = MockEvent()
  1110. mevent.taskname = taskname
  1111. mevent.taskhash = taskhash
  1112. task_information = self._get_task_information(mevent,recipe)
  1113. task_information['path_to_sstate_obj'] = sstatefile
  1114. self.orm_wrapper.get_update_task_object(task_information)
  1115. def store_target_package_data(self, event):
  1116. self._ensure_build()
  1117. # for all image targets
  1118. for target in self.internal_state['targets']:
  1119. if target.is_image:
  1120. pkgdata = BuildInfoHelper._get_data_from_event(event)['pkgdata']
  1121. imgdata = BuildInfoHelper._get_data_from_event(event)['imgdata'].get(target.target, {})
  1122. filedata = BuildInfoHelper._get_data_from_event(event)['filedata'].get(target.target, {})
  1123. try:
  1124. self.orm_wrapper.save_target_package_information(self.internal_state['build'], target, imgdata, pkgdata, self.internal_state['recipes'], built_package=True)
  1125. self.orm_wrapper.save_target_package_information(self.internal_state['build'], target, imgdata.copy(), pkgdata, self.internal_state['recipes'], built_package=False)
  1126. except KeyError as e:
  1127. logger.warning("KeyError in save_target_package_information"
  1128. "%s ", e)
  1129. # only try to find files in the image if the task for this
  1130. # target is one which produces image files; otherwise, the old
  1131. # list of files in the files-in-image.txt file will be
  1132. # appended to the target even if it didn't produce any images
  1133. if target.task in BuildInfoHelper.IMAGE_GENERATING_TASKS:
  1134. try:
  1135. self.orm_wrapper.save_target_file_information(self.internal_state['build'], target, filedata)
  1136. except KeyError as e:
  1137. logger.warning("KeyError in save_target_file_information"
  1138. "%s ", e)
  1139. def cancel_cli_build(self):
  1140. """
  1141. If a build is currently underway, set its state to CANCELLED;
  1142. note that this only gets called for command line builds which are
  1143. interrupted, so it doesn't touch any BuildRequest objects
  1144. """
  1145. self._ensure_build()
  1146. self.internal_state['build'].outcome = Build.CANCELLED
  1147. self.internal_state['build'].save()
  1148. signal_runbuilds()
  1149. def store_dependency_information(self, event):
  1150. assert '_depgraph' in vars(event)
  1151. assert 'layer-priorities' in event._depgraph
  1152. assert 'pn' in event._depgraph
  1153. assert 'tdepends' in event._depgraph
  1154. errormsg = ""
  1155. # save layer version priorities
  1156. if 'layer-priorities' in event._depgraph.keys():
  1157. for lv in event._depgraph['layer-priorities']:
  1158. (_, path, _, priority) = lv
  1159. layer_version_obj = self._get_layer_version_for_dependency(path)
  1160. if layer_version_obj:
  1161. layer_version_obj.priority = priority
  1162. layer_version_obj.save()
  1163. # save recipe information
  1164. self.internal_state['recipes'] = {}
  1165. for pn in event._depgraph['pn']:
  1166. file_name = event._depgraph['pn'][pn]['filename'].split(":")[-1]
  1167. pathflags = ":".join(sorted(event._depgraph['pn'][pn]['filename'].split(":")[:-1]))
  1168. layer_version_obj = self._get_layer_version_for_path(file_name)
  1169. assert layer_version_obj is not None
  1170. recipe_info = {}
  1171. recipe_info['name'] = pn
  1172. recipe_info['layer_version'] = layer_version_obj
  1173. if 'version' in event._depgraph['pn'][pn]:
  1174. recipe_info['version'] = event._depgraph['pn'][pn]['version'].lstrip(":")
  1175. if 'summary' in event._depgraph['pn'][pn]:
  1176. recipe_info['summary'] = event._depgraph['pn'][pn]['summary']
  1177. if 'license' in event._depgraph['pn'][pn]:
  1178. recipe_info['license'] = event._depgraph['pn'][pn]['license']
  1179. if 'description' in event._depgraph['pn'][pn]:
  1180. recipe_info['description'] = event._depgraph['pn'][pn]['description']
  1181. if 'section' in event._depgraph['pn'][pn]:
  1182. recipe_info['section'] = event._depgraph['pn'][pn]['section']
  1183. if 'homepage' in event._depgraph['pn'][pn]:
  1184. recipe_info['homepage'] = event._depgraph['pn'][pn]['homepage']
  1185. if 'bugtracker' in event._depgraph['pn'][pn]:
  1186. recipe_info['bugtracker'] = event._depgraph['pn'][pn]['bugtracker']
  1187. recipe_info['file_path'] = file_name
  1188. recipe_info['pathflags'] = pathflags
  1189. if recipe_info['file_path'].startswith(recipe_info['layer_version'].local_path):
  1190. recipe_info['file_path'] = recipe_info['file_path'][len(recipe_info['layer_version'].local_path):].lstrip("/")
  1191. else:
  1192. raise RuntimeError("Recipe file path %s is not under layer version at %s" % (recipe_info['file_path'], recipe_info['layer_version'].local_path))
  1193. recipe = self.orm_wrapper.get_update_recipe_object(recipe_info)
  1194. recipe.is_image = False
  1195. if 'inherits' in event._depgraph['pn'][pn].keys():
  1196. for cls in event._depgraph['pn'][pn]['inherits']:
  1197. if cls.endswith('/image.bbclass'):
  1198. recipe.is_image = True
  1199. recipe_info['is_image'] = True
  1200. # Save the is_image state to the relevant recipe objects
  1201. self.orm_wrapper.get_update_recipe_object(recipe_info)
  1202. break
  1203. if recipe.is_image:
  1204. for t in self.internal_state['targets']:
  1205. if pn == t.target:
  1206. t.is_image = True
  1207. t.save()
  1208. self.internal_state['recipes'][pn] = recipe
  1209. # we'll not get recipes for key w/ values listed in ASSUME_PROVIDED
  1210. assume_provided = self.server.runCommand(["getVariable", "ASSUME_PROVIDED"])[0].split()
  1211. # save recipe dependency
  1212. # buildtime
  1213. recipedeps_objects = []
  1214. for recipe in event._depgraph['depends']:
  1215. target = self.internal_state['recipes'][recipe]
  1216. for dep in event._depgraph['depends'][recipe]:
  1217. if dep in assume_provided:
  1218. continue
  1219. via = None
  1220. if 'providermap' in event._depgraph and dep in event._depgraph['providermap']:
  1221. deprecipe = event._depgraph['providermap'][dep][0]
  1222. dependency = self.internal_state['recipes'][deprecipe]
  1223. via = Provides.objects.get_or_create(name=dep,
  1224. recipe=dependency)[0]
  1225. elif dep in self.internal_state['recipes']:
  1226. dependency = self.internal_state['recipes'][dep]
  1227. else:
  1228. errormsg += " stpd: KeyError saving recipe dependency for %s, %s \n" % (recipe, dep)
  1229. continue
  1230. recipe_dep = Recipe_Dependency(recipe=target,
  1231. depends_on=dependency,
  1232. via=via,
  1233. dep_type=Recipe_Dependency.TYPE_DEPENDS)
  1234. recipedeps_objects.append(recipe_dep)
  1235. Recipe_Dependency.objects.bulk_create(recipedeps_objects)
  1236. # save all task information
  1237. def _save_a_task(taskdesc):
  1238. spec = re.split(r'\.', taskdesc)
  1239. pn = ".".join(spec[0:-1])
  1240. taskname = spec[-1]
  1241. e = event
  1242. e.taskname = pn
  1243. recipe = self.internal_state['recipes'][pn]
  1244. task_info = self._get_task_information(e, recipe)
  1245. task_info['task_name'] = taskname
  1246. task_obj = self.orm_wrapper.get_update_task_object(task_info)
  1247. return task_obj
  1248. # create tasks
  1249. tasks = {}
  1250. for taskdesc in event._depgraph['tdepends']:
  1251. tasks[taskdesc] = _save_a_task(taskdesc)
  1252. # create dependencies between tasks
  1253. taskdeps_objects = []
  1254. for taskdesc in event._depgraph['tdepends']:
  1255. target = tasks[taskdesc]
  1256. for taskdep in event._depgraph['tdepends'][taskdesc]:
  1257. if taskdep not in tasks:
  1258. # Fetch tasks info is not collected previously
  1259. dep = _save_a_task(taskdep)
  1260. else:
  1261. dep = tasks[taskdep]
  1262. taskdeps_objects.append(Task_Dependency( task = target, depends_on = dep ))
  1263. Task_Dependency.objects.bulk_create(taskdeps_objects)
  1264. if len(errormsg) > 0:
  1265. logger.warning("buildinfohelper: dependency info not identify recipes: \n%s", errormsg)
  1266. def store_build_package_information(self, event):
  1267. self._ensure_build()
  1268. package_info = BuildInfoHelper._get_data_from_event(event)
  1269. self.orm_wrapper.save_build_package_information(
  1270. self.internal_state['build'],
  1271. package_info,
  1272. self.internal_state['recipes'],
  1273. built_package=True)
  1274. self.orm_wrapper.save_build_package_information(
  1275. self.internal_state['build'],
  1276. package_info,
  1277. self.internal_state['recipes'],
  1278. built_package=False)
  1279. def _store_build_done(self, errorcode):
  1280. logger.info("Build exited with errorcode %d", errorcode)
  1281. if not self.brbe:
  1282. return
  1283. br_id, be_id = self.brbe.split(":")
  1284. br = BuildRequest.objects.get(pk = br_id)
  1285. # if we're 'done' because we got cancelled update the build outcome
  1286. if br.state == BuildRequest.REQ_CANCELLING:
  1287. logger.info("Build cancelled")
  1288. br.build.outcome = Build.CANCELLED
  1289. br.build.save()
  1290. self.internal_state['build'] = br.build
  1291. errorcode = 0
  1292. if errorcode == 0:
  1293. # request archival of the project artifacts
  1294. br.state = BuildRequest.REQ_COMPLETED
  1295. else:
  1296. br.state = BuildRequest.REQ_FAILED
  1297. br.save()
  1298. be = BuildEnvironment.objects.get(pk = be_id)
  1299. be.lock = BuildEnvironment.LOCK_FREE
  1300. be.save()
  1301. signal_runbuilds()
  1302. def store_log_error(self, text):
  1303. mockevent = MockEvent()
  1304. mockevent.levelno = formatter.ERROR
  1305. mockevent.msg = text
  1306. mockevent.pathname = '-- None'
  1307. mockevent.lineno = LogMessage.ERROR
  1308. self.store_log_event(mockevent)
  1309. def store_log_exception(self, text, backtrace = ""):
  1310. mockevent = MockEvent()
  1311. mockevent.levelno = -1
  1312. mockevent.msg = text
  1313. mockevent.pathname = backtrace
  1314. mockevent.lineno = -1
  1315. self.store_log_event(mockevent)
  1316. def store_log_event(self, event,cli_backlog=True):
  1317. self._ensure_build()
  1318. if event.levelno < formatter.WARNING:
  1319. return
  1320. # early return for CLI builds
  1321. if cli_backlog and self.brbe is None:
  1322. if not 'backlog' in self.internal_state:
  1323. self.internal_state['backlog'] = []
  1324. self.internal_state['backlog'].append(event)
  1325. return
  1326. if 'backlog' in self.internal_state:
  1327. # if we have a backlog of events, do our best to save them here
  1328. if len(self.internal_state['backlog']):
  1329. tempevent = self.internal_state['backlog'].pop()
  1330. logger.debug(1, "buildinfohelper: Saving stored event %s "
  1331. % tempevent)
  1332. self.store_log_event(tempevent,cli_backlog)
  1333. else:
  1334. logger.info("buildinfohelper: All events saved")
  1335. del self.internal_state['backlog']
  1336. log_information = {}
  1337. log_information['build'] = self.internal_state['build']
  1338. if event.levelno == formatter.CRITICAL:
  1339. log_information['level'] = LogMessage.CRITICAL
  1340. elif event.levelno == formatter.ERROR:
  1341. log_information['level'] = LogMessage.ERROR
  1342. elif event.levelno == formatter.WARNING:
  1343. log_information['level'] = LogMessage.WARNING
  1344. elif event.levelno == -2: # toaster self-logging
  1345. log_information['level'] = -2
  1346. else:
  1347. log_information['level'] = LogMessage.INFO
  1348. log_information['message'] = event.getMessage()
  1349. log_information['pathname'] = event.pathname
  1350. log_information['lineno'] = event.lineno
  1351. logger.info("Logging error 2: %s", log_information)
  1352. self.orm_wrapper.create_logmessage(log_information)
  1353. def _get_filenames_from_image_license(self, image_license_manifest_path):
  1354. """
  1355. Find the FILES line in the image_license.manifest file,
  1356. which has the basenames of the bzImage and modules files
  1357. in this format:
  1358. FILES: bzImage--4.4.11+git0+3a5f494784_53e84104c5-r0-qemux86-20160603165040.bin modules--4.4.11+git0+3a5f494784_53e84104c5-r0-qemux86-20160603165040.tgz
  1359. """
  1360. files = []
  1361. with open(image_license_manifest_path) as image_license:
  1362. for line in image_license:
  1363. if line.startswith('FILES'):
  1364. files_str = line.split(':')[1].strip()
  1365. files_str = re.sub(r' {2,}', ' ', files_str)
  1366. # ignore lines like "FILES:" with no filenames
  1367. if files_str:
  1368. files += files_str.split(' ')
  1369. return files
  1370. def _endswith(self, str_to_test, endings):
  1371. """
  1372. Returns True if str ends with one of the strings in the list
  1373. endings, False otherwise
  1374. """
  1375. endswith = False
  1376. for ending in endings:
  1377. if str_to_test.endswith(ending):
  1378. endswith = True
  1379. break
  1380. return endswith
  1381. def scan_task_artifacts(self, event):
  1382. """
  1383. The 'TaskArtifacts' event passes the manifest file content for the
  1384. tasks 'do_deploy', 'do_image_complete', 'do_populate_sdk', and
  1385. 'do_populate_sdk_ext'. The first two will be implemented later.
  1386. """
  1387. task_vars = BuildInfoHelper._get_data_from_event(event)
  1388. task_name = task_vars['task'][task_vars['task'].find(':')+1:]
  1389. task_artifacts = task_vars['artifacts']
  1390. if task_name in ['do_populate_sdk', 'do_populate_sdk_ext']:
  1391. targets = [target for target in self.internal_state['targets'] \
  1392. if target.task == task_name[3:]]
  1393. if not targets:
  1394. logger.warning("scan_task_artifacts: SDK targets not found: %s\n", task_name)
  1395. return
  1396. for artifact_path in task_artifacts:
  1397. if not os.path.isfile(artifact_path):
  1398. logger.warning("scan_task_artifacts: artifact file not found: %s\n", artifact_path)
  1399. continue
  1400. for target in targets:
  1401. # don't record the file if it's already been added
  1402. # to this target
  1403. matching_files = TargetSDKFile.objects.filter(
  1404. target=target, file_name=artifact_path)
  1405. if matching_files.count() == 0:
  1406. artifact_size = os.stat(artifact_path).st_size
  1407. self.orm_wrapper.save_target_sdk_file(
  1408. target, artifact_path, artifact_size)
  1409. def _get_image_files(self, deploy_dir_image, image_name, image_file_extensions):
  1410. """
  1411. Find files in deploy_dir_image whose basename starts with the
  1412. string image_name and ends with one of the strings in
  1413. image_file_extensions.
  1414. Returns a list of file dictionaries like
  1415. [
  1416. {
  1417. 'path': '/path/to/image/file',
  1418. 'size': <file size in bytes>
  1419. }
  1420. ]
  1421. """
  1422. image_files = []
  1423. for dirpath, _, filenames in os.walk(deploy_dir_image):
  1424. for filename in filenames:
  1425. if filename.startswith(image_name) and \
  1426. self._endswith(filename, image_file_extensions):
  1427. image_file_path = os.path.join(dirpath, filename)
  1428. image_file_size = os.stat(image_file_path).st_size
  1429. image_files.append({
  1430. 'path': image_file_path,
  1431. 'size': image_file_size
  1432. })
  1433. return image_files
  1434. def scan_image_artifacts(self):
  1435. """
  1436. Scan for built image artifacts in DEPLOY_DIR_IMAGE and associate them
  1437. with a Target object in self.internal_state['targets'].
  1438. We have two situations to handle:
  1439. 1. This is the first time a target + machine has been built, so
  1440. add files from the DEPLOY_DIR_IMAGE to the target.
  1441. OR
  1442. 2. There are no new files for the target (they were already produced by
  1443. a previous build), so copy them from the most recent previous build with
  1444. the same target, task and machine.
  1445. """
  1446. deploy_dir_image = \
  1447. self.server.runCommand(['getVariable', 'DEPLOY_DIR_IMAGE'])[0]
  1448. # if there's no DEPLOY_DIR_IMAGE, there aren't going to be
  1449. # any image artifacts, so we can return immediately
  1450. if not deploy_dir_image:
  1451. return
  1452. buildname = self.server.runCommand(['getVariable', 'BUILDNAME'])[0]
  1453. machine = self.server.runCommand(['getVariable', 'MACHINE'])[0]
  1454. image_name = self.server.runCommand(['getVariable', 'IMAGE_NAME'])[0]
  1455. # location of the manifest files for this build;
  1456. # note that this file is only produced if an image is produced
  1457. license_directory = \
  1458. self.server.runCommand(['getVariable', 'LICENSE_DIRECTORY'])[0]
  1459. # file name extensions for image files
  1460. image_file_extensions_unique = {}
  1461. image_fstypes = self.server.runCommand(
  1462. ['getVariable', 'IMAGE_FSTYPES'])[0]
  1463. if image_fstypes is not None:
  1464. image_types_str = image_fstypes.strip()
  1465. image_file_extensions = re.sub(r' {2,}', ' ', image_types_str)
  1466. image_file_extensions_unique = set(image_file_extensions.split(' '))
  1467. targets = self.internal_state['targets']
  1468. # filter out anything which isn't an image target
  1469. image_targets = [target for target in targets if target.is_image]
  1470. for image_target in image_targets:
  1471. # this is set to True if we find at least one file relating to
  1472. # this target; if this remains False after the scan, we copy the
  1473. # files from the most-recent Target with the same target + machine
  1474. # onto this Target instead
  1475. has_files = False
  1476. # we construct this because by the time we reach
  1477. # BuildCompleted, this has reset to
  1478. # 'defaultpkgname-<MACHINE>-<BUILDNAME>';
  1479. # we need to change it to
  1480. # <TARGET>-<MACHINE>-<BUILDNAME>
  1481. real_image_name = re.sub(r'^defaultpkgname', image_target.target,
  1482. image_name)
  1483. image_license_manifest_path = os.path.join(
  1484. license_directory,
  1485. real_image_name,
  1486. 'image_license.manifest')
  1487. image_package_manifest_path = os.path.join(
  1488. license_directory,
  1489. real_image_name,
  1490. 'image_license.manifest')
  1491. # if image_license.manifest exists, we can read the names of
  1492. # bzImage, modules etc. files for this build from it, then look for
  1493. # them in the DEPLOY_DIR_IMAGE; note that this file is only produced
  1494. # if an image file was produced
  1495. if os.path.isfile(image_license_manifest_path):
  1496. has_files = True
  1497. basenames = self._get_filenames_from_image_license(
  1498. image_license_manifest_path)
  1499. for basename in basenames:
  1500. artifact_path = os.path.join(deploy_dir_image, basename)
  1501. if not os.path.exists(artifact_path):
  1502. logger.warning("artifact %s doesn't exist, skipping" % artifact_path)
  1503. continue
  1504. artifact_size = os.stat(artifact_path).st_size
  1505. # note that the artifact will only be saved against this
  1506. # build if it hasn't been already
  1507. self.orm_wrapper.save_target_kernel_file(image_target,
  1508. artifact_path, artifact_size)
  1509. # store the license manifest path on the target
  1510. # (this file is also created any time an image file is created)
  1511. license_manifest_path = os.path.join(license_directory,
  1512. real_image_name, 'license.manifest')
  1513. self.orm_wrapper.update_target_set_license_manifest(
  1514. image_target, license_manifest_path)
  1515. # store the package manifest path on the target (this file
  1516. # is created any time an image file is created)
  1517. package_manifest_path = os.path.join(deploy_dir_image,
  1518. real_image_name + '.rootfs.manifest')
  1519. if os.path.exists(package_manifest_path):
  1520. self.orm_wrapper.update_target_set_package_manifest(
  1521. image_target, package_manifest_path)
  1522. # scan the directory for image files relating to this build
  1523. # (via real_image_name); note that we don't have to set
  1524. # has_files = True, as searching for the license manifest file
  1525. # will already have set it to true if at least one image file was
  1526. # produced; note that the real_image_name includes BUILDNAME, which
  1527. # in turn includes a timestamp; so if no files were produced for
  1528. # this timestamp (i.e. the build reused existing image files already
  1529. # in the directory), no files will be recorded against this target
  1530. image_files = self._get_image_files(deploy_dir_image,
  1531. real_image_name, image_file_extensions_unique)
  1532. for image_file in image_files:
  1533. self.orm_wrapper.save_target_image_file_information(
  1534. image_target, image_file['path'], image_file['size'])
  1535. if not has_files:
  1536. # copy image files and build artifacts from the
  1537. # most-recently-built Target with the
  1538. # same target + machine as this Target; also copy the license
  1539. # manifest path, as that is not treated as an artifact and needs
  1540. # to be set separately
  1541. similar_target = \
  1542. self.orm_wrapper.get_similar_target_with_image_files(
  1543. image_target)
  1544. if similar_target:
  1545. logger.info('image artifacts for target %s cloned from ' \
  1546. 'target %s' % (image_target.pk, similar_target.pk))
  1547. self.orm_wrapper.clone_image_artifacts(similar_target,
  1548. image_target)
  1549. def _get_sdk_targets(self):
  1550. """
  1551. Return targets which could generate SDK artifacts, i.e.
  1552. "do_populate_sdk" and "do_populate_sdk_ext".
  1553. """
  1554. return [target for target in self.internal_state['targets'] \
  1555. if target.task in ['populate_sdk', 'populate_sdk_ext']]
  1556. def scan_sdk_artifacts(self, event):
  1557. """
  1558. Note that we have to intercept an SDKArtifactInfo event from
  1559. toaster.bbclass (via toasterui) to get hold of the SDK variables we
  1560. need to be able to scan for files accurately: this is because
  1561. variables like TOOLCHAIN_OUTPUTNAME have reset to None by the time
  1562. BuildCompleted is fired by bitbake, so we have to get those values
  1563. while the build is still in progress.
  1564. For populate_sdk_ext, this runs twice, with two different
  1565. TOOLCHAIN_OUTPUTNAME settings, each of which will capture some of the
  1566. files in the SDK output directory.
  1567. """
  1568. sdk_vars = BuildInfoHelper._get_data_from_event(event)
  1569. toolchain_outputname = sdk_vars['TOOLCHAIN_OUTPUTNAME']
  1570. # targets which might have created SDK artifacts
  1571. sdk_targets = self._get_sdk_targets()
  1572. # location of SDK artifacts
  1573. tmpdir = self.server.runCommand(['getVariable', 'TMPDIR'])[0]
  1574. sdk_dir = os.path.join(tmpdir, 'deploy', 'sdk')
  1575. # all files in the SDK directory
  1576. artifacts = []
  1577. for dir_path, _, filenames in os.walk(sdk_dir):
  1578. for filename in filenames:
  1579. full_path = os.path.join(dir_path, filename)
  1580. if not os.path.islink(full_path):
  1581. artifacts.append(full_path)
  1582. for sdk_target in sdk_targets:
  1583. # find files in the SDK directory which haven't already been
  1584. # recorded against a Target and whose basename matches
  1585. # TOOLCHAIN_OUTPUTNAME
  1586. for artifact_path in artifacts:
  1587. basename = os.path.basename(artifact_path)
  1588. toolchain_match = basename.startswith(toolchain_outputname)
  1589. # files which match the name of the target which produced them;
  1590. # for example,
  1591. # poky-glibc-x86_64-core-image-sato-i586-toolchain-ext-2.1+snapshot.sh
  1592. target_match = re.search(sdk_target.target, basename)
  1593. # targets which produce "*-nativesdk-*" files
  1594. is_ext_sdk_target = sdk_target.task in \
  1595. ['do_populate_sdk_ext', 'populate_sdk_ext']
  1596. # SDK files which don't match the target name, i.e.
  1597. # x86_64-nativesdk-libc.*
  1598. # poky-glibc-x86_64-buildtools-tarball-i586-buildtools-nativesdk-standalone-2.1+snapshot*
  1599. is_ext_sdk_file = re.search('-nativesdk-', basename)
  1600. file_from_target = (toolchain_match and target_match) or \
  1601. (is_ext_sdk_target and is_ext_sdk_file)
  1602. if file_from_target:
  1603. # don't record the file if it's already been added to this
  1604. # target
  1605. matching_files = TargetSDKFile.objects.filter(
  1606. target=sdk_target, file_name=artifact_path)
  1607. if matching_files.count() == 0:
  1608. artifact_size = os.stat(artifact_path).st_size
  1609. self.orm_wrapper.save_target_sdk_file(
  1610. sdk_target, artifact_path, artifact_size)
  1611. def clone_required_sdk_artifacts(self):
  1612. """
  1613. If an SDK target doesn't have any SDK artifacts, this means that
  1614. the postfuncs of populate_sdk or populate_sdk_ext didn't fire, which
  1615. in turn means that the targets of this build didn't generate any new
  1616. artifacts.
  1617. In this case, clone SDK artifacts for targets in the current build
  1618. from existing targets for this build.
  1619. """
  1620. sdk_targets = self._get_sdk_targets()
  1621. for sdk_target in sdk_targets:
  1622. # only clone for SDK targets which have no TargetSDKFiles yet
  1623. if sdk_target.targetsdkfile_set.all().count() == 0:
  1624. similar_target = \
  1625. self.orm_wrapper.get_similar_target_with_sdk_files(
  1626. sdk_target)
  1627. if similar_target:
  1628. logger.info('SDK artifacts for target %s cloned from ' \
  1629. 'target %s' % (sdk_target.pk, similar_target.pk))
  1630. self.orm_wrapper.clone_sdk_artifacts(similar_target,
  1631. sdk_target)
  1632. def close(self, errorcode):
  1633. self._store_build_done(errorcode)
  1634. if 'backlog' in self.internal_state:
  1635. # we save missed events in the database for the current build
  1636. tempevent = self.internal_state['backlog'].pop()
  1637. # Do not skip command line build events
  1638. self.store_log_event(tempevent,False)
  1639. if not connection.features.autocommits_when_autocommit_is_off:
  1640. transaction.set_autocommit(True)
  1641. # unset the brbe; this is to prevent subsequent command-line builds
  1642. # being incorrectly attached to the previous Toaster-triggered build;
  1643. # see https://bugzilla.yoctoproject.org/show_bug.cgi?id=9021
  1644. self.brbe = None
  1645. # unset the internal Build object to prevent it being reused for the
  1646. # next build
  1647. self.internal_state['build'] = None