restapi.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. # Copyright (C) 2016-2018 Wind River Systems, Inc.
  2. #
  3. # SPDX-License-Identifier: GPL-2.0-only
  4. #
  5. import logging
  6. import json
  7. from urllib.parse import unquote
  8. from urllib.parse import urlparse
  9. import layerindexlib
  10. import layerindexlib.plugin
  11. logger = logging.getLogger('BitBake.layerindexlib.restapi')
  12. def plugin_init(plugins):
  13. return RestApiPlugin()
  14. class RestApiPlugin(layerindexlib.plugin.IndexPlugin):
  15. def __init__(self):
  16. self.type = "restapi"
  17. def load_index(self, url, load):
  18. """
  19. Fetches layer information from a local or remote layer index.
  20. The return value is a LayerIndexObj.
  21. url is the url to the rest api of the layer index, such as:
  22. http://layers.openembedded.org/layerindex/api/
  23. Or a local file...
  24. """
  25. up = urlparse(url)
  26. if up.scheme == 'file':
  27. return self.load_index_file(up, url, load)
  28. if up.scheme == 'http' or up.scheme == 'https':
  29. return self.load_index_web(up, url, load)
  30. raise layerindexlib.plugin.LayerIndexPluginUrlError(self.type, url)
  31. def load_index_file(self, up, url, load):
  32. """
  33. Fetches layer information from a local file or directory.
  34. The return value is a LayerIndexObj.
  35. ud is the parsed url to the local file or directory.
  36. """
  37. if not os.path.exists(up.path):
  38. raise FileNotFoundError(up.path)
  39. index = layerindexlib.LayerIndexObj()
  40. index.config = {}
  41. index.config['TYPE'] = self.type
  42. index.config['URL'] = url
  43. params = self.layerindex._parse_params(up.params)
  44. if 'desc' in params:
  45. index.config['DESCRIPTION'] = unquote(params['desc'])
  46. else:
  47. index.config['DESCRIPTION'] = up.path
  48. if 'cache' in params:
  49. index.config['CACHE'] = params['cache']
  50. if 'branch' in params:
  51. branches = params['branch'].split(',')
  52. index.config['BRANCH'] = branches
  53. else:
  54. branches = ['*']
  55. def load_cache(path, index, branches=[]):
  56. logger.debug(1, 'Loading json file %s' % path)
  57. with open(path, 'rt', encoding='utf-8') as f:
  58. pindex = json.load(f)
  59. # Filter the branches on loaded files...
  60. newpBranch = []
  61. for branch in branches:
  62. if branch != '*':
  63. if 'branches' in pindex:
  64. for br in pindex['branches']:
  65. if br['name'] == branch:
  66. newpBranch.append(br)
  67. else:
  68. if 'branches' in pindex:
  69. for br in pindex['branches']:
  70. newpBranch.append(br)
  71. if newpBranch:
  72. index.add_raw_element('branches', layerindexlib.Branch, newpBranch)
  73. else:
  74. logger.debug(1, 'No matching branches (%s) in index file(s)' % branches)
  75. # No matching branches.. return nothing...
  76. return
  77. for (lName, lType) in [("layerItems", layerindexlib.LayerItem),
  78. ("layerBranches", layerindexlib.LayerBranch),
  79. ("layerDependencies", layerindexlib.LayerDependency),
  80. ("recipes", layerindexlib.Recipe),
  81. ("machines", layerindexlib.Machine),
  82. ("distros", layerindexlib.Distro)]:
  83. if lName in pindex:
  84. index.add_raw_element(lName, lType, pindex[lName])
  85. if not os.path.isdir(up.path):
  86. load_cache(up.path, index, branches)
  87. return index
  88. logger.debug(1, 'Loading from dir %s...' % (up.path))
  89. for (dirpath, _, filenames) in os.walk(up.path):
  90. for filename in filenames:
  91. if not filename.endswith('.json'):
  92. continue
  93. fpath = os.path.join(dirpath, filename)
  94. load_cache(fpath, index, branches)
  95. return index
  96. def load_index_web(self, up, url, load):
  97. """
  98. Fetches layer information from a remote layer index.
  99. The return value is a LayerIndexObj.
  100. ud is the parsed url to the rest api of the layer index, such as:
  101. http://layers.openembedded.org/layerindex/api/
  102. """
  103. def _get_json_response(apiurl=None, username=None, password=None, retry=True):
  104. assert apiurl is not None
  105. logger.debug(1, "fetching %s" % apiurl)
  106. up = urlparse(apiurl)
  107. username=up.username
  108. password=up.password
  109. # Strip username/password and params
  110. if up.port:
  111. up_stripped = up._replace(params="", netloc="%s:%s" % (up.hostname, up.port))
  112. else:
  113. up_stripped = up._replace(params="", netloc=up.hostname)
  114. res = self.layerindex._fetch_url(up_stripped.geturl(), username=username, password=password)
  115. try:
  116. parsed = json.loads(res.read().decode('utf-8'))
  117. except ConnectionResetError:
  118. if retry:
  119. logger.debug(1, "%s: Connection reset by peer. Retrying..." % url)
  120. parsed = _get_json_response(apiurl=up_stripped.geturl(), username=username, password=password, retry=False)
  121. logger.debug(1, "%s: retry successful.")
  122. else:
  123. raise LayerIndexFetchError('%s: Connection reset by peer. Is there a firewall blocking your connection?' % apiurl)
  124. return parsed
  125. index = layerindexlib.LayerIndexObj()
  126. index.config = {}
  127. index.config['TYPE'] = self.type
  128. index.config['URL'] = url
  129. params = self.layerindex._parse_params(up.params)
  130. if 'desc' in params:
  131. index.config['DESCRIPTION'] = unquote(params['desc'])
  132. else:
  133. index.config['DESCRIPTION'] = up.hostname
  134. if 'cache' in params:
  135. index.config['CACHE'] = params['cache']
  136. if 'branch' in params:
  137. branches = params['branch'].split(',')
  138. index.config['BRANCH'] = branches
  139. else:
  140. branches = ['*']
  141. try:
  142. index.apilinks = _get_json_response(apiurl=url, username=up.username, password=up.password)
  143. except Exception as e:
  144. raise layerindexlib.LayerIndexFetchError(url, e)
  145. # Local raw index set...
  146. pindex = {}
  147. # Load all the requested branches at the same time time,
  148. # a special branch of '*' means load all branches
  149. filter = ""
  150. if "*" not in branches:
  151. filter = "?filter=name:%s" % "OR".join(branches)
  152. logger.debug(1, "Loading %s from %s" % (branches, index.apilinks['branches']))
  153. # The link won't include username/password, so pull it from the original url
  154. pindex['branches'] = _get_json_response(index.apilinks['branches'] + filter,
  155. username=up.username, password=up.password)
  156. if not pindex['branches']:
  157. logger.debug(1, "No valid branches (%s) found at url %s." % (branch, url))
  158. return index
  159. index.add_raw_element("branches", layerindexlib.Branch, pindex['branches'])
  160. # Load all of the layerItems (these can not be easily filtered)
  161. logger.debug(1, "Loading %s from %s" % ('layerItems', index.apilinks['layerItems']))
  162. # The link won't include username/password, so pull it from the original url
  163. pindex['layerItems'] = _get_json_response(index.apilinks['layerItems'],
  164. username=up.username, password=up.password)
  165. if not pindex['layerItems']:
  166. logger.debug(1, "No layers were found at url %s." % (url))
  167. return index
  168. index.add_raw_element("layerItems", layerindexlib.LayerItem, pindex['layerItems'])
  169. # From this point on load the contents for each branch. Otherwise we
  170. # could run into a timeout.
  171. for branch in index.branches:
  172. filter = "?filter=branch__name:%s" % index.branches[branch].name
  173. logger.debug(1, "Loading %s from %s" % ('layerBranches', index.apilinks['layerBranches']))
  174. # The link won't include username/password, so pull it from the original url
  175. pindex['layerBranches'] = _get_json_response(index.apilinks['layerBranches'] + filter,
  176. username=up.username, password=up.password)
  177. if not pindex['layerBranches']:
  178. logger.debug(1, "No valid layer branches (%s) found at url %s." % (branches or "*", url))
  179. return index
  180. index.add_raw_element("layerBranches", layerindexlib.LayerBranch, pindex['layerBranches'])
  181. # Load the rest, they all have a similar format
  182. # Note: the layer index has a few more items, we can add them if necessary
  183. # in the future.
  184. filter = "?filter=layerbranch__branch__name:%s" % index.branches[branch].name
  185. for (lName, lType) in [("layerDependencies", layerindexlib.LayerDependency),
  186. ("recipes", layerindexlib.Recipe),
  187. ("machines", layerindexlib.Machine),
  188. ("distros", layerindexlib.Distro)]:
  189. if lName not in load:
  190. continue
  191. logger.debug(1, "Loading %s from %s" % (lName, index.apilinks[lName]))
  192. # The link won't include username/password, so pull it from the original url
  193. pindex[lName] = _get_json_response(index.apilinks[lName] + filter,
  194. username=up.username, password=up.password)
  195. index.add_raw_element(lName, lType, pindex[lName])
  196. return index
  197. def store_index(self, url, index):
  198. """
  199. Store layer information into a local file/dir.
  200. The return value is a dictionary containing API,
  201. layer, branch, dependency, recipe, machine, distro, information.
  202. ud is a parsed url to a directory or file. If the path is a
  203. directory, we will split the files into one file per layer.
  204. If the path is to a file (exists or not) the entire DB will be
  205. dumped into that one file.
  206. """
  207. up = urlparse(url)
  208. if up.scheme != 'file':
  209. raise layerindexlib.plugin.LayerIndexPluginUrlError(self.type, url)
  210. logger.debug(1, "Storing to %s..." % up.path)
  211. try:
  212. layerbranches = index.layerBranches
  213. except KeyError:
  214. logger.error('No layerBranches to write.')
  215. return
  216. def filter_item(layerbranchid, objects):
  217. filtered = []
  218. for obj in getattr(index, objects, None):
  219. try:
  220. if getattr(index, objects)[obj].layerbranch_id == layerbranchid:
  221. filtered.append(getattr(index, objects)[obj]._data)
  222. except AttributeError:
  223. logger.debug(1, 'No obj.layerbranch_id: %s' % objects)
  224. # No simple filter method, just include it...
  225. try:
  226. filtered.append(getattr(index, objects)[obj]._data)
  227. except AttributeError:
  228. logger.debug(1, 'No obj._data: %s %s' % (objects, type(obj)))
  229. filtered.append(obj)
  230. return filtered
  231. # Write out to a single file.
  232. # Filter out unnecessary items, then sort as we write for determinism
  233. if not os.path.isdir(up.path):
  234. pindex = {}
  235. pindex['branches'] = []
  236. pindex['layerItems'] = []
  237. pindex['layerBranches'] = []
  238. for layerbranchid in layerbranches:
  239. if layerbranches[layerbranchid].branch._data not in pindex['branches']:
  240. pindex['branches'].append(layerbranches[layerbranchid].branch._data)
  241. if layerbranches[layerbranchid].layer._data not in pindex['layerItems']:
  242. pindex['layerItems'].append(layerbranches[layerbranchid].layer._data)
  243. if layerbranches[layerbranchid]._data not in pindex['layerBranches']:
  244. pindex['layerBranches'].append(layerbranches[layerbranchid]._data)
  245. for entry in index._index:
  246. # Skip local items, apilinks and items already processed
  247. if entry in index.config['local'] or \
  248. entry == 'apilinks' or \
  249. entry == 'branches' or \
  250. entry == 'layerBranches' or \
  251. entry == 'layerItems':
  252. continue
  253. if entry not in pindex:
  254. pindex[entry] = []
  255. pindex[entry].extend(filter_item(layerbranchid, entry))
  256. bb.debug(1, 'Writing index to %s' % up.path)
  257. with open(up.path, 'wt') as f:
  258. json.dump(layerindexlib.sort_entry(pindex), f, indent=4)
  259. return
  260. # Write out to a directory one file per layerBranch
  261. # Prepare all layer related items, to create a minimal file.
  262. # We have to sort the entries as we write so they are deterministic
  263. for layerbranchid in layerbranches:
  264. pindex = {}
  265. for entry in index._index:
  266. # Skip local items, apilinks and items already processed
  267. if entry in index.config['local'] or \
  268. entry == 'apilinks' or \
  269. entry == 'branches' or \
  270. entry == 'layerBranches' or \
  271. entry == 'layerItems':
  272. continue
  273. pindex[entry] = filter_item(layerbranchid, entry)
  274. # Add the layer we're processing as the first one...
  275. pindex['branches'] = [layerbranches[layerbranchid].branch._data]
  276. pindex['layerItems'] = [layerbranches[layerbranchid].layer._data]
  277. pindex['layerBranches'] = [layerbranches[layerbranchid]._data]
  278. # We also need to include the layerbranch for any dependencies...
  279. for layerdep in pindex['layerDependencies']:
  280. layerdependency = layerindexlib.LayerDependency(index, layerdep)
  281. layeritem = layerdependency.dependency
  282. layerbranch = layerdependency.dependency_layerBranch
  283. # We need to avoid duplicates...
  284. if layeritem._data not in pindex['layerItems']:
  285. pindex['layerItems'].append(layeritem._data)
  286. if layerbranch._data not in pindex['layerBranches']:
  287. pindex['layerBranches'].append(layerbranch._data)
  288. # apply mirroring adjustments here....
  289. fname = index.config['DESCRIPTION'] + '__' + pindex['branches'][0]['name'] + '__' + pindex['layerItems'][0]['name']
  290. fname = fname.translate(str.maketrans('/ ', '__'))
  291. fpath = os.path.join(up.path, fname)
  292. bb.debug(1, 'Writing index to %s' % fpath + '.json')
  293. with open(fpath + '.json', 'wt') as f:
  294. json.dump(layerindexlib.sort_entry(pindex), f, indent=4)