buildinfohelper.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  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. for p in packagedict:
  539. for (px,deptype) in packagedict[p]['depends']:
  540. if deptype == 'depends':
  541. tdeptype = Package_Dependency.TYPE_TRDEPENDS
  542. elif deptype == 'recommends':
  543. tdeptype = Package_Dependency.TYPE_TRECOMMENDS
  544. try:
  545. packagedeps_objs.append(Package_Dependency(
  546. package = packagedict[p]['object'],
  547. depends_on = packagedict[px]['object'],
  548. dep_type = tdeptype,
  549. target = target_obj))
  550. except KeyError as e:
  551. logger.warning("Could not add dependency to the package %s "
  552. "because %s is an unknown package", p, px)
  553. if len(packagedeps_objs) > 0:
  554. Package_Dependency.objects.bulk_create(packagedeps_objs)
  555. else:
  556. logger.info("No package dependencies created")
  557. if len(errormsg) > 0:
  558. logger.warning("buildinfohelper: target_package_info could not identify recipes: \n%s", errormsg)
  559. def save_target_image_file_information(self, target_obj, file_name, file_size):
  560. Target_Image_File.objects.create(target=target_obj,
  561. file_name=file_name, file_size=file_size)
  562. def save_target_kernel_file(self, target_obj, file_name, file_size):
  563. """
  564. Save kernel file (bzImage, modules*) information for a Target target_obj.
  565. """
  566. TargetKernelFile.objects.create(target=target_obj,
  567. file_name=file_name, file_size=file_size)
  568. def save_target_sdk_file(self, target_obj, file_name, file_size):
  569. """
  570. Save SDK artifacts to the database, associating them with a
  571. Target object.
  572. """
  573. TargetSDKFile.objects.create(target=target_obj, file_name=file_name,
  574. file_size=file_size)
  575. def create_logmessage(self, log_information):
  576. assert 'build' in log_information
  577. assert 'level' in log_information
  578. assert 'message' in log_information
  579. log_object = LogMessage.objects.create(
  580. build = log_information['build'],
  581. level = log_information['level'],
  582. message = log_information['message'])
  583. for v in vars(log_object):
  584. if v in log_information.keys():
  585. vars(log_object)[v] = log_information[v]
  586. return log_object.save()
  587. def save_build_package_information(self, build_obj, package_info, recipes,
  588. built_package):
  589. # assert isinstance(build_obj, Build)
  590. if not 'PN' in package_info.keys():
  591. # no package data to save (e.g. 'OPKGN'="lib64-*"|"lib32-*")
  592. return None
  593. # create and save the object
  594. pname = package_info['PKG']
  595. built_recipe = recipes[package_info['PN']]
  596. if 'OPKGN' in package_info.keys():
  597. pname = package_info['OPKGN']
  598. if built_package:
  599. bp_object, _ = Package.objects.get_or_create( build = build_obj,
  600. name = pname )
  601. recipe = built_recipe
  602. else:
  603. bp_object, created = \
  604. CustomImagePackage.objects.get_or_create(name=pname)
  605. try:
  606. recipe = self._cached_get(Recipe,
  607. name=built_recipe.name,
  608. layer_version__build=None,
  609. file_path=built_recipe.file_path,
  610. version=built_recipe.version)
  611. except (Recipe.DoesNotExist, Recipe.MultipleObjectsReturned):
  612. logger.debug("We did not find one recipe for the configuration"
  613. "data package %s" % pname)
  614. return
  615. bp_object.installed_name = package_info['PKG']
  616. bp_object.recipe = recipe
  617. bp_object.version = package_info['PKGV']
  618. bp_object.revision = package_info['PKGR']
  619. bp_object.summary = package_info['SUMMARY']
  620. bp_object.description = package_info['DESCRIPTION']
  621. bp_object.size = int(package_info['PKGSIZE'])
  622. bp_object.section = package_info['SECTION']
  623. bp_object.license = package_info['LICENSE']
  624. bp_object.save()
  625. # save any attached file information
  626. packagefile_objects = []
  627. for path in package_info['FILES_INFO']:
  628. packagefile_objects.append(Package_File( package = bp_object,
  629. path = path,
  630. size = package_info['FILES_INFO'][path] ))
  631. if len(packagefile_objects):
  632. Package_File.objects.bulk_create(packagefile_objects)
  633. def _po_byname(p):
  634. if built_package:
  635. pkg, created = Package.objects.get_or_create(build=build_obj,
  636. name=p)
  637. else:
  638. pkg, created = CustomImagePackage.objects.get_or_create(name=p)
  639. if created:
  640. pkg.size = -1
  641. pkg.save()
  642. return pkg
  643. packagedeps_objs = []
  644. # save soft dependency information
  645. if 'RDEPENDS' in package_info and package_info['RDEPENDS']:
  646. for p in bb.utils.explode_deps(package_info['RDEPENDS']):
  647. packagedeps_objs.append(Package_Dependency( package = bp_object,
  648. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RDEPENDS))
  649. if 'RPROVIDES' in package_info and package_info['RPROVIDES']:
  650. for p in bb.utils.explode_deps(package_info['RPROVIDES']):
  651. packagedeps_objs.append(Package_Dependency( package = bp_object,
  652. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RPROVIDES))
  653. if 'RRECOMMENDS' in package_info and package_info['RRECOMMENDS']:
  654. for p in bb.utils.explode_deps(package_info['RRECOMMENDS']):
  655. packagedeps_objs.append(Package_Dependency( package = bp_object,
  656. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RRECOMMENDS))
  657. if 'RSUGGESTS' in package_info and package_info['RSUGGESTS']:
  658. for p in bb.utils.explode_deps(package_info['RSUGGESTS']):
  659. packagedeps_objs.append(Package_Dependency( package = bp_object,
  660. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RSUGGESTS))
  661. if 'RREPLACES' in package_info and package_info['RREPLACES']:
  662. for p in bb.utils.explode_deps(package_info['RREPLACES']):
  663. packagedeps_objs.append(Package_Dependency( package = bp_object,
  664. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RREPLACES))
  665. if 'RCONFLICTS' in package_info and package_info['RCONFLICTS']:
  666. for p in bb.utils.explode_deps(package_info['RCONFLICTS']):
  667. packagedeps_objs.append(Package_Dependency( package = bp_object,
  668. depends_on = _po_byname(p), dep_type = Package_Dependency.TYPE_RCONFLICTS))
  669. if len(packagedeps_objs) > 0:
  670. Package_Dependency.objects.bulk_create(packagedeps_objs)
  671. return bp_object
  672. def save_build_variables(self, build_obj, vardump):
  673. assert isinstance(build_obj, Build)
  674. for k in vardump:
  675. desc = vardump[k]['doc']
  676. if desc is None:
  677. var_words = [word for word in k.split('_')]
  678. root_var = "_".join([word for word in var_words if word.isupper()])
  679. if root_var and root_var != k and root_var in vardump:
  680. desc = vardump[root_var]['doc']
  681. if desc is None:
  682. desc = ''
  683. if len(desc):
  684. HelpText.objects.get_or_create(build=build_obj,
  685. area=HelpText.VARIABLE,
  686. key=k, text=desc)
  687. if not bool(vardump[k]['func']):
  688. value = vardump[k]['v']
  689. if value is None:
  690. value = ''
  691. variable_obj = Variable.objects.create( build = build_obj,
  692. variable_name = k,
  693. variable_value = value,
  694. description = desc)
  695. varhist_objects = []
  696. for vh in vardump[k]['history']:
  697. if not 'documentation.conf' in vh['file']:
  698. varhist_objects.append(VariableHistory( variable = variable_obj,
  699. file_name = vh['file'],
  700. line_number = vh['line'],
  701. operation = vh['op']))
  702. if len(varhist_objects):
  703. VariableHistory.objects.bulk_create(varhist_objects)
  704. class MockEvent(object):
  705. """ This object is used to create event, for which normal event-processing methods can
  706. be used, out of data that is not coming via an actual event
  707. """
  708. def __init__(self):
  709. self.msg = None
  710. self.levelno = None
  711. self.taskname = None
  712. self.taskhash = None
  713. self.pathname = None
  714. self.lineno = None
  715. def getMessage(self):
  716. """
  717. Simulate LogRecord message return
  718. """
  719. return self.msg
  720. class BuildInfoHelper(object):
  721. """ This class gathers the build information from the server and sends it
  722. towards the ORM wrapper for storing in the database
  723. It is instantiated once per build
  724. Keeps in memory all data that needs matching before writing it to the database
  725. """
  726. # tasks which produce image files; note we include '', as we set
  727. # the task for a target to '' (i.e. 'build') if no target is
  728. # explicitly defined
  729. IMAGE_GENERATING_TASKS = ['', 'build', 'image', 'populate_sdk_ext']
  730. # pylint: disable=protected-access
  731. # the code will look into the protected variables of the event; no easy way around this
  732. # pylint: disable=bad-continuation
  733. # we do not follow the python conventions for continuation indentation due to long lines here
  734. def __init__(self, server, has_build_history = False, brbe = None):
  735. self.internal_state = {}
  736. self.internal_state['taskdata'] = {}
  737. self.internal_state['targets'] = []
  738. self.task_order = 0
  739. self.autocommit_step = 1
  740. self.server = server
  741. # we use manual transactions if the database doesn't autocommit on us
  742. if not connection.features.autocommits_when_autocommit_is_off:
  743. transaction.set_autocommit(False)
  744. self.orm_wrapper = ORMWrapper()
  745. self.has_build_history = has_build_history
  746. self.tmp_dir = self.server.runCommand(["getVariable", "TMPDIR"])[0]
  747. # this is set for Toaster-triggered builds by localhostbecontroller
  748. # via toasterui
  749. self.brbe = brbe
  750. self.project = None
  751. logger.debug(1, "buildinfohelper: Build info helper inited %s" % vars(self))
  752. ###################
  753. ## methods to convert event/external info into objects that the ORM layer uses
  754. def _ensure_build(self):
  755. """
  756. Ensure the current build object exists and is up to date with
  757. data on the bitbake server
  758. """
  759. if not 'build' in self.internal_state or not self.internal_state['build']:
  760. # create the Build object
  761. self.internal_state['build'] = \
  762. self.orm_wrapper.get_or_create_build_object(self.brbe)
  763. build = self.internal_state['build']
  764. # update missing fields on the Build object with found data
  765. build_info = {}
  766. # set to True if at least one field is going to be set
  767. changed = False
  768. if not build.build_name:
  769. build_name = self.server.runCommand(["getVariable", "BUILDNAME"])[0]
  770. # only reset the build name if the one on the server is actually
  771. # a valid value for the build_name field
  772. if build_name != None:
  773. build_info['build_name'] = build_name
  774. changed = True
  775. if not build.machine:
  776. build_info['machine'] = self.server.runCommand(["getVariable", "MACHINE"])[0]
  777. changed = True
  778. if not build.distro:
  779. build_info['distro'] = self.server.runCommand(["getVariable", "DISTRO"])[0]
  780. changed = True
  781. if not build.distro_version:
  782. build_info['distro_version'] = self.server.runCommand(["getVariable", "DISTRO_VERSION"])[0]
  783. changed = True
  784. if not build.bitbake_version:
  785. build_info['bitbake_version'] = self.server.runCommand(["getVariable", "BB_VERSION"])[0]
  786. changed = True
  787. if changed:
  788. self.orm_wrapper.update_build(self.internal_state['build'], build_info)
  789. def _get_task_information(self, event, recipe):
  790. assert 'taskname' in vars(event)
  791. self._ensure_build()
  792. task_information = {}
  793. task_information['build'] = self.internal_state['build']
  794. task_information['outcome'] = Task.OUTCOME_NA
  795. task_information['recipe'] = recipe
  796. task_information['task_name'] = event.taskname
  797. try:
  798. # some tasks don't come with a hash. and that's ok
  799. task_information['sstate_checksum'] = event.taskhash
  800. except AttributeError:
  801. pass
  802. return task_information
  803. def _get_layer_version_for_dependency(self, pathRE):
  804. """ Returns the layer in the toaster db that has a full regex
  805. match to the pathRE. pathRE - the layer path passed as a regex in the
  806. event. It is created in cooker.py as a collection for the layer
  807. priorities.
  808. """
  809. self._ensure_build()
  810. def _sort_longest_path(layer_version):
  811. assert isinstance(layer_version, Layer_Version)
  812. return len(layer_version.local_path)
  813. # Our paths don't append a trailing slash
  814. if pathRE.endswith("/"):
  815. pathRE = pathRE[:-1]
  816. p = re.compile(pathRE)
  817. path=re.sub(r'[$^]',r'',pathRE)
  818. # Heuristics: we always match recipe to the deepest layer path in
  819. # the discovered layers
  820. for lvo in sorted(self.orm_wrapper.layer_version_objects,
  821. reverse=True, key=_sort_longest_path):
  822. if p.fullmatch(os.path.abspath(lvo.local_path)):
  823. return lvo
  824. if lvo.layer.local_source_dir:
  825. if p.fullmatch(os.path.abspath(lvo.layer.local_source_dir)):
  826. return lvo
  827. if 0 == path.find(lvo.local_path):
  828. # sub-layer path inside existing layer
  829. return lvo
  830. # if we get here, we didn't read layers correctly;
  831. # dump whatever information we have on the error log
  832. logger.warning("Could not match layer dependency for path %s : %s",
  833. pathRE,
  834. self.orm_wrapper.layer_version_objects)
  835. return None
  836. def _get_layer_version_for_path(self, path):
  837. self._ensure_build()
  838. def _slkey_interactive(layer_version):
  839. assert isinstance(layer_version, Layer_Version)
  840. return len(layer_version.local_path)
  841. # Heuristics: we always match recipe to the deepest layer path in the discovered layers
  842. for lvo in sorted(self.orm_wrapper.layer_version_objects, reverse=True, key=_slkey_interactive):
  843. # we can match to the recipe file path
  844. if path.startswith(lvo.local_path):
  845. return lvo
  846. if lvo.layer.local_source_dir and \
  847. path.startswith(lvo.layer.local_source_dir):
  848. return lvo
  849. #if we get here, we didn't read layers correctly; dump whatever information we have on the error log
  850. logger.warning("Could not match layer version for recipe path %s : %s", path, self.orm_wrapper.layer_version_objects)
  851. #mockup the new layer
  852. unknown_layer, _ = Layer.objects.get_or_create(name="Unidentified layer", layer_index_url="")
  853. unknown_layer_version_obj, _ = Layer_Version.objects.get_or_create(layer = unknown_layer, build = self.internal_state['build'])
  854. # append it so we don't run into this error again and again
  855. self.orm_wrapper.layer_version_objects.append(unknown_layer_version_obj)
  856. return unknown_layer_version_obj
  857. def _get_recipe_information_from_taskfile(self, taskfile):
  858. localfilepath = taskfile.split(":")[-1]
  859. filepath_flags = ":".join(sorted(taskfile.split(":")[:-1]))
  860. layer_version_obj = self._get_layer_version_for_path(localfilepath)
  861. recipe_info = {}
  862. recipe_info['layer_version'] = layer_version_obj
  863. recipe_info['file_path'] = localfilepath
  864. recipe_info['pathflags'] = filepath_flags
  865. if recipe_info['file_path'].startswith(recipe_info['layer_version'].local_path):
  866. recipe_info['file_path'] = recipe_info['file_path'][len(recipe_info['layer_version'].local_path):].lstrip("/")
  867. else:
  868. raise RuntimeError("Recipe file path %s is not under layer version at %s" % (recipe_info['file_path'], recipe_info['layer_version'].local_path))
  869. return recipe_info
  870. def _get_path_information(self, task_object):
  871. self._ensure_build()
  872. assert isinstance(task_object, Task)
  873. build_stats_format = "{tmpdir}/buildstats/{buildname}/{package}/"
  874. build_stats_path = []
  875. for t in self.internal_state['targets']:
  876. buildname = self.internal_state['build'].build_name
  877. pe, pv = task_object.recipe.version.split(":",1)
  878. if len(pe) > 0:
  879. package = task_object.recipe.name + "-" + pe + "_" + pv
  880. else:
  881. package = task_object.recipe.name + "-" + pv
  882. build_stats_path.append(build_stats_format.format(tmpdir=self.tmp_dir,
  883. buildname=buildname,
  884. package=package))
  885. return build_stats_path
  886. ################################
  887. ## external available methods to store information
  888. @staticmethod
  889. def _get_data_from_event(event):
  890. evdata = None
  891. if '_localdata' in vars(event):
  892. evdata = event._localdata
  893. elif 'data' in vars(event):
  894. evdata = event.data
  895. else:
  896. raise Exception("Event with neither _localdata or data properties")
  897. return evdata
  898. def store_layer_info(self, event):
  899. layerinfos = BuildInfoHelper._get_data_from_event(event)
  900. self.internal_state['lvs'] = {}
  901. for layer in layerinfos:
  902. try:
  903. self.internal_state['lvs'][self.orm_wrapper.get_update_layer_object(layerinfos[layer], self.brbe)] = layerinfos[layer]['version']
  904. self.internal_state['lvs'][self.orm_wrapper.get_update_layer_object(layerinfos[layer], self.brbe)]['local_path'] = layerinfos[layer]['local_path']
  905. except NotExisting as nee:
  906. logger.warning("buildinfohelper: cannot identify layer exception:%s ", nee)
  907. def store_started_build(self):
  908. self._ensure_build()
  909. def save_build_log_file_path(self, build_log_path):
  910. self._ensure_build()
  911. if not self.internal_state['build'].cooker_log_path:
  912. data_dict = {'cooker_log_path': build_log_path}
  913. self.orm_wrapper.update_build(self.internal_state['build'], data_dict)
  914. def save_build_targets(self, event):
  915. self._ensure_build()
  916. # create target information
  917. assert '_pkgs' in vars(event)
  918. target_information = {}
  919. target_information['targets'] = event._pkgs
  920. target_information['build'] = self.internal_state['build']
  921. self.internal_state['targets'] = self.orm_wrapper.get_or_create_targets(target_information)
  922. def save_build_layers_and_variables(self):
  923. self._ensure_build()
  924. build_obj = self.internal_state['build']
  925. # save layer version information for this build
  926. if not 'lvs' in self.internal_state:
  927. logger.error("Layer version information not found; Check if the bitbake server was configured to inherit toaster.bbclass.")
  928. else:
  929. for layer_obj in self.internal_state['lvs']:
  930. self.orm_wrapper.get_update_layer_version_object(build_obj, layer_obj, self.internal_state['lvs'][layer_obj])
  931. del self.internal_state['lvs']
  932. # Save build configuration
  933. data = self.server.runCommand(["getAllKeysWithFlags", ["doc", "func"]])[0]
  934. # convert the paths from absolute to relative to either the build directory or layer checkouts
  935. path_prefixes = []
  936. if self.brbe is not None:
  937. _, be_id = self.brbe.split(":")
  938. be = BuildEnvironment.objects.get(pk = be_id)
  939. path_prefixes.append(be.builddir)
  940. for layer in sorted(self.orm_wrapper.layer_version_objects, key = lambda x:len(x.local_path), reverse=True):
  941. path_prefixes.append(layer.local_path)
  942. # we strip the prefixes
  943. for k in data:
  944. if not bool(data[k]['func']):
  945. for vh in data[k]['history']:
  946. if not 'documentation.conf' in vh['file']:
  947. abs_file_name = vh['file']
  948. for pp in path_prefixes:
  949. if abs_file_name.startswith(pp + "/"):
  950. # preserve layer name in relative path
  951. vh['file']=abs_file_name[pp.rfind("/")+1:]
  952. break
  953. # save the variables
  954. self.orm_wrapper.save_build_variables(build_obj, data)
  955. return self.brbe
  956. def set_recipes_to_parse(self, num_recipes):
  957. """
  958. Set the number of recipes which need to be parsed for this build.
  959. This is set the first time ParseStarted is received by toasterui.
  960. """
  961. self._ensure_build()
  962. self.internal_state['build'].recipes_to_parse = num_recipes
  963. self.internal_state['build'].save()
  964. def set_recipes_parsed(self, num_recipes):
  965. """
  966. Set the number of recipes parsed so far for this build; this is updated
  967. each time a ParseProgress or ParseCompleted event is received by
  968. toasterui.
  969. """
  970. self._ensure_build()
  971. if num_recipes <= self.internal_state['build'].recipes_to_parse:
  972. self.internal_state['build'].recipes_parsed = num_recipes
  973. self.internal_state['build'].save()
  974. def update_target_image_file(self, event):
  975. evdata = BuildInfoHelper._get_data_from_event(event)
  976. for t in self.internal_state['targets']:
  977. if t.is_image == True:
  978. output_files = list(evdata.keys())
  979. for output in output_files:
  980. if t.target in output and 'rootfs' in output and not output.endswith(".manifest"):
  981. self.orm_wrapper.save_target_image_file_information(t, output, evdata[output])
  982. def update_artifact_image_file(self, event):
  983. self._ensure_build()
  984. evdata = BuildInfoHelper._get_data_from_event(event)
  985. for artifact_path in evdata.keys():
  986. self.orm_wrapper.save_artifact_information(
  987. self.internal_state['build'], artifact_path,
  988. evdata[artifact_path])
  989. def update_build_information(self, event, errors, warnings, taskfailures):
  990. self._ensure_build()
  991. self.orm_wrapper.update_build_stats_and_outcome(
  992. self.internal_state['build'], errors, warnings, taskfailures)
  993. def store_started_task(self, event):
  994. assert isinstance(event, (bb.runqueue.sceneQueueTaskStarted, bb.runqueue.runQueueTaskStarted, bb.runqueue.runQueueTaskSkipped))
  995. assert 'taskfile' in vars(event)
  996. localfilepath = event.taskfile.split(":")[-1]
  997. assert localfilepath.startswith("/")
  998. identifier = event.taskfile + ":" + event.taskname
  999. recipe_information = self._get_recipe_information_from_taskfile(event.taskfile)
  1000. recipe = self.orm_wrapper.get_update_recipe_object(recipe_information, True)
  1001. task_information = self._get_task_information(event, recipe)
  1002. task_information['outcome'] = Task.OUTCOME_NA
  1003. if isinstance(event, bb.runqueue.runQueueTaskSkipped):
  1004. assert 'reason' in vars(event)
  1005. task_information['task_executed'] = False
  1006. if event.reason == "covered":
  1007. task_information['outcome'] = Task.OUTCOME_COVERED
  1008. if event.reason == "existing":
  1009. task_information['outcome'] = Task.OUTCOME_PREBUILT
  1010. else:
  1011. task_information['task_executed'] = True
  1012. if 'noexec' in vars(event) and event.noexec == True:
  1013. task_information['task_executed'] = False
  1014. task_information['outcome'] = Task.OUTCOME_EMPTY
  1015. task_information['script_type'] = Task.CODING_NA
  1016. # do not assign order numbers to scene tasks
  1017. if not isinstance(event, bb.runqueue.sceneQueueTaskStarted):
  1018. self.task_order += 1
  1019. task_information['order'] = self.task_order
  1020. self.orm_wrapper.get_update_task_object(task_information)
  1021. self.internal_state['taskdata'][identifier] = {
  1022. 'outcome': task_information['outcome'],
  1023. }
  1024. def store_tasks_stats(self, event):
  1025. self._ensure_build()
  1026. task_data = BuildInfoHelper._get_data_from_event(event)
  1027. for (task_file, task_name, task_stats, recipe_name) in task_data:
  1028. build = self.internal_state['build']
  1029. self.orm_wrapper.update_task_object(build, task_name, recipe_name, task_stats)
  1030. def update_and_store_task(self, event):
  1031. assert 'taskfile' in vars(event)
  1032. localfilepath = event.taskfile.split(":")[-1]
  1033. assert localfilepath.startswith("/")
  1034. identifier = event.taskfile + ":" + event.taskname
  1035. if not identifier in self.internal_state['taskdata']:
  1036. if isinstance(event, bb.build.TaskBase):
  1037. # we do a bit of guessing
  1038. candidates = [x for x in self.internal_state['taskdata'].keys() if x.endswith(identifier)]
  1039. if len(candidates) == 1:
  1040. identifier = candidates[0]
  1041. elif len(candidates) > 1 and hasattr(event,'_package'):
  1042. if 'native-' in event._package:
  1043. identifier = 'native:' + identifier
  1044. if 'nativesdk-' in event._package:
  1045. identifier = 'nativesdk:' + identifier
  1046. candidates = [x for x in self.internal_state['taskdata'].keys() if x.endswith(identifier)]
  1047. if len(candidates) == 1:
  1048. identifier = candidates[0]
  1049. assert identifier in self.internal_state['taskdata']
  1050. identifierlist = identifier.split(":")
  1051. realtaskfile = ":".join(identifierlist[0:len(identifierlist)-1])
  1052. recipe_information = self._get_recipe_information_from_taskfile(realtaskfile)
  1053. recipe = self.orm_wrapper.get_update_recipe_object(recipe_information, True)
  1054. task_information = self._get_task_information(event,recipe)
  1055. task_information['outcome'] = self.internal_state['taskdata'][identifier]['outcome']
  1056. if 'logfile' in vars(event):
  1057. task_information['logfile'] = event.logfile
  1058. if '_message' in vars(event):
  1059. task_information['message'] = event._message
  1060. if 'taskflags' in vars(event):
  1061. # with TaskStarted, we get even more information
  1062. if 'python' in event.taskflags.keys() and event.taskflags['python'] == '1':
  1063. task_information['script_type'] = Task.CODING_PYTHON
  1064. else:
  1065. task_information['script_type'] = Task.CODING_SHELL
  1066. if task_information['outcome'] == Task.OUTCOME_NA:
  1067. if isinstance(event, (bb.runqueue.runQueueTaskCompleted, bb.runqueue.sceneQueueTaskCompleted)):
  1068. task_information['outcome'] = Task.OUTCOME_SUCCESS
  1069. del self.internal_state['taskdata'][identifier]
  1070. if isinstance(event, (bb.runqueue.runQueueTaskFailed, bb.runqueue.sceneQueueTaskFailed)):
  1071. task_information['outcome'] = Task.OUTCOME_FAILED
  1072. del self.internal_state['taskdata'][identifier]
  1073. if not connection.features.autocommits_when_autocommit_is_off:
  1074. # we force a sync point here, to get the progress bar to show
  1075. if self.autocommit_step % 3 == 0:
  1076. transaction.set_autocommit(True)
  1077. transaction.set_autocommit(False)
  1078. self.autocommit_step += 1
  1079. self.orm_wrapper.get_update_task_object(task_information, True) # must exist
  1080. def store_missed_state_tasks(self, event):
  1081. for (fn, taskname, taskhash, sstatefile) in BuildInfoHelper._get_data_from_event(event)['missed']:
  1082. # identifier = fn + taskname + "_setscene"
  1083. recipe_information = self._get_recipe_information_from_taskfile(fn)
  1084. recipe = self.orm_wrapper.get_update_recipe_object(recipe_information)
  1085. mevent = MockEvent()
  1086. mevent.taskname = taskname
  1087. mevent.taskhash = taskhash
  1088. task_information = self._get_task_information(mevent,recipe)
  1089. task_information['start_time'] = timezone.now()
  1090. task_information['outcome'] = Task.OUTCOME_NA
  1091. task_information['sstate_checksum'] = taskhash
  1092. task_information['sstate_result'] = Task.SSTATE_MISS
  1093. task_information['path_to_sstate_obj'] = sstatefile
  1094. self.orm_wrapper.get_update_task_object(task_information)
  1095. for (fn, taskname, taskhash, sstatefile) in BuildInfoHelper._get_data_from_event(event)['found']:
  1096. # identifier = fn + taskname + "_setscene"
  1097. recipe_information = self._get_recipe_information_from_taskfile(fn)
  1098. recipe = self.orm_wrapper.get_update_recipe_object(recipe_information)
  1099. mevent = MockEvent()
  1100. mevent.taskname = taskname
  1101. mevent.taskhash = taskhash
  1102. task_information = self._get_task_information(mevent,recipe)
  1103. task_information['path_to_sstate_obj'] = sstatefile
  1104. self.orm_wrapper.get_update_task_object(task_information)
  1105. def store_target_package_data(self, event):
  1106. self._ensure_build()
  1107. # for all image targets
  1108. for target in self.internal_state['targets']:
  1109. if target.is_image:
  1110. pkgdata = BuildInfoHelper._get_data_from_event(event)['pkgdata']
  1111. imgdata = BuildInfoHelper._get_data_from_event(event)['imgdata'].get(target.target, {})
  1112. filedata = BuildInfoHelper._get_data_from_event(event)['filedata'].get(target.target, {})
  1113. try:
  1114. self.orm_wrapper.save_target_package_information(self.internal_state['build'], target, imgdata, pkgdata, self.internal_state['recipes'], built_package=True)
  1115. self.orm_wrapper.save_target_package_information(self.internal_state['build'], target, imgdata.copy(), pkgdata, self.internal_state['recipes'], built_package=False)
  1116. except KeyError as e:
  1117. logger.warning("KeyError in save_target_package_information"
  1118. "%s ", e)
  1119. # only try to find files in the image if the task for this
  1120. # target is one which produces image files; otherwise, the old
  1121. # list of files in the files-in-image.txt file will be
  1122. # appended to the target even if it didn't produce any images
  1123. if target.task in BuildInfoHelper.IMAGE_GENERATING_TASKS:
  1124. try:
  1125. self.orm_wrapper.save_target_file_information(self.internal_state['build'], target, filedata)
  1126. except KeyError as e:
  1127. logger.warning("KeyError in save_target_file_information"
  1128. "%s ", e)
  1129. def cancel_cli_build(self):
  1130. """
  1131. If a build is currently underway, set its state to CANCELLED;
  1132. note that this only gets called for command line builds which are
  1133. interrupted, so it doesn't touch any BuildRequest objects
  1134. """
  1135. self._ensure_build()
  1136. self.internal_state['build'].outcome = Build.CANCELLED
  1137. self.internal_state['build'].save()
  1138. signal_runbuilds()
  1139. def store_dependency_information(self, event):
  1140. assert '_depgraph' in vars(event)
  1141. assert 'layer-priorities' in event._depgraph
  1142. assert 'pn' in event._depgraph
  1143. assert 'tdepends' in event._depgraph
  1144. errormsg = ""
  1145. # save layer version priorities
  1146. if 'layer-priorities' in event._depgraph.keys():
  1147. for lv in event._depgraph['layer-priorities']:
  1148. (_, path, _, priority) = lv
  1149. layer_version_obj = self._get_layer_version_for_dependency(path)
  1150. if layer_version_obj:
  1151. layer_version_obj.priority = priority
  1152. layer_version_obj.save()
  1153. # save recipe information
  1154. self.internal_state['recipes'] = {}
  1155. for pn in event._depgraph['pn']:
  1156. file_name = event._depgraph['pn'][pn]['filename'].split(":")[-1]
  1157. pathflags = ":".join(sorted(event._depgraph['pn'][pn]['filename'].split(":")[:-1]))
  1158. layer_version_obj = self._get_layer_version_for_path(file_name)
  1159. assert layer_version_obj is not None
  1160. recipe_info = {}
  1161. recipe_info['name'] = pn
  1162. recipe_info['layer_version'] = layer_version_obj
  1163. if 'version' in event._depgraph['pn'][pn]:
  1164. recipe_info['version'] = event._depgraph['pn'][pn]['version'].lstrip(":")
  1165. if 'summary' in event._depgraph['pn'][pn]:
  1166. recipe_info['summary'] = event._depgraph['pn'][pn]['summary']
  1167. if 'license' in event._depgraph['pn'][pn]:
  1168. recipe_info['license'] = event._depgraph['pn'][pn]['license']
  1169. if 'description' in event._depgraph['pn'][pn]:
  1170. recipe_info['description'] = event._depgraph['pn'][pn]['description']
  1171. if 'section' in event._depgraph['pn'][pn]:
  1172. recipe_info['section'] = event._depgraph['pn'][pn]['section']
  1173. if 'homepage' in event._depgraph['pn'][pn]:
  1174. recipe_info['homepage'] = event._depgraph['pn'][pn]['homepage']
  1175. if 'bugtracker' in event._depgraph['pn'][pn]:
  1176. recipe_info['bugtracker'] = event._depgraph['pn'][pn]['bugtracker']
  1177. recipe_info['file_path'] = file_name
  1178. recipe_info['pathflags'] = pathflags
  1179. if recipe_info['file_path'].startswith(recipe_info['layer_version'].local_path):
  1180. recipe_info['file_path'] = recipe_info['file_path'][len(recipe_info['layer_version'].local_path):].lstrip("/")
  1181. else:
  1182. raise RuntimeError("Recipe file path %s is not under layer version at %s" % (recipe_info['file_path'], recipe_info['layer_version'].local_path))
  1183. recipe = self.orm_wrapper.get_update_recipe_object(recipe_info)
  1184. recipe.is_image = False
  1185. if 'inherits' in event._depgraph['pn'][pn].keys():
  1186. for cls in event._depgraph['pn'][pn]['inherits']:
  1187. if cls.endswith('/image.bbclass'):
  1188. recipe.is_image = True
  1189. recipe_info['is_image'] = True
  1190. # Save the is_image state to the relevant recipe objects
  1191. self.orm_wrapper.get_update_recipe_object(recipe_info)
  1192. break
  1193. if recipe.is_image:
  1194. for t in self.internal_state['targets']:
  1195. if pn == t.target:
  1196. t.is_image = True
  1197. t.save()
  1198. self.internal_state['recipes'][pn] = recipe
  1199. # we'll not get recipes for key w/ values listed in ASSUME_PROVIDED
  1200. assume_provided = self.server.runCommand(["getVariable", "ASSUME_PROVIDED"])[0].split()
  1201. # save recipe dependency
  1202. # buildtime
  1203. recipedeps_objects = []
  1204. for recipe in event._depgraph['depends']:
  1205. target = self.internal_state['recipes'][recipe]
  1206. for dep in event._depgraph['depends'][recipe]:
  1207. if dep in assume_provided:
  1208. continue
  1209. via = None
  1210. if 'providermap' in event._depgraph and dep in event._depgraph['providermap']:
  1211. deprecipe = event._depgraph['providermap'][dep][0]
  1212. dependency = self.internal_state['recipes'][deprecipe]
  1213. via = Provides.objects.get_or_create(name=dep,
  1214. recipe=dependency)[0]
  1215. elif dep in self.internal_state['recipes']:
  1216. dependency = self.internal_state['recipes'][dep]
  1217. else:
  1218. errormsg += " stpd: KeyError saving recipe dependency for %s, %s \n" % (recipe, dep)
  1219. continue
  1220. recipe_dep = Recipe_Dependency(recipe=target,
  1221. depends_on=dependency,
  1222. via=via,
  1223. dep_type=Recipe_Dependency.TYPE_DEPENDS)
  1224. recipedeps_objects.append(recipe_dep)
  1225. Recipe_Dependency.objects.bulk_create(recipedeps_objects)
  1226. # save all task information
  1227. def _save_a_task(taskdesc):
  1228. spec = re.split(r'\.', taskdesc)
  1229. pn = ".".join(spec[0:-1])
  1230. taskname = spec[-1]
  1231. e = event
  1232. e.taskname = pn
  1233. recipe = self.internal_state['recipes'][pn]
  1234. task_info = self._get_task_information(e, recipe)
  1235. task_info['task_name'] = taskname
  1236. task_obj = self.orm_wrapper.get_update_task_object(task_info)
  1237. return task_obj
  1238. # create tasks
  1239. tasks = {}
  1240. for taskdesc in event._depgraph['tdepends']:
  1241. tasks[taskdesc] = _save_a_task(taskdesc)
  1242. # create dependencies between tasks
  1243. taskdeps_objects = []
  1244. for taskdesc in event._depgraph['tdepends']:
  1245. target = tasks[taskdesc]
  1246. for taskdep in event._depgraph['tdepends'][taskdesc]:
  1247. if taskdep not in tasks:
  1248. # Fetch tasks info is not collected previously
  1249. dep = _save_a_task(taskdep)
  1250. else:
  1251. dep = tasks[taskdep]
  1252. taskdeps_objects.append(Task_Dependency( task = target, depends_on = dep ))
  1253. Task_Dependency.objects.bulk_create(taskdeps_objects)
  1254. if len(errormsg) > 0:
  1255. logger.warning("buildinfohelper: dependency info not identify recipes: \n%s", errormsg)
  1256. def store_build_package_information(self, event):
  1257. self._ensure_build()
  1258. package_info = BuildInfoHelper._get_data_from_event(event)
  1259. self.orm_wrapper.save_build_package_information(
  1260. self.internal_state['build'],
  1261. package_info,
  1262. self.internal_state['recipes'],
  1263. built_package=True)
  1264. self.orm_wrapper.save_build_package_information(
  1265. self.internal_state['build'],
  1266. package_info,
  1267. self.internal_state['recipes'],
  1268. built_package=False)
  1269. def _store_build_done(self, errorcode):
  1270. logger.info("Build exited with errorcode %d", errorcode)
  1271. if not self.brbe:
  1272. return
  1273. br_id, be_id = self.brbe.split(":")
  1274. br = BuildRequest.objects.get(pk = br_id)
  1275. # if we're 'done' because we got cancelled update the build outcome
  1276. if br.state == BuildRequest.REQ_CANCELLING:
  1277. logger.info("Build cancelled")
  1278. br.build.outcome = Build.CANCELLED
  1279. br.build.save()
  1280. self.internal_state['build'] = br.build
  1281. errorcode = 0
  1282. if errorcode == 0:
  1283. # request archival of the project artifacts
  1284. br.state = BuildRequest.REQ_COMPLETED
  1285. else:
  1286. br.state = BuildRequest.REQ_FAILED
  1287. br.save()
  1288. be = BuildEnvironment.objects.get(pk = be_id)
  1289. be.lock = BuildEnvironment.LOCK_FREE
  1290. be.save()
  1291. signal_runbuilds()
  1292. def store_log_error(self, text):
  1293. mockevent = MockEvent()
  1294. mockevent.levelno = formatter.ERROR
  1295. mockevent.msg = text
  1296. mockevent.pathname = '-- None'
  1297. mockevent.lineno = LogMessage.ERROR
  1298. self.store_log_event(mockevent)
  1299. def store_log_exception(self, text, backtrace = ""):
  1300. mockevent = MockEvent()
  1301. mockevent.levelno = -1
  1302. mockevent.msg = text
  1303. mockevent.pathname = backtrace
  1304. mockevent.lineno = -1
  1305. self.store_log_event(mockevent)
  1306. def store_log_event(self, event,cli_backlog=True):
  1307. self._ensure_build()
  1308. if event.levelno < formatter.WARNING:
  1309. return
  1310. # early return for CLI builds
  1311. if cli_backlog and self.brbe is None:
  1312. if not 'backlog' in self.internal_state:
  1313. self.internal_state['backlog'] = []
  1314. self.internal_state['backlog'].append(event)
  1315. return
  1316. if 'backlog' in self.internal_state:
  1317. # if we have a backlog of events, do our best to save them here
  1318. if len(self.internal_state['backlog']):
  1319. tempevent = self.internal_state['backlog'].pop()
  1320. logger.debug(1, "buildinfohelper: Saving stored event %s "
  1321. % tempevent)
  1322. self.store_log_event(tempevent,cli_backlog)
  1323. else:
  1324. logger.info("buildinfohelper: All events saved")
  1325. del self.internal_state['backlog']
  1326. log_information = {}
  1327. log_information['build'] = self.internal_state['build']
  1328. if event.levelno == formatter.CRITICAL:
  1329. log_information['level'] = LogMessage.CRITICAL
  1330. elif event.levelno == formatter.ERROR:
  1331. log_information['level'] = LogMessage.ERROR
  1332. elif event.levelno == formatter.WARNING:
  1333. log_information['level'] = LogMessage.WARNING
  1334. elif event.levelno == -2: # toaster self-logging
  1335. log_information['level'] = -2
  1336. else:
  1337. log_information['level'] = LogMessage.INFO
  1338. log_information['message'] = event.getMessage()
  1339. log_information['pathname'] = event.pathname
  1340. log_information['lineno'] = event.lineno
  1341. logger.info("Logging error 2: %s", log_information)
  1342. self.orm_wrapper.create_logmessage(log_information)
  1343. def _get_filenames_from_image_license(self, image_license_manifest_path):
  1344. """
  1345. Find the FILES line in the image_license.manifest file,
  1346. which has the basenames of the bzImage and modules files
  1347. in this format:
  1348. FILES: bzImage--4.4.11+git0+3a5f494784_53e84104c5-r0-qemux86-20160603165040.bin modules--4.4.11+git0+3a5f494784_53e84104c5-r0-qemux86-20160603165040.tgz
  1349. """
  1350. files = []
  1351. with open(image_license_manifest_path) as image_license:
  1352. for line in image_license:
  1353. if line.startswith('FILES'):
  1354. files_str = line.split(':')[1].strip()
  1355. files_str = re.sub(r' {2,}', ' ', files_str)
  1356. # ignore lines like "FILES:" with no filenames
  1357. if files_str:
  1358. files += files_str.split(' ')
  1359. return files
  1360. def _endswith(self, str_to_test, endings):
  1361. """
  1362. Returns True if str ends with one of the strings in the list
  1363. endings, False otherwise
  1364. """
  1365. endswith = False
  1366. for ending in endings:
  1367. if str_to_test.endswith(ending):
  1368. endswith = True
  1369. break
  1370. return endswith
  1371. def scan_task_artifacts(self, event):
  1372. """
  1373. The 'TaskArtifacts' event passes the manifest file content for the
  1374. tasks 'do_deploy', 'do_image_complete', 'do_populate_sdk', and
  1375. 'do_populate_sdk_ext'. The first two will be implemented later.
  1376. """
  1377. task_vars = BuildInfoHelper._get_data_from_event(event)
  1378. task_name = task_vars['task'][task_vars['task'].find(':')+1:]
  1379. task_artifacts = task_vars['artifacts']
  1380. if task_name in ['do_populate_sdk', 'do_populate_sdk_ext']:
  1381. targets = [target for target in self.internal_state['targets'] \
  1382. if target.task == task_name[3:]]
  1383. if not targets:
  1384. logger.warning("scan_task_artifacts: SDK targets not found: %s\n", task_name)
  1385. return
  1386. for artifact_path in task_artifacts:
  1387. if not os.path.isfile(artifact_path):
  1388. logger.warning("scan_task_artifacts: artifact file not found: %s\n", artifact_path)
  1389. continue
  1390. for target in targets:
  1391. # don't record the file if it's already been added
  1392. # to this target
  1393. matching_files = TargetSDKFile.objects.filter(
  1394. target=target, file_name=artifact_path)
  1395. if matching_files.count() == 0:
  1396. artifact_size = os.stat(artifact_path).st_size
  1397. self.orm_wrapper.save_target_sdk_file(
  1398. target, artifact_path, artifact_size)
  1399. def _get_image_files(self, deploy_dir_image, image_name, image_file_extensions):
  1400. """
  1401. Find files in deploy_dir_image whose basename starts with the
  1402. string image_name and ends with one of the strings in
  1403. image_file_extensions.
  1404. Returns a list of file dictionaries like
  1405. [
  1406. {
  1407. 'path': '/path/to/image/file',
  1408. 'size': <file size in bytes>
  1409. }
  1410. ]
  1411. """
  1412. image_files = []
  1413. for dirpath, _, filenames in os.walk(deploy_dir_image):
  1414. for filename in filenames:
  1415. if filename.startswith(image_name) and \
  1416. self._endswith(filename, image_file_extensions):
  1417. image_file_path = os.path.join(dirpath, filename)
  1418. image_file_size = os.stat(image_file_path).st_size
  1419. image_files.append({
  1420. 'path': image_file_path,
  1421. 'size': image_file_size
  1422. })
  1423. return image_files
  1424. def scan_image_artifacts(self):
  1425. """
  1426. Scan for built image artifacts in DEPLOY_DIR_IMAGE and associate them
  1427. with a Target object in self.internal_state['targets'].
  1428. We have two situations to handle:
  1429. 1. This is the first time a target + machine has been built, so
  1430. add files from the DEPLOY_DIR_IMAGE to the target.
  1431. OR
  1432. 2. There are no new files for the target (they were already produced by
  1433. a previous build), so copy them from the most recent previous build with
  1434. the same target, task and machine.
  1435. """
  1436. deploy_dir_image = \
  1437. self.server.runCommand(['getVariable', 'DEPLOY_DIR_IMAGE'])[0]
  1438. # if there's no DEPLOY_DIR_IMAGE, there aren't going to be
  1439. # any image artifacts, so we can return immediately
  1440. if not deploy_dir_image:
  1441. return
  1442. buildname = self.server.runCommand(['getVariable', 'BUILDNAME'])[0]
  1443. machine = self.server.runCommand(['getVariable', 'MACHINE'])[0]
  1444. image_name = self.server.runCommand(['getVariable', 'IMAGE_NAME'])[0]
  1445. # location of the manifest files for this build;
  1446. # note that this file is only produced if an image is produced
  1447. license_directory = \
  1448. self.server.runCommand(['getVariable', 'LICENSE_DIRECTORY'])[0]
  1449. # file name extensions for image files
  1450. image_file_extensions_unique = {}
  1451. image_fstypes = self.server.runCommand(
  1452. ['getVariable', 'IMAGE_FSTYPES'])[0]
  1453. if image_fstypes != None:
  1454. image_types_str = image_fstypes.strip()
  1455. image_file_extensions = re.sub(r' {2,}', ' ', image_types_str)
  1456. image_file_extensions_unique = set(image_file_extensions.split(' '))
  1457. targets = self.internal_state['targets']
  1458. # filter out anything which isn't an image target
  1459. image_targets = [target for target in targets if target.is_image]
  1460. for image_target in image_targets:
  1461. # this is set to True if we find at least one file relating to
  1462. # this target; if this remains False after the scan, we copy the
  1463. # files from the most-recent Target with the same target + machine
  1464. # onto this Target instead
  1465. has_files = False
  1466. # we construct this because by the time we reach
  1467. # BuildCompleted, this has reset to
  1468. # 'defaultpkgname-<MACHINE>-<BUILDNAME>';
  1469. # we need to change it to
  1470. # <TARGET>-<MACHINE>-<BUILDNAME>
  1471. real_image_name = re.sub(r'^defaultpkgname', image_target.target,
  1472. image_name)
  1473. image_license_manifest_path = os.path.join(
  1474. license_directory,
  1475. real_image_name,
  1476. 'image_license.manifest')
  1477. image_package_manifest_path = os.path.join(
  1478. license_directory,
  1479. real_image_name,
  1480. 'image_license.manifest')
  1481. # if image_license.manifest exists, we can read the names of
  1482. # bzImage, modules etc. files for this build from it, then look for
  1483. # them in the DEPLOY_DIR_IMAGE; note that this file is only produced
  1484. # if an image file was produced
  1485. if os.path.isfile(image_license_manifest_path):
  1486. has_files = True
  1487. basenames = self._get_filenames_from_image_license(
  1488. image_license_manifest_path)
  1489. for basename in basenames:
  1490. artifact_path = os.path.join(deploy_dir_image, basename)
  1491. if not os.path.exists(artifact_path):
  1492. logger.warning("artifact %s doesn't exist, skipping" % artifact_path)
  1493. continue
  1494. artifact_size = os.stat(artifact_path).st_size
  1495. # note that the artifact will only be saved against this
  1496. # build if it hasn't been already
  1497. self.orm_wrapper.save_target_kernel_file(image_target,
  1498. artifact_path, artifact_size)
  1499. # store the license manifest path on the target
  1500. # (this file is also created any time an image file is created)
  1501. license_manifest_path = os.path.join(license_directory,
  1502. real_image_name, 'license.manifest')
  1503. self.orm_wrapper.update_target_set_license_manifest(
  1504. image_target, license_manifest_path)
  1505. # store the package manifest path on the target (this file
  1506. # is created any time an image file is created)
  1507. package_manifest_path = os.path.join(deploy_dir_image,
  1508. real_image_name + '.rootfs.manifest')
  1509. if os.path.exists(package_manifest_path):
  1510. self.orm_wrapper.update_target_set_package_manifest(
  1511. image_target, package_manifest_path)
  1512. # scan the directory for image files relating to this build
  1513. # (via real_image_name); note that we don't have to set
  1514. # has_files = True, as searching for the license manifest file
  1515. # will already have set it to true if at least one image file was
  1516. # produced; note that the real_image_name includes BUILDNAME, which
  1517. # in turn includes a timestamp; so if no files were produced for
  1518. # this timestamp (i.e. the build reused existing image files already
  1519. # in the directory), no files will be recorded against this target
  1520. image_files = self._get_image_files(deploy_dir_image,
  1521. real_image_name, image_file_extensions_unique)
  1522. for image_file in image_files:
  1523. self.orm_wrapper.save_target_image_file_information(
  1524. image_target, image_file['path'], image_file['size'])
  1525. if not has_files:
  1526. # copy image files and build artifacts from the
  1527. # most-recently-built Target with the
  1528. # same target + machine as this Target; also copy the license
  1529. # manifest path, as that is not treated as an artifact and needs
  1530. # to be set separately
  1531. similar_target = \
  1532. self.orm_wrapper.get_similar_target_with_image_files(
  1533. image_target)
  1534. if similar_target:
  1535. logger.info('image artifacts for target %s cloned from ' \
  1536. 'target %s' % (image_target.pk, similar_target.pk))
  1537. self.orm_wrapper.clone_image_artifacts(similar_target,
  1538. image_target)
  1539. def _get_sdk_targets(self):
  1540. """
  1541. Return targets which could generate SDK artifacts, i.e.
  1542. "do_populate_sdk" and "do_populate_sdk_ext".
  1543. """
  1544. return [target for target in self.internal_state['targets'] \
  1545. if target.task in ['populate_sdk', 'populate_sdk_ext']]
  1546. def scan_sdk_artifacts(self, event):
  1547. """
  1548. Note that we have to intercept an SDKArtifactInfo event from
  1549. toaster.bbclass (via toasterui) to get hold of the SDK variables we
  1550. need to be able to scan for files accurately: this is because
  1551. variables like TOOLCHAIN_OUTPUTNAME have reset to None by the time
  1552. BuildCompleted is fired by bitbake, so we have to get those values
  1553. while the build is still in progress.
  1554. For populate_sdk_ext, this runs twice, with two different
  1555. TOOLCHAIN_OUTPUTNAME settings, each of which will capture some of the
  1556. files in the SDK output directory.
  1557. """
  1558. sdk_vars = BuildInfoHelper._get_data_from_event(event)
  1559. toolchain_outputname = sdk_vars['TOOLCHAIN_OUTPUTNAME']
  1560. # targets which might have created SDK artifacts
  1561. sdk_targets = self._get_sdk_targets()
  1562. # location of SDK artifacts
  1563. tmpdir = self.server.runCommand(['getVariable', 'TMPDIR'])[0]
  1564. sdk_dir = os.path.join(tmpdir, 'deploy', 'sdk')
  1565. # all files in the SDK directory
  1566. artifacts = []
  1567. for dir_path, _, filenames in os.walk(sdk_dir):
  1568. for filename in filenames:
  1569. full_path = os.path.join(dir_path, filename)
  1570. if not os.path.islink(full_path):
  1571. artifacts.append(full_path)
  1572. for sdk_target in sdk_targets:
  1573. # find files in the SDK directory which haven't already been
  1574. # recorded against a Target and whose basename matches
  1575. # TOOLCHAIN_OUTPUTNAME
  1576. for artifact_path in artifacts:
  1577. basename = os.path.basename(artifact_path)
  1578. toolchain_match = basename.startswith(toolchain_outputname)
  1579. # files which match the name of the target which produced them;
  1580. # for example,
  1581. # poky-glibc-x86_64-core-image-sato-i586-toolchain-ext-2.1+snapshot.sh
  1582. target_match = re.search(sdk_target.target, basename)
  1583. # targets which produce "*-nativesdk-*" files
  1584. is_ext_sdk_target = sdk_target.task in \
  1585. ['do_populate_sdk_ext', 'populate_sdk_ext']
  1586. # SDK files which don't match the target name, i.e.
  1587. # x86_64-nativesdk-libc.*
  1588. # poky-glibc-x86_64-buildtools-tarball-i586-buildtools-nativesdk-standalone-2.1+snapshot*
  1589. is_ext_sdk_file = re.search('-nativesdk-', basename)
  1590. file_from_target = (toolchain_match and target_match) or \
  1591. (is_ext_sdk_target and is_ext_sdk_file)
  1592. if file_from_target:
  1593. # don't record the file if it's already been added to this
  1594. # target
  1595. matching_files = TargetSDKFile.objects.filter(
  1596. target=sdk_target, file_name=artifact_path)
  1597. if matching_files.count() == 0:
  1598. artifact_size = os.stat(artifact_path).st_size
  1599. self.orm_wrapper.save_target_sdk_file(
  1600. sdk_target, artifact_path, artifact_size)
  1601. def clone_required_sdk_artifacts(self):
  1602. """
  1603. If an SDK target doesn't have any SDK artifacts, this means that
  1604. the postfuncs of populate_sdk or populate_sdk_ext didn't fire, which
  1605. in turn means that the targets of this build didn't generate any new
  1606. artifacts.
  1607. In this case, clone SDK artifacts for targets in the current build
  1608. from existing targets for this build.
  1609. """
  1610. sdk_targets = self._get_sdk_targets()
  1611. for sdk_target in sdk_targets:
  1612. # only clone for SDK targets which have no TargetSDKFiles yet
  1613. if sdk_target.targetsdkfile_set.all().count() == 0:
  1614. similar_target = \
  1615. self.orm_wrapper.get_similar_target_with_sdk_files(
  1616. sdk_target)
  1617. if similar_target:
  1618. logger.info('SDK artifacts for target %s cloned from ' \
  1619. 'target %s' % (sdk_target.pk, similar_target.pk))
  1620. self.orm_wrapper.clone_sdk_artifacts(similar_target,
  1621. sdk_target)
  1622. def close(self, errorcode):
  1623. self._store_build_done(errorcode)
  1624. if 'backlog' in self.internal_state:
  1625. # we save missed events in the database for the current build
  1626. tempevent = self.internal_state['backlog'].pop()
  1627. # Do not skip command line build events
  1628. self.store_log_event(tempevent,False)
  1629. if not connection.features.autocommits_when_autocommit_is_off:
  1630. transaction.set_autocommit(True)
  1631. # unset the brbe; this is to prevent subsequent command-line builds
  1632. # being incorrectly attached to the previous Toaster-triggered build;
  1633. # see https://bugzilla.yoctoproject.org/show_bug.cgi?id=9021
  1634. self.brbe = None
  1635. # unset the internal Build object to prevent it being reused for the
  1636. # next build
  1637. self.internal_state['build'] = None