restapi.py 15 KB

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