cooker.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # Copyright (C) 2016-2018 Wind River Systems, Inc.
  2. #
  3. # SPDX-License-Identifier: GPL-2.0-only
  4. #
  5. import logging
  6. import os
  7. from collections import defaultdict
  8. from urllib.parse import unquote, urlparse
  9. import layerindexlib
  10. import layerindexlib.plugin
  11. logger = logging.getLogger('BitBake.layerindexlib.cooker')
  12. import bb.utils
  13. def plugin_init(plugins):
  14. return CookerPlugin()
  15. class CookerPlugin(layerindexlib.plugin.IndexPlugin):
  16. def __init__(self):
  17. self.type = "cooker"
  18. self.server_connection = None
  19. self.ui_module = None
  20. self.server = None
  21. def _run_command(self, command, path, default=None):
  22. try:
  23. result, _ = bb.process.run(command, cwd=path)
  24. result = result.strip()
  25. except bb.process.ExecutionError:
  26. result = default
  27. return result
  28. def _handle_git_remote(self, remote):
  29. if "://" not in remote:
  30. if ':' in remote:
  31. # This is assumed to be ssh
  32. remote = "ssh://" + remote
  33. else:
  34. # This is assumed to be a file path
  35. remote = "file://" + remote
  36. return remote
  37. def _get_bitbake_info(self):
  38. """Return a tuple of bitbake information"""
  39. # Our path SHOULD be .../bitbake/lib/layerindex/cooker.py
  40. bb_path = os.path.dirname(__file__) # .../bitbake/lib/layerindex/cooker.py
  41. bb_path = os.path.dirname(bb_path) # .../bitbake/lib/layerindex
  42. bb_path = os.path.dirname(bb_path) # .../bitbake/lib
  43. bb_path = os.path.dirname(bb_path) # .../bitbake
  44. bb_path = self._run_command('git rev-parse --show-toplevel', os.path.dirname(__file__), default=bb_path)
  45. bb_branch = self._run_command('git rev-parse --abbrev-ref HEAD', bb_path, default="<unknown>")
  46. bb_rev = self._run_command('git rev-parse HEAD', bb_path, default="<unknown>")
  47. for remotes in self._run_command('git remote -v', bb_path, default="").split("\n"):
  48. remote = remotes.split("\t")[1].split(" ")[0]
  49. if "(fetch)" == remotes.split("\t")[1].split(" ")[1]:
  50. bb_remote = self._handle_git_remote(remote)
  51. break
  52. else:
  53. bb_remote = self._handle_git_remote(bb_path)
  54. return (bb_remote, bb_branch, bb_rev, bb_path)
  55. def _load_bblayers(self, branches=None):
  56. """Load the BBLAYERS and related collection information"""
  57. d = self.layerindex.data
  58. if not branches:
  59. raise layerindexlib.LayerIndexFetchError("No branches specified for _load_bblayers!")
  60. index = layerindexlib.LayerIndexObj()
  61. branchId = 0
  62. index.branches = {}
  63. layerItemId = 0
  64. index.layerItems = {}
  65. layerBranchId = 0
  66. index.layerBranches = {}
  67. bblayers = d.getVar('BBLAYERS').split()
  68. if not bblayers:
  69. # It's blank! Nothing to process...
  70. return index
  71. collections = d.getVar('BBFILE_COLLECTIONS')
  72. layerconfs = d.varhistory.get_variable_items_files('BBFILE_COLLECTIONS')
  73. bbfile_collections = {layer: os.path.dirname(os.path.dirname(path)) for layer, path in layerconfs.items()}
  74. (_, bb_branch, _, _) = self._get_bitbake_info()
  75. for branch in branches:
  76. branchId += 1
  77. index.branches[branchId] = layerindexlib.Branch(index, None)
  78. index.branches[branchId].define_data(branchId, branch, bb_branch)
  79. for entry in collections.split():
  80. layerpath = entry
  81. if entry in bbfile_collections:
  82. layerpath = bbfile_collections[entry]
  83. layername = d.getVar('BBLAYERS_LAYERINDEX_NAME_%s' % entry) or os.path.basename(layerpath)
  84. layerversion = d.getVar('LAYERVERSION_%s' % entry) or ""
  85. layerurl = self._handle_git_remote(layerpath)
  86. layersubdir = ""
  87. layerrev = "<unknown>"
  88. layerbranch = "<unknown>"
  89. if os.path.isdir(layerpath):
  90. layerbasepath = self._run_command('git rev-parse --show-toplevel', layerpath, default=layerpath)
  91. if os.path.abspath(layerpath) != os.path.abspath(layerbasepath):
  92. layersubdir = os.path.abspath(layerpath)[len(layerbasepath) + 1:]
  93. layerbranch = self._run_command('git rev-parse --abbrev-ref HEAD', layerpath, default="<unknown>")
  94. layerrev = self._run_command('git rev-parse HEAD', layerpath, default="<unknown>")
  95. for remotes in self._run_command('git remote -v', layerpath, default="").split("\n"):
  96. if not remotes:
  97. layerurl = self._handle_git_remote(layerpath)
  98. else:
  99. remote = remotes.split("\t")[1].split(" ")[0]
  100. if "(fetch)" == remotes.split("\t")[1].split(" ")[1]:
  101. layerurl = self._handle_git_remote(remote)
  102. break
  103. layerItemId += 1
  104. index.layerItems[layerItemId] = layerindexlib.LayerItem(index, None)
  105. index.layerItems[layerItemId].define_data(layerItemId, layername, description=layerpath, vcs_url=layerurl)
  106. for branchId in index.branches:
  107. layerBranchId += 1
  108. index.layerBranches[layerBranchId] = layerindexlib.LayerBranch(index, None)
  109. index.layerBranches[layerBranchId].define_data(layerBranchId, entry, layerversion, layerItemId, branchId,
  110. vcs_subdir=layersubdir, vcs_last_rev=layerrev, actual_branch=layerbranch)
  111. return index
  112. def load_index(self, url, load):
  113. """
  114. Fetches layer information from a build configuration.
  115. The return value is a dictionary containing API,
  116. layer, branch, dependency, recipe, machine, distro, information.
  117. url type should be 'cooker'.
  118. url path is ignored
  119. """
  120. up = urlparse(url)
  121. if up.scheme != 'cooker':
  122. raise layerindexlib.plugin.LayerIndexPluginUrlError(self.type, url)
  123. d = self.layerindex.data
  124. params = self.layerindex._parse_params(up.params)
  125. # Only reason to pass a branch is to emulate them...
  126. if 'branch' in params:
  127. branches = params['branch'].split(',')
  128. else:
  129. branches = ['HEAD']
  130. logger.debug(1, "Loading cooker data branches %s" % branches)
  131. index = self._load_bblayers(branches=branches)
  132. index.config = {}
  133. index.config['TYPE'] = self.type
  134. index.config['URL'] = url
  135. if 'desc' in params:
  136. index.config['DESCRIPTION'] = unquote(params['desc'])
  137. else:
  138. index.config['DESCRIPTION'] = 'local'
  139. if 'cache' in params:
  140. index.config['CACHE'] = params['cache']
  141. index.config['BRANCH'] = branches
  142. # ("layerDependencies", layerindexlib.LayerDependency)
  143. layerDependencyId = 0
  144. if "layerDependencies" in load:
  145. index.layerDependencies = {}
  146. for layerBranchId in index.layerBranches:
  147. branchName = index.layerBranches[layerBranchId].branch.name
  148. collection = index.layerBranches[layerBranchId].collection
  149. def add_dependency(layerDependencyId, index, deps, required):
  150. try:
  151. depDict = bb.utils.explode_dep_versions2(deps)
  152. except bb.utils.VersionStringException as vse:
  153. bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (collection, str(vse)))
  154. for dep, oplist in list(depDict.items()):
  155. # We need to search ourselves, so use the _ version...
  156. depLayerBranch = index.find_collection(dep, branches=[branchName])
  157. if not depLayerBranch:
  158. # Missing dependency?!
  159. logger.error('Missing dependency %s (%s)' % (dep, branchName))
  160. continue
  161. # We assume that the oplist matches...
  162. layerDependencyId += 1
  163. layerDependency = layerindexlib.LayerDependency(index, None)
  164. layerDependency.define_data(id=layerDependencyId,
  165. required=required, layerbranch=layerBranchId,
  166. dependency=depLayerBranch.layer_id)
  167. logger.debug(1, '%s requires %s' % (layerDependency.layer.name, layerDependency.dependency.name))
  168. index.add_element("layerDependencies", [layerDependency])
  169. return layerDependencyId
  170. deps = d.getVar("LAYERDEPENDS_%s" % collection)
  171. if deps:
  172. layerDependencyId = add_dependency(layerDependencyId, index, deps, True)
  173. deps = d.getVar("LAYERRECOMMENDS_%s" % collection)
  174. if deps:
  175. layerDependencyId = add_dependency(layerDependencyId, index, deps, False)
  176. # Need to load recipes here (requires cooker access)
  177. recipeId = 0
  178. ## TODO: NOT IMPLEMENTED
  179. # The code following this is an example of what needs to be
  180. # implemented. However, it does not work as-is.
  181. if False and 'recipes' in load:
  182. index.recipes = {}
  183. ret = self.ui_module.main(self.server_connection.connection, self.server_connection.events, config_params)
  184. all_versions = self._run_command('allProviders')
  185. all_versions_list = defaultdict(list, all_versions)
  186. for pn in all_versions_list:
  187. for ((pe, pv, pr), fpath) in all_versions_list[pn]:
  188. realfn = bb.cache.virtualfn2realfn(fpath)
  189. filepath = os.path.dirname(realfn[0])
  190. filename = os.path.basename(realfn[0])
  191. # This is all HORRIBLY slow, and likely unnecessary
  192. #dscon = self._run_command('parseRecipeFile', fpath, False, [])
  193. #connector = myDataStoreConnector(self, dscon.dsindex)
  194. #recipe_data = bb.data.init()
  195. #recipe_data.setVar('_remote_data', connector)
  196. #summary = recipe_data.getVar('SUMMARY')
  197. #description = recipe_data.getVar('DESCRIPTION')
  198. #section = recipe_data.getVar('SECTION')
  199. #license = recipe_data.getVar('LICENSE')
  200. #homepage = recipe_data.getVar('HOMEPAGE')
  201. #bugtracker = recipe_data.getVar('BUGTRACKER')
  202. #provides = recipe_data.getVar('PROVIDES')
  203. layer = bb.utils.get_file_layer(realfn[0], self.config_data)
  204. depBranchId = collection[layer]
  205. recipeId += 1
  206. recipe = layerindexlib.Recipe(index, None)
  207. recipe.define_data(id=recipeId,
  208. filename=filename, filepath=filepath,
  209. pn=pn, pv=pv,
  210. summary=pn, description=pn, section='?',
  211. license='?', homepage='?', bugtracker='?',
  212. provides='?', bbclassextend='?', inherits='?',
  213. blacklisted='?', layerbranch=depBranchId)
  214. index = addElement("recipes", [recipe], index)
  215. # ("machines", layerindexlib.Machine)
  216. machineId = 0
  217. if 'machines' in load:
  218. index.machines = {}
  219. for layerBranchId in index.layerBranches:
  220. # load_bblayers uses the description to cache the actual path...
  221. machine_path = index.layerBranches[layerBranchId].layer.description
  222. machine_path = os.path.join(machine_path, 'conf/machine')
  223. if os.path.isdir(machine_path):
  224. for (dirpath, _, filenames) in os.walk(machine_path):
  225. # Ignore subdirs...
  226. if not dirpath.endswith('conf/machine'):
  227. continue
  228. for fname in filenames:
  229. if fname.endswith('.conf'):
  230. machineId += 1
  231. machine = layerindexlib.Machine(index, None)
  232. machine.define_data(id=machineId, name=fname[:-5],
  233. description=fname[:-5],
  234. layerbranch=index.layerBranches[layerBranchId])
  235. index.add_element("machines", [machine])
  236. # ("distros", layerindexlib.Distro)
  237. distroId = 0
  238. if 'distros' in load:
  239. index.distros = {}
  240. for layerBranchId in index.layerBranches:
  241. # load_bblayers uses the description to cache the actual path...
  242. distro_path = index.layerBranches[layerBranchId].layer.description
  243. distro_path = os.path.join(distro_path, 'conf/distro')
  244. if os.path.isdir(distro_path):
  245. for (dirpath, _, filenames) in os.walk(distro_path):
  246. # Ignore subdirs...
  247. if not dirpath.endswith('conf/distro'):
  248. continue
  249. for fname in filenames:
  250. if fname.endswith('.conf'):
  251. distroId += 1
  252. distro = layerindexlib.Distro(index, None)
  253. distro.define_data(id=distroId, name=fname[:-5],
  254. description=fname[:-5],
  255. layerbranch=index.layerBranches[layerBranchId])
  256. index.add_element("distros", [distro])
  257. return index