__init__.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. # Copyright (C) 2016-2018 Wind River Systems, Inc.
  2. #
  3. # SPDX-License-Identifier: GPL-2.0-only
  4. #
  5. import datetime
  6. import logging
  7. import imp
  8. import os
  9. from collections import OrderedDict
  10. from layerindexlib.plugin import LayerIndexPluginUrlError
  11. logger = logging.getLogger('BitBake.layerindexlib')
  12. # Exceptions
  13. class LayerIndexException(Exception):
  14. '''LayerIndex Generic Exception'''
  15. def __init__(self, message):
  16. self.msg = message
  17. Exception.__init__(self, message)
  18. def __str__(self):
  19. return self.msg
  20. class LayerIndexUrlError(LayerIndexException):
  21. '''Exception raised when unable to access a URL for some reason'''
  22. def __init__(self, url, message=""):
  23. if message:
  24. msg = "Unable to access layerindex url %s: %s" % (url, message)
  25. else:
  26. msg = "Unable to access layerindex url %s" % url
  27. self.url = url
  28. LayerIndexException.__init__(self, msg)
  29. class LayerIndexFetchError(LayerIndexException):
  30. '''General layerindex fetcher exception when something fails'''
  31. def __init__(self, url, message=""):
  32. if message:
  33. msg = "Unable to fetch layerindex url %s: %s" % (url, message)
  34. else:
  35. msg = "Unable to fetch layerindex url %s" % url
  36. self.url = url
  37. LayerIndexException.__init__(self, msg)
  38. # Interface to the overall layerindex system
  39. # the layer may contain one or more individual indexes
  40. class LayerIndex():
  41. def __init__(self, d):
  42. if not d:
  43. raise LayerIndexException("Must be initialized with bb.data.")
  44. self.data = d
  45. # List of LayerIndexObj
  46. self.indexes = []
  47. self.plugins = []
  48. import bb.utils
  49. bb.utils.load_plugins(logger, self.plugins, os.path.dirname(__file__))
  50. for plugin in self.plugins:
  51. if hasattr(plugin, 'init'):
  52. plugin.init(self)
  53. def __add__(self, other):
  54. newIndex = LayerIndex(self.data)
  55. if self.__class__ != newIndex.__class__ or \
  56. other.__class__ != newIndex.__class__:
  57. raise TypeError("Can not add different types.")
  58. for indexEnt in self.indexes:
  59. newIndex.indexes.append(indexEnt)
  60. for indexEnt in other.indexes:
  61. newIndex.indexes.append(indexEnt)
  62. return newIndex
  63. def _parse_params(self, params):
  64. '''Take a parameter list, return a dictionary of parameters.
  65. Expected to be called from the data of urllib.parse.urlparse(url).params
  66. If there are two conflicting parameters, last in wins...
  67. '''
  68. param_dict = {}
  69. for param in params.split(';'):
  70. if not param:
  71. continue
  72. item = param.split('=', 1)
  73. logger.debug(1, item)
  74. param_dict[item[0]] = item[1]
  75. return param_dict
  76. def _fetch_url(self, url, username=None, password=None, debuglevel=0):
  77. '''Fetch data from a specific URL.
  78. Fetch something from a specific URL. This is specifically designed to
  79. fetch data from a layerindex-web instance, but may be useful for other
  80. raw fetch actions.
  81. It is not designed to be used to fetch recipe sources or similar. the
  82. regular fetcher class should used for that.
  83. It is the responsibility of the caller to check BB_NO_NETWORK and related
  84. BB_ALLOWED_NETWORKS.
  85. '''
  86. if not url:
  87. raise LayerIndexUrlError(url, "empty url")
  88. import urllib
  89. from urllib.request import urlopen, Request
  90. from urllib.parse import urlparse
  91. up = urlparse(url)
  92. if username:
  93. logger.debug(1, "Configuring authentication for %s..." % url)
  94. password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  95. password_mgr.add_password(None, "%s://%s" % (up.scheme, up.netloc), username, password)
  96. handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
  97. opener = urllib.request.build_opener(handler, urllib.request.HTTPSHandler(debuglevel=debuglevel))
  98. else:
  99. opener = urllib.request.build_opener(urllib.request.HTTPSHandler(debuglevel=debuglevel))
  100. urllib.request.install_opener(opener)
  101. logger.debug(1, "Fetching %s (%s)..." % (url, ["without authentication", "with authentication"][bool(username)]))
  102. try:
  103. res = urlopen(Request(url, headers={'User-Agent': 'Mozilla/5.0 (bitbake/lib/layerindex)'}, unverifiable=True))
  104. except urllib.error.HTTPError as e:
  105. logger.debug(1, "HTTP Error: %s: %s" % (e.code, e.reason))
  106. logger.debug(1, " Requested: %s" % (url))
  107. logger.debug(1, " Actual: %s" % (e.geturl()))
  108. if e.code == 404:
  109. logger.debug(1, "Request not found.")
  110. raise LayerIndexFetchError(url, e)
  111. else:
  112. logger.debug(1, "Headers:\n%s" % (e.headers))
  113. raise LayerIndexFetchError(url, e)
  114. except OSError as e:
  115. error = 0
  116. reason = ""
  117. # Process base OSError first...
  118. if hasattr(e, 'errno'):
  119. error = e.errno
  120. reason = e.strerror
  121. # Process gaierror (socket error) subclass if available.
  122. if hasattr(e, 'reason') and hasattr(e.reason, 'errno') and hasattr(e.reason, 'strerror'):
  123. error = e.reason.errno
  124. reason = e.reason.strerror
  125. if error == -2:
  126. raise LayerIndexFetchError(url, "%s: %s" % (e, reason))
  127. if error and error != 0:
  128. raise LayerIndexFetchError(url, "Unexpected exception: [Error %s] %s" % (error, reason))
  129. else:
  130. raise LayerIndexFetchError(url, "Unable to fetch OSError exception: %s" % e)
  131. finally:
  132. logger.debug(1, "...fetching %s (%s), done." % (url, ["without authentication", "with authentication"][bool(username)]))
  133. return res
  134. def load_layerindex(self, indexURI, load=['layerDependencies', 'recipes', 'machines', 'distros'], reload=False):
  135. '''Load the layerindex.
  136. indexURI - An index to load. (Use multiple calls to load multiple indexes)
  137. reload - If reload is True, then any previously loaded indexes will be forgotten.
  138. load - List of elements to load. Default loads all items.
  139. Note: plugs may ignore this.
  140. The format of the indexURI:
  141. <url>;branch=<branch>;cache=<cache>;desc=<description>
  142. Note: the 'branch' parameter if set can select multiple branches by using
  143. comma, such as 'branch=master,morty,pyro'. However, many operations only look
  144. at the -first- branch specified!
  145. The cache value may be undefined, in this case a network failure will
  146. result in an error, otherwise the system will look for a file of the cache
  147. name and load that instead.
  148. For example:
  149. http://layers.openembedded.org/layerindex/api/;branch=master;desc=OpenEmbedded%20Layer%20Index
  150. cooker://
  151. '''
  152. if reload:
  153. self.indexes = []
  154. logger.debug(1, 'Loading: %s' % indexURI)
  155. if not self.plugins:
  156. raise LayerIndexException("No LayerIndex Plugins available")
  157. for plugin in self.plugins:
  158. # Check if the plugin was initialized
  159. logger.debug(1, 'Trying %s' % plugin.__class__)
  160. if not hasattr(plugin, 'type') or not plugin.type:
  161. continue
  162. try:
  163. # TODO: Implement 'cache', for when the network is not available
  164. indexEnt = plugin.load_index(indexURI, load)
  165. break
  166. except LayerIndexPluginUrlError as e:
  167. logger.debug(1, "%s doesn't support %s" % (plugin.type, e.url))
  168. except NotImplementedError:
  169. pass
  170. else:
  171. logger.debug(1, "No plugins support %s" % indexURI)
  172. raise LayerIndexException("No plugins support %s" % indexURI)
  173. # Mark CONFIG data as something we've added...
  174. indexEnt.config['local'] = []
  175. indexEnt.config['local'].append('config')
  176. # No longer permit changes..
  177. indexEnt.lockData()
  178. self.indexes.append(indexEnt)
  179. def store_layerindex(self, indexURI, index=None):
  180. '''Store one layerindex
  181. Typically this will be used to create a local cache file of a remote index.
  182. file://<path>;branch=<branch>
  183. We can write out in either the restapi or django formats. The split option
  184. will write out the individual elements split by layer and related components.
  185. '''
  186. if not index:
  187. logger.warning('No index to write, nothing to do.')
  188. return
  189. if not self.plugins:
  190. raise LayerIndexException("No LayerIndex Plugins available")
  191. for plugin in self.plugins:
  192. # Check if the plugin was initialized
  193. logger.debug(1, 'Trying %s' % plugin.__class__)
  194. if not hasattr(plugin, 'type') or not plugin.type:
  195. continue
  196. try:
  197. plugin.store_index(indexURI, index)
  198. break
  199. except LayerIndexPluginUrlError as e:
  200. logger.debug(1, "%s doesn't support %s" % (plugin.type, e.url))
  201. except NotImplementedError:
  202. logger.debug(1, "Store not implemented in %s" % plugin.type)
  203. pass
  204. else:
  205. logger.debug(1, "No plugins support %s" % indexURI)
  206. raise LayerIndexException("No plugins support %s" % indexURI)
  207. def is_empty(self):
  208. '''Return True or False if the index has any usable data.
  209. We check the indexes entries to see if they have a branch set, as well as
  210. layerBranches set. If not, they are effectively blank.'''
  211. found = False
  212. for index in self.indexes:
  213. if index.__bool__():
  214. found = True
  215. break
  216. return not found
  217. def find_vcs_url(self, vcs_url, branch=None):
  218. '''Return the first layerBranch with the given vcs_url
  219. If a branch has not been specified, we will iterate over the branches in
  220. the default configuration until the first vcs_url/branch match.'''
  221. for index in self.indexes:
  222. logger.debug(1, ' searching %s' % index.config['DESCRIPTION'])
  223. layerBranch = index.find_vcs_url(vcs_url, [branch])
  224. if layerBranch:
  225. return layerBranch
  226. return None
  227. def find_collection(self, collection, version=None, branch=None):
  228. '''Return the first layerBranch with the given collection name
  229. If a branch has not been specified, we will iterate over the branches in
  230. the default configuration until the first collection/branch match.'''
  231. logger.debug(1, 'find_collection: %s (%s) %s' % (collection, version, branch))
  232. if branch:
  233. branches = [branch]
  234. else:
  235. branches = None
  236. for index in self.indexes:
  237. logger.debug(1, ' searching %s' % index.config['DESCRIPTION'])
  238. layerBranch = index.find_collection(collection, version, branches)
  239. if layerBranch:
  240. return layerBranch
  241. else:
  242. logger.debug(1, 'Collection %s (%s) not found for branch (%s)' % (collection, version, branch))
  243. return None
  244. def find_layerbranch(self, name, branch=None):
  245. '''Return the layerBranch item for a given name and branch
  246. If a branch has not been specified, we will iterate over the branches in
  247. the default configuration until the first name/branch match.'''
  248. if branch:
  249. branches = [branch]
  250. else:
  251. branches = None
  252. for index in self.indexes:
  253. layerBranch = index.find_layerbranch(name, branches)
  254. if layerBranch:
  255. return layerBranch
  256. return None
  257. def find_dependencies(self, names=None, layerbranches=None, ignores=None):
  258. '''Return a tuple of all dependencies and valid items for the list of (layer) names
  259. The dependency scanning happens depth-first. The returned
  260. dependencies should be in the best order to define bblayers.
  261. names - list of layer names (searching layerItems)
  262. branches - when specified (with names) only this list of branches are evaluated
  263. layerbranches - list of layerbranches to resolve dependencies
  264. ignores - list of layer names to ignore
  265. return: (dependencies, invalid)
  266. dependencies[LayerItem.name] = [ LayerBranch, LayerDependency1, LayerDependency2, ... ]
  267. invalid = [ LayerItem.name1, LayerItem.name2, ... ]
  268. '''
  269. invalid = []
  270. # Convert name/branch to layerbranches
  271. if layerbranches is None:
  272. layerbranches = []
  273. for name in names:
  274. if ignores and name in ignores:
  275. continue
  276. for index in self.indexes:
  277. layerbranch = index.find_layerbranch(name)
  278. if not layerbranch:
  279. # Not in this index, hopefully it's in another...
  280. continue
  281. layerbranches.append(layerbranch)
  282. break
  283. else:
  284. invalid.append(name)
  285. def _resolve_dependencies(layerbranches, ignores, dependencies, invalid, processed=None):
  286. for layerbranch in layerbranches:
  287. if ignores and layerbranch.layer.name in ignores:
  288. continue
  289. # Get a list of dependencies and then recursively process them
  290. for layerdependency in layerbranch.index.layerDependencies_layerBranchId[layerbranch.id]:
  291. deplayerbranch = layerdependency.dependency_layerBranch
  292. if ignores and deplayerbranch.layer.name in ignores:
  293. continue
  294. # Since this is depth first, we need to know what we're currently processing
  295. # in order to avoid infinite recursion on a loop.
  296. if processed and deplayerbranch.layer.name in processed:
  297. # We have found a recursion...
  298. logger.warning('Circular layer dependency found: %s -> %s' % (processed, deplayerbranch.layer.name))
  299. continue
  300. # This little block is why we can't re-use the LayerIndexObj version,
  301. # we must be able to satisfy each dependencies across layer indexes and
  302. # use the layer index order for priority. (r stands for replacement below)
  303. # If this is the primary index, we can fast path and skip this
  304. if deplayerbranch.index != self.indexes[0]:
  305. # Is there an entry in a prior index for this collection/version?
  306. rdeplayerbranch = self.find_collection(
  307. collection=deplayerbranch.collection,
  308. version=deplayerbranch.version
  309. )
  310. if rdeplayerbranch != deplayerbranch:
  311. logger.debug(1, 'Replaced %s:%s:%s with %s:%s:%s' % \
  312. (deplayerbranch.index.config['DESCRIPTION'],
  313. deplayerbranch.branch.name,
  314. deplayerbranch.layer.name,
  315. rdeplayerbranch.index.config['DESCRIPTION'],
  316. rdeplayerbranch.branch.name,
  317. rdeplayerbranch.layer.name))
  318. deplayerbranch = rdeplayerbranch
  319. # New dependency, we need to resolve it now... depth-first
  320. if deplayerbranch.layer.name not in dependencies:
  321. # Avoid recursion on this branch.
  322. # We copy so we don't end up polluting the depth-first branch with other
  323. # branches. Duplication between individual branches IS expected and
  324. # handled by 'dependencies' processing.
  325. if not processed:
  326. local_processed = []
  327. else:
  328. local_processed = processed.copy()
  329. local_processed.append(deplayerbranch.layer.name)
  330. (dependencies, invalid) = _resolve_dependencies([deplayerbranch], ignores, dependencies, invalid, local_processed)
  331. if deplayerbranch.layer.name not in dependencies:
  332. dependencies[deplayerbranch.layer.name] = [deplayerbranch, layerdependency]
  333. else:
  334. if layerdependency not in dependencies[deplayerbranch.layer.name]:
  335. dependencies[deplayerbranch.layer.name].append(layerdependency)
  336. return (dependencies, invalid)
  337. # OK, resolve this one...
  338. dependencies = OrderedDict()
  339. (dependencies, invalid) = _resolve_dependencies(layerbranches, ignores, dependencies, invalid)
  340. for layerbranch in layerbranches:
  341. if layerbranch.layer.name not in dependencies:
  342. dependencies[layerbranch.layer.name] = [layerbranch]
  343. return (dependencies, invalid)
  344. def list_obj(self, object):
  345. '''Print via the plain logger object information
  346. This function is used to implement debugging and provide the user info.
  347. '''
  348. for lix in self.indexes:
  349. if not hasattr(lix, object):
  350. continue
  351. logger.plain ('')
  352. logger.plain ('Index: %s' % lix.config['DESCRIPTION'])
  353. output = []
  354. if object == 'branches':
  355. logger.plain ('%s %s %s' % ('{:26}'.format('branch'), '{:34}'.format('description'), '{:22}'.format('bitbake branch')))
  356. logger.plain ('{:-^80}'.format(""))
  357. for branchid in lix.branches:
  358. output.append('%s %s %s' % (
  359. '{:26}'.format(lix.branches[branchid].name),
  360. '{:34}'.format(lix.branches[branchid].short_description),
  361. '{:22}'.format(lix.branches[branchid].bitbake_branch)
  362. ))
  363. for line in sorted(output):
  364. logger.plain (line)
  365. continue
  366. if object == 'layerItems':
  367. logger.plain ('%s %s' % ('{:26}'.format('layer'), '{:34}'.format('description')))
  368. logger.plain ('{:-^80}'.format(""))
  369. for layerid in lix.layerItems:
  370. output.append('%s %s' % (
  371. '{:26}'.format(lix.layerItems[layerid].name),
  372. '{:34}'.format(lix.layerItems[layerid].summary)
  373. ))
  374. for line in sorted(output):
  375. logger.plain (line)
  376. continue
  377. if object == 'layerBranches':
  378. logger.plain ('%s %s %s' % ('{:26}'.format('layer'), '{:34}'.format('description'), '{:19}'.format('collection:version')))
  379. logger.plain ('{:-^80}'.format(""))
  380. for layerbranchid in lix.layerBranches:
  381. output.append('%s %s %s' % (
  382. '{:26}'.format(lix.layerBranches[layerbranchid].layer.name),
  383. '{:34}'.format(lix.layerBranches[layerbranchid].layer.summary),
  384. '{:19}'.format("%s:%s" %
  385. (lix.layerBranches[layerbranchid].collection,
  386. lix.layerBranches[layerbranchid].version)
  387. )
  388. ))
  389. for line in sorted(output):
  390. logger.plain (line)
  391. continue
  392. if object == 'layerDependencies':
  393. logger.plain ('%s %s %s %s' % ('{:19}'.format('branch'), '{:26}'.format('layer'), '{:11}'.format('dependency'), '{:26}'.format('layer')))
  394. logger.plain ('{:-^80}'.format(""))
  395. for layerDependency in lix.layerDependencies:
  396. if not lix.layerDependencies[layerDependency].dependency_layerBranch:
  397. continue
  398. output.append('%s %s %s %s' % (
  399. '{:19}'.format(lix.layerDependencies[layerDependency].layerbranch.branch.name),
  400. '{:26}'.format(lix.layerDependencies[layerDependency].layerbranch.layer.name),
  401. '{:11}'.format('requires' if lix.layerDependencies[layerDependency].required else 'recommends'),
  402. '{:26}'.format(lix.layerDependencies[layerDependency].dependency_layerBranch.layer.name)
  403. ))
  404. for line in sorted(output):
  405. logger.plain (line)
  406. continue
  407. if object == 'recipes':
  408. logger.plain ('%s %s %s' % ('{:20}'.format('recipe'), '{:10}'.format('version'), 'layer'))
  409. logger.plain ('{:-^80}'.format(""))
  410. output = []
  411. for recipe in lix.recipes:
  412. output.append('%s %s %s' % (
  413. '{:30}'.format(lix.recipes[recipe].pn),
  414. '{:30}'.format(lix.recipes[recipe].pv),
  415. lix.recipes[recipe].layer.name
  416. ))
  417. for line in sorted(output):
  418. logger.plain (line)
  419. continue
  420. if object == 'machines':
  421. logger.plain ('%s %s %s' % ('{:24}'.format('machine'), '{:34}'.format('description'), '{:19}'.format('layer')))
  422. logger.plain ('{:-^80}'.format(""))
  423. for machine in lix.machines:
  424. output.append('%s %s %s' % (
  425. '{:24}'.format(lix.machines[machine].name),
  426. '{:34}'.format(lix.machines[machine].description)[:34],
  427. '{:19}'.format(lix.machines[machine].layerbranch.layer.name)
  428. ))
  429. for line in sorted(output):
  430. logger.plain (line)
  431. continue
  432. if object == 'distros':
  433. logger.plain ('%s %s %s' % ('{:24}'.format('distro'), '{:34}'.format('description'), '{:19}'.format('layer')))
  434. logger.plain ('{:-^80}'.format(""))
  435. for distro in lix.distros:
  436. output.append('%s %s %s' % (
  437. '{:24}'.format(lix.distros[distro].name),
  438. '{:34}'.format(lix.distros[distro].description)[:34],
  439. '{:19}'.format(lix.distros[distro].layerbranch.layer.name)
  440. ))
  441. for line in sorted(output):
  442. logger.plain (line)
  443. continue
  444. logger.plain ('')
  445. # This class holds a single layer index instance
  446. # The LayerIndexObj is made up of dictionary of elements, such as:
  447. # index['config'] - configuration data for this index
  448. # index['branches'] - dictionary of Branch objects, by id number
  449. # index['layerItems'] - dictionary of layerItem objects, by id number
  450. # ...etc... (See: http://layers.openembedded.org/layerindex/api/)
  451. #
  452. # The class needs to manage the 'index' entries and allow easily adding
  453. # of new items, as well as simply loading of the items.
  454. class LayerIndexObj():
  455. def __init__(self):
  456. super().__setattr__('_index', {})
  457. super().__setattr__('_lock', False)
  458. def __bool__(self):
  459. '''False if the index is effectively empty
  460. We check the index to see if it has a branch set, as well as
  461. layerbranches set. If not, it is effectively blank.'''
  462. if not bool(self._index):
  463. return False
  464. try:
  465. if self.branches and self.layerBranches:
  466. return True
  467. except AttributeError:
  468. pass
  469. return False
  470. def __getattr__(self, name):
  471. if name.startswith('_'):
  472. return super().__getattribute__(name)
  473. if name not in self._index:
  474. raise AttributeError('%s not in index datastore' % name)
  475. return self._index[name]
  476. def __setattr__(self, name, value):
  477. if self.isLocked():
  478. raise TypeError("Can not set attribute '%s': index is locked" % name)
  479. if name.startswith('_'):
  480. super().__setattr__(name, value)
  481. return
  482. self._index[name] = value
  483. def __delattr__(self, name):
  484. if self.isLocked():
  485. raise TypeError("Can not delete attribute '%s': index is locked" % name)
  486. if name.startswith('_'):
  487. super().__delattr__(name)
  488. self._index.pop(name)
  489. def lockData(self):
  490. '''Lock data object (make it readonly)'''
  491. super().__setattr__("_lock", True)
  492. def unlockData(self):
  493. '''unlock data object (make it readonly)'''
  494. super().__setattr__("_lock", False)
  495. # When the data is unlocked, we have to clear the caches, as
  496. # modification is allowed!
  497. del(self._layerBranches_layerId_branchId)
  498. del(self._layerDependencies_layerBranchId)
  499. del(self._layerBranches_vcsUrl)
  500. def isLocked(self):
  501. '''Is this object locked (readonly)?'''
  502. return self._lock
  503. def add_element(self, indexname, objs):
  504. '''Add a layer index object to index.<indexname>'''
  505. if indexname not in self._index:
  506. self._index[indexname] = {}
  507. for obj in objs:
  508. if obj.id in self._index[indexname]:
  509. if self._index[indexname][obj.id] == obj:
  510. continue
  511. raise LayerIndexException('Conflict adding object %s(%s) to index' % (indexname, obj.id))
  512. self._index[indexname][obj.id] = obj
  513. def add_raw_element(self, indexname, objtype, rawobjs):
  514. '''Convert a raw layer index data item to a layer index item object and add to the index'''
  515. objs = []
  516. for entry in rawobjs:
  517. objs.append(objtype(self, entry))
  518. self.add_element(indexname, objs)
  519. # Quick lookup table for searching layerId and branchID combos
  520. @property
  521. def layerBranches_layerId_branchId(self):
  522. def createCache(self):
  523. cache = {}
  524. for layerbranchid in self.layerBranches:
  525. layerbranch = self.layerBranches[layerbranchid]
  526. cache["%s:%s" % (layerbranch.layer_id, layerbranch.branch_id)] = layerbranch
  527. return cache
  528. if self.isLocked():
  529. cache = getattr(self, '_layerBranches_layerId_branchId', None)
  530. else:
  531. cache = None
  532. if not cache:
  533. cache = createCache(self)
  534. if self.isLocked():
  535. super().__setattr__('_layerBranches_layerId_branchId', cache)
  536. return cache
  537. # Quick lookup table for finding all dependencies of a layerBranch
  538. @property
  539. def layerDependencies_layerBranchId(self):
  540. def createCache(self):
  541. cache = {}
  542. # This ensures empty lists for all branchids
  543. for layerbranchid in self.layerBranches:
  544. cache[layerbranchid] = []
  545. for layerdependencyid in self.layerDependencies:
  546. layerdependency = self.layerDependencies[layerdependencyid]
  547. cache[layerdependency.layerbranch_id].append(layerdependency)
  548. return cache
  549. if self.isLocked():
  550. cache = getattr(self, '_layerDependencies_layerBranchId', None)
  551. else:
  552. cache = None
  553. if not cache:
  554. cache = createCache(self)
  555. if self.isLocked():
  556. super().__setattr__('_layerDependencies_layerBranchId', cache)
  557. return cache
  558. # Quick lookup table for finding all instances of a vcs_url
  559. @property
  560. def layerBranches_vcsUrl(self):
  561. def createCache(self):
  562. cache = {}
  563. for layerbranchid in self.layerBranches:
  564. layerbranch = self.layerBranches[layerbranchid]
  565. if layerbranch.layer.vcs_url not in cache:
  566. cache[layerbranch.layer.vcs_url] = [layerbranch]
  567. else:
  568. cache[layerbranch.layer.vcs_url].append(layerbranch)
  569. return cache
  570. if self.isLocked():
  571. cache = getattr(self, '_layerBranches_vcsUrl', None)
  572. else:
  573. cache = None
  574. if not cache:
  575. cache = createCache(self)
  576. if self.isLocked():
  577. super().__setattr__('_layerBranches_vcsUrl', cache)
  578. return cache
  579. def find_vcs_url(self, vcs_url, branches=None):
  580. ''''Return the first layerBranch with the given vcs_url
  581. If a list of branches has not been specified, we will iterate on
  582. all branches until the first vcs_url is found.'''
  583. if not self.__bool__():
  584. return None
  585. for layerbranch in self.layerBranches_vcsUrl:
  586. if branches and layerbranch.branch.name not in branches:
  587. continue
  588. return layerbranch
  589. return None
  590. def find_collection(self, collection, version=None, branches=None):
  591. '''Return the first layerBranch with the given collection name
  592. If a list of branches has not been specified, we will iterate on
  593. all branches until the first collection is found.'''
  594. if not self.__bool__():
  595. return None
  596. for layerbranchid in self.layerBranches:
  597. layerbranch = self.layerBranches[layerbranchid]
  598. if branches and layerbranch.branch.name not in branches:
  599. continue
  600. if layerbranch.collection == collection and \
  601. (version is None or version == layerbranch.version):
  602. return layerbranch
  603. return None
  604. def find_layerbranch(self, name, branches=None):
  605. '''Return the first layerbranch whose layer name matches
  606. If a list of branches has not been specified, we will iterate on
  607. all branches until the first layer with that name is found.'''
  608. if not self.__bool__():
  609. return None
  610. for layerbranchid in self.layerBranches:
  611. layerbranch = self.layerBranches[layerbranchid]
  612. if branches and layerbranch.branch.name not in branches:
  613. continue
  614. if layerbranch.layer.name == name:
  615. return layerbranch
  616. return None
  617. def find_dependencies(self, names=None, branches=None, layerBranches=None, ignores=None):
  618. '''Return a tuple of all dependencies and valid items for the list of (layer) names
  619. The dependency scanning happens depth-first. The returned
  620. dependencies should be in the best order to define bblayers.
  621. names - list of layer names (searching layerItems)
  622. branches - when specified (with names) only this list of branches are evaluated
  623. layerBranches - list of layerBranches to resolve dependencies
  624. ignores - list of layer names to ignore
  625. return: (dependencies, invalid)
  626. dependencies[LayerItem.name] = [ LayerBranch, LayerDependency1, LayerDependency2, ... ]
  627. invalid = [ LayerItem.name1, LayerItem.name2, ... ]'''
  628. invalid = []
  629. # Convert name/branch to layerBranches
  630. if layerbranches is None:
  631. layerbranches = []
  632. for name in names:
  633. if ignores and name in ignores:
  634. continue
  635. layerbranch = self.find_layerbranch(name, branches)
  636. if not layerbranch:
  637. invalid.append(name)
  638. else:
  639. layerbranches.append(layerbranch)
  640. for layerbranch in layerbranches:
  641. if layerbranch.index != self:
  642. raise LayerIndexException("Can not resolve dependencies across indexes with this class function!")
  643. def _resolve_dependencies(layerbranches, ignores, dependencies, invalid):
  644. for layerbranch in layerbranches:
  645. if ignores and layerbranch.layer.name in ignores:
  646. continue
  647. for layerdependency in layerbranch.index.layerDependencies_layerBranchId[layerbranch.id]:
  648. deplayerbranch = layerdependency.dependency_layerBranch
  649. if ignores and deplayerbranch.layer.name in ignores:
  650. continue
  651. # New dependency, we need to resolve it now... depth-first
  652. if deplayerbranch.layer.name not in dependencies:
  653. (dependencies, invalid) = _resolve_dependencies([deplayerbranch], ignores, dependencies, invalid)
  654. if deplayerbranch.layer.name not in dependencies:
  655. dependencies[deplayerbranch.layer.name] = [deplayerbranch, layerdependency]
  656. else:
  657. if layerdependency not in dependencies[deplayerbranch.layer.name]:
  658. dependencies[deplayerbranch.layer.name].append(layerdependency)
  659. return (dependencies, invalid)
  660. # OK, resolve this one...
  661. dependencies = OrderedDict()
  662. (dependencies, invalid) = _resolve_dependencies(layerbranches, ignores, dependencies, invalid)
  663. # Is this item already in the list, if not add it
  664. for layerbranch in layerbranches:
  665. if layerbranch.layer.name not in dependencies:
  666. dependencies[layerbranch.layer.name] = [layerbranch]
  667. return (dependencies, invalid)
  668. # Define a basic LayerIndexItemObj. This object forms the basis for all other
  669. # objects. The raw Layer Index data is stored in the _data element, but we
  670. # do not want users to access data directly. So wrap this and protect it
  671. # from direct manipulation.
  672. #
  673. # It is up to the insantiators of the objects to fill them out, and once done
  674. # lock the objects to prevent further accidently manipulation.
  675. #
  676. # Using the getattr, setattr and properties we can access and manipulate
  677. # the data within the data element.
  678. class LayerIndexItemObj():
  679. def __init__(self, index, data=None, lock=False):
  680. if data is None:
  681. data = {}
  682. if type(data) != type(dict()):
  683. raise TypeError('data (%s) is not a dict' % type(data))
  684. super().__setattr__('_lock', lock)
  685. super().__setattr__('index', index)
  686. super().__setattr__('_data', data)
  687. def __eq__(self, other):
  688. if self.__class__ != other.__class__:
  689. return False
  690. res=(self._data == other._data)
  691. return res
  692. def __bool__(self):
  693. return bool(self._data)
  694. def __getattr__(self, name):
  695. # These are internal to THIS class, and not part of data
  696. if name == "index" or name.startswith('_'):
  697. return super().__getattribute__(name)
  698. if name not in self._data:
  699. raise AttributeError('%s not in datastore' % name)
  700. return self._data[name]
  701. def _setattr(self, name, value, prop=True):
  702. '''__setattr__ like function, but with control over property object behavior'''
  703. if self.isLocked():
  704. raise TypeError("Can not set attribute '%s': Object data is locked" % name)
  705. if name.startswith('_'):
  706. super().__setattr__(name, value)
  707. return
  708. # Since __setattr__ runs before properties, we need to check if
  709. # there is a setter property and then execute it
  710. # ... or return self._data[name]
  711. propertyobj = getattr(self.__class__, name, None)
  712. if prop and isinstance(propertyobj, property):
  713. if propertyobj.fset:
  714. propertyobj.fset(self, value)
  715. else:
  716. raise AttributeError('Attribute %s is readonly, and may not be set' % name)
  717. else:
  718. self._data[name] = value
  719. def __setattr__(self, name, value):
  720. self._setattr(name, value, prop=True)
  721. def _delattr(self, name, prop=True):
  722. # Since __delattr__ runs before properties, we need to check if
  723. # there is a deleter property and then execute it
  724. # ... or we pop it ourselves..
  725. propertyobj = getattr(self.__class__, name, None)
  726. if prop and isinstance(propertyobj, property):
  727. if propertyobj.fdel:
  728. propertyobj.fdel(self)
  729. else:
  730. raise AttributeError('Attribute %s is readonly, and may not be deleted' % name)
  731. else:
  732. self._data.pop(name)
  733. def __delattr__(self, name):
  734. self._delattr(name, prop=True)
  735. def lockData(self):
  736. '''Lock data object (make it readonly)'''
  737. super().__setattr__("_lock", True)
  738. def unlockData(self):
  739. '''unlock data object (make it readonly)'''
  740. super().__setattr__("_lock", False)
  741. def isLocked(self):
  742. '''Is this object locked (readonly)?'''
  743. return self._lock
  744. # Branch object
  745. class Branch(LayerIndexItemObj):
  746. def define_data(self, id, name, bitbake_branch,
  747. short_description=None, sort_priority=1,
  748. updates_enabled=True, updated=None,
  749. update_environment=None):
  750. self.id = id
  751. self.name = name
  752. self.bitbake_branch = bitbake_branch
  753. self.short_description = short_description or name
  754. self.sort_priority = sort_priority
  755. self.updates_enabled = updates_enabled
  756. self.updated = updated or datetime.datetime.today().isoformat()
  757. self.update_environment = update_environment
  758. @property
  759. def name(self):
  760. return self.__getattr__('name')
  761. @name.setter
  762. def name(self, value):
  763. self._data['name'] = value
  764. if self.bitbake_branch == value:
  765. self.bitbake_branch = ""
  766. @name.deleter
  767. def name(self):
  768. self._delattr('name', prop=False)
  769. @property
  770. def bitbake_branch(self):
  771. try:
  772. return self.__getattr__('bitbake_branch')
  773. except AttributeError:
  774. return self.name
  775. @bitbake_branch.setter
  776. def bitbake_branch(self, value):
  777. if self.name == value:
  778. self._data['bitbake_branch'] = ""
  779. else:
  780. self._data['bitbake_branch'] = value
  781. @bitbake_branch.deleter
  782. def bitbake_branch(self):
  783. self._delattr('bitbake_branch', prop=False)
  784. class LayerItem(LayerIndexItemObj):
  785. def define_data(self, id, name, status='P',
  786. layer_type='A', summary=None,
  787. description=None,
  788. vcs_url=None, vcs_web_url=None,
  789. vcs_web_tree_base_url=None,
  790. vcs_web_file_base_url=None,
  791. usage_url=None,
  792. mailing_list_url=None,
  793. index_preference=1,
  794. classic=False,
  795. updated=None):
  796. self.id = id
  797. self.name = name
  798. self.status = status
  799. self.layer_type = layer_type
  800. self.summary = summary or name
  801. self.description = description or summary or name
  802. self.vcs_url = vcs_url
  803. self.vcs_web_url = vcs_web_url
  804. self.vcs_web_tree_base_url = vcs_web_tree_base_url
  805. self.vcs_web_file_base_url = vcs_web_file_base_url
  806. self.index_preference = index_preference
  807. self.classic = classic
  808. self.updated = updated or datetime.datetime.today().isoformat()
  809. class LayerBranch(LayerIndexItemObj):
  810. def define_data(self, id, collection, version, layer, branch,
  811. vcs_subdir="", vcs_last_fetch=None,
  812. vcs_last_rev=None, vcs_last_commit=None,
  813. actual_branch="",
  814. updated=None):
  815. self.id = id
  816. self.collection = collection
  817. self.version = version
  818. if isinstance(layer, LayerItem):
  819. self.layer = layer
  820. else:
  821. self.layer_id = layer
  822. if isinstance(branch, Branch):
  823. self.branch = branch
  824. else:
  825. self.branch_id = branch
  826. self.vcs_subdir = vcs_subdir
  827. self.vcs_last_fetch = vcs_last_fetch
  828. self.vcs_last_rev = vcs_last_rev
  829. self.vcs_last_commit = vcs_last_commit
  830. self.actual_branch = actual_branch
  831. self.updated = updated or datetime.datetime.today().isoformat()
  832. # This is a little odd, the _data attribute is 'layer', but it's really
  833. # referring to the layer id.. so lets adjust this to make it useful
  834. @property
  835. def layer_id(self):
  836. return self.__getattr__('layer')
  837. @layer_id.setter
  838. def layer_id(self, value):
  839. self._setattr('layer', value, prop=False)
  840. @layer_id.deleter
  841. def layer_id(self):
  842. self._delattr('layer', prop=False)
  843. @property
  844. def layer(self):
  845. try:
  846. return self.index.layerItems[self.layer_id]
  847. except KeyError:
  848. raise AttributeError('Unable to find layerItems in index to map layer_id %s' % self.layer_id)
  849. except IndexError:
  850. raise AttributeError('Unable to find layer_id %s in index layerItems' % self.layer_id)
  851. @layer.setter
  852. def layer(self, value):
  853. if not isinstance(value, LayerItem):
  854. raise TypeError('value is not a LayerItem')
  855. if self.index != value.index:
  856. raise AttributeError('Object and value do not share the same index and thus key set.')
  857. self.layer_id = value.id
  858. @layer.deleter
  859. def layer(self):
  860. del self.layer_id
  861. @property
  862. def branch_id(self):
  863. return self.__getattr__('branch')
  864. @branch_id.setter
  865. def branch_id(self, value):
  866. self._setattr('branch', value, prop=False)
  867. @branch_id.deleter
  868. def branch_id(self):
  869. self._delattr('branch', prop=False)
  870. @property
  871. def branch(self):
  872. try:
  873. logger.debug(1, "Get branch object from branches[%s]" % (self.branch_id))
  874. return self.index.branches[self.branch_id]
  875. except KeyError:
  876. raise AttributeError('Unable to find branches in index to map branch_id %s' % self.branch_id)
  877. except IndexError:
  878. raise AttributeError('Unable to find branch_id %s in index branches' % self.branch_id)
  879. @branch.setter
  880. def branch(self, value):
  881. if not isinstance(value, LayerItem):
  882. raise TypeError('value is not a LayerItem')
  883. if self.index != value.index:
  884. raise AttributeError('Object and value do not share the same index and thus key set.')
  885. self.branch_id = value.id
  886. @branch.deleter
  887. def branch(self):
  888. del self.branch_id
  889. @property
  890. def actual_branch(self):
  891. if self.__getattr__('actual_branch'):
  892. return self.__getattr__('actual_branch')
  893. else:
  894. return self.branch.name
  895. @actual_branch.setter
  896. def actual_branch(self, value):
  897. logger.debug(1, "Set actual_branch to %s .. name is %s" % (value, self.branch.name))
  898. if value != self.branch.name:
  899. self._setattr('actual_branch', value, prop=False)
  900. else:
  901. self._setattr('actual_branch', '', prop=False)
  902. @actual_branch.deleter
  903. def actual_branch(self):
  904. self._delattr('actual_branch', prop=False)
  905. # Extend LayerIndexItemObj with common LayerBranch manipulations
  906. # All of the remaining LayerIndex objects refer to layerbranch, and it is
  907. # up to the user to follow that back through the LayerBranch object into
  908. # the layer object to get various attributes. So add an intermediate set
  909. # of attributes that can easily get us the layerbranch as well as layer.
  910. class LayerIndexItemObj_LayerBranch(LayerIndexItemObj):
  911. @property
  912. def layerbranch_id(self):
  913. return self.__getattr__('layerbranch')
  914. @layerbranch_id.setter
  915. def layerbranch_id(self, value):
  916. self._setattr('layerbranch', value, prop=False)
  917. @layerbranch_id.deleter
  918. def layerbranch_id(self):
  919. self._delattr('layerbranch', prop=False)
  920. @property
  921. def layerbranch(self):
  922. try:
  923. return self.index.layerBranches[self.layerbranch_id]
  924. except KeyError:
  925. raise AttributeError('Unable to find layerBranches in index to map layerbranch_id %s' % self.layerbranch_id)
  926. except IndexError:
  927. raise AttributeError('Unable to find layerbranch_id %s in index branches' % self.layerbranch_id)
  928. @layerbranch.setter
  929. def layerbranch(self, value):
  930. if not isinstance(value, LayerBranch):
  931. raise TypeError('value (%s) is not a layerBranch' % type(value))
  932. if self.index != value.index:
  933. raise AttributeError('Object and value do not share the same index and thus key set.')
  934. self.layerbranch_id = value.id
  935. @layerbranch.deleter
  936. def layerbranch(self):
  937. del self.layerbranch_id
  938. @property
  939. def layer_id(self):
  940. return self.layerbranch.layer_id
  941. # Doesn't make sense to set or delete layer_id
  942. @property
  943. def layer(self):
  944. return self.layerbranch.layer
  945. # Doesn't make sense to set or delete layer
  946. class LayerDependency(LayerIndexItemObj_LayerBranch):
  947. def define_data(self, id, layerbranch, dependency, required=True):
  948. self.id = id
  949. if isinstance(layerbranch, LayerBranch):
  950. self.layerbranch = layerbranch
  951. else:
  952. self.layerbranch_id = layerbranch
  953. if isinstance(dependency, LayerDependency):
  954. self.dependency = dependency
  955. else:
  956. self.dependency_id = dependency
  957. self.required = required
  958. @property
  959. def dependency_id(self):
  960. return self.__getattr__('dependency')
  961. @dependency_id.setter
  962. def dependency_id(self, value):
  963. self._setattr('dependency', value, prop=False)
  964. @dependency_id.deleter
  965. def dependency_id(self):
  966. self._delattr('dependency', prop=False)
  967. @property
  968. def dependency(self):
  969. try:
  970. return self.index.layerItems[self.dependency_id]
  971. except KeyError:
  972. raise AttributeError('Unable to find layerItems in index to map layerbranch_id %s' % self.dependency_id)
  973. except IndexError:
  974. raise AttributeError('Unable to find dependency_id %s in index layerItems' % self.dependency_id)
  975. @dependency.setter
  976. def dependency(self, value):
  977. if not isinstance(value, LayerDependency):
  978. raise TypeError('value (%s) is not a dependency' % type(value))
  979. if self.index != value.index:
  980. raise AttributeError('Object and value do not share the same index and thus key set.')
  981. self.dependency_id = value.id
  982. @dependency.deleter
  983. def dependency(self):
  984. self._delattr('dependency', prop=False)
  985. @property
  986. def dependency_layerBranch(self):
  987. layerid = self.dependency_id
  988. branchid = self.layerbranch.branch_id
  989. try:
  990. return self.index.layerBranches_layerId_branchId["%s:%s" % (layerid, branchid)]
  991. except IndexError:
  992. # layerBranches_layerId_branchId -- but not layerId:branchId
  993. raise AttributeError('Unable to find layerId:branchId %s:%s in index layerBranches_layerId_branchId' % (layerid, branchid))
  994. except KeyError:
  995. raise AttributeError('Unable to find layerId:branchId %s:%s in layerItems and layerBranches' % (layerid, branchid))
  996. # dependency_layerBranch doesn't make sense to set or del
  997. class Recipe(LayerIndexItemObj_LayerBranch):
  998. def define_data(self, id,
  999. filename, filepath, pn, pv, layerbranch,
  1000. summary="", description="", section="", license="",
  1001. homepage="", bugtracker="", provides="", bbclassextend="",
  1002. inherits="", blacklisted="", updated=None):
  1003. self.id = id
  1004. self.filename = filename
  1005. self.filepath = filepath
  1006. self.pn = pn
  1007. self.pv = pv
  1008. self.summary = summary
  1009. self.description = description
  1010. self.section = section
  1011. self.license = license
  1012. self.homepage = homepage
  1013. self.bugtracker = bugtracker
  1014. self.provides = provides
  1015. self.bbclassextend = bbclassextend
  1016. self.inherits = inherits
  1017. self.updated = updated or datetime.datetime.today().isoformat()
  1018. self.blacklisted = blacklisted
  1019. if isinstance(layerbranch, LayerBranch):
  1020. self.layerbranch = layerbranch
  1021. else:
  1022. self.layerbranch_id = layerbranch
  1023. @property
  1024. def fullpath(self):
  1025. return os.path.join(self.filepath, self.filename)
  1026. # Set would need to understand how to split it
  1027. # del would we del both parts?
  1028. @property
  1029. def inherits(self):
  1030. if 'inherits' not in self._data:
  1031. # Older indexes may not have this, so emulate it
  1032. if '-image-' in self.pn:
  1033. return 'image'
  1034. return self.__getattr__('inherits')
  1035. @inherits.setter
  1036. def inherits(self, value):
  1037. return self._setattr('inherits', value, prop=False)
  1038. @inherits.deleter
  1039. def inherits(self):
  1040. return self._delattr('inherits', prop=False)
  1041. class Machine(LayerIndexItemObj_LayerBranch):
  1042. def define_data(self, id,
  1043. name, description, layerbranch,
  1044. updated=None):
  1045. self.id = id
  1046. self.name = name
  1047. self.description = description
  1048. if isinstance(layerbranch, LayerBranch):
  1049. self.layerbranch = layerbranch
  1050. else:
  1051. self.layerbranch_id = layerbranch
  1052. self.updated = updated or datetime.datetime.today().isoformat()
  1053. class Distro(LayerIndexItemObj_LayerBranch):
  1054. def define_data(self, id,
  1055. name, description, layerbranch,
  1056. updated=None):
  1057. self.id = id
  1058. self.name = name
  1059. self.description = description
  1060. if isinstance(layerbranch, LayerBranch):
  1061. self.layerbranch = layerbranch
  1062. else:
  1063. self.layerbranch_id = layerbranch
  1064. self.updated = updated or datetime.datetime.today().isoformat()
  1065. # When performing certain actions, we may need to sort the data.
  1066. # This will allow us to keep it consistent from run to run.
  1067. def sort_entry(item):
  1068. newitem = item
  1069. try:
  1070. if type(newitem) == type(dict()):
  1071. newitem = OrderedDict(sorted(newitem.items(), key=lambda t: t[0]))
  1072. for index in newitem:
  1073. newitem[index] = sort_entry(newitem[index])
  1074. elif type(newitem) == type(list()):
  1075. newitem.sort(key=lambda obj: obj['id'])
  1076. for index, _ in enumerate(newitem):
  1077. newitem[index] = sort_entry(newitem[index])
  1078. except:
  1079. logger.error('Sort failed for item %s' % type(item))
  1080. pass
  1081. return newitem