cooker.py 14 KB

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