buildinfohelper.py 85 KB

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