cooker.py 14 KB

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