__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. """
  4. BitBake 'Fetch' implementations
  5. Classes for obtaining upstream sources for the
  6. BitBake build tools.
  7. """
  8. # Copyright (C) 2003, 2004 Chris Larson
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License version 2 as
  12. # published by the Free Software Foundation.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. # Based on functions from the base bb module, Copyright 2003 Holger Schurig
  24. import os, re, fcntl
  25. import bb
  26. from bb import data
  27. from bb import persist_data
  28. try:
  29. import cPickle as pickle
  30. except ImportError:
  31. import pickle
  32. class FetchError(Exception):
  33. """Exception raised when a download fails"""
  34. class NoMethodError(Exception):
  35. """Exception raised when there is no method to obtain a supplied url or set of urls"""
  36. class MissingParameterError(Exception):
  37. """Exception raised when a fetch method is missing a critical parameter in the url"""
  38. class ParameterError(Exception):
  39. """Exception raised when a url cannot be proccessed due to invalid parameters."""
  40. class MD5SumError(Exception):
  41. """Exception raised when a MD5SUM of a file does not match the expected one"""
  42. def uri_replace(uri, uri_find, uri_replace, d):
  43. # bb.msg.note(1, bb.msg.domain.Fetcher, "uri_replace: operating on %s" % uri)
  44. if not uri or not uri_find or not uri_replace:
  45. bb.msg.debug(1, bb.msg.domain.Fetcher, "uri_replace: passed an undefined value, not replacing")
  46. uri_decoded = list(bb.decodeurl(uri))
  47. uri_find_decoded = list(bb.decodeurl(uri_find))
  48. uri_replace_decoded = list(bb.decodeurl(uri_replace))
  49. result_decoded = ['','','','','',{}]
  50. for i in uri_find_decoded:
  51. loc = uri_find_decoded.index(i)
  52. result_decoded[loc] = uri_decoded[loc]
  53. import types
  54. if type(i) == types.StringType:
  55. import re
  56. if (re.match(i, uri_decoded[loc])):
  57. result_decoded[loc] = re.sub(i, uri_replace_decoded[loc], uri_decoded[loc])
  58. if uri_find_decoded.index(i) == 2:
  59. if d:
  60. localfn = bb.fetch.localpath(uri, d)
  61. if localfn:
  62. result_decoded[loc] = os.path.dirname(result_decoded[loc]) + "/" + os.path.basename(bb.fetch.localpath(uri, d))
  63. # bb.msg.note(1, bb.msg.domain.Fetcher, "uri_replace: matching %s against %s and replacing with %s" % (i, uri_decoded[loc], uri_replace_decoded[loc]))
  64. else:
  65. # bb.msg.note(1, bb.msg.domain.Fetcher, "uri_replace: no match")
  66. return uri
  67. # else:
  68. # for j in i.keys():
  69. # FIXME: apply replacements against options
  70. return bb.encodeurl(result_decoded)
  71. methods = []
  72. urldata_cache = {}
  73. def fetcher_init(d):
  74. """
  75. Called to initilize the fetchers once the configuration data is known
  76. Calls before this must not hit the cache.
  77. """
  78. pd = persist_data.PersistData(d)
  79. # When to drop SCM head revisions controled by user policy
  80. srcrev_policy = bb.data.getVar('BB_SRCREV_POLICY', d, 1) or "clear"
  81. if srcrev_policy == "cache":
  82. bb.msg.debug(1, bb.msg.domain.Fetcher, "Keeping SRCREV cache due to cache policy of: %s" % srcrev_policy)
  83. elif srcrev_policy == "clear":
  84. bb.msg.debug(1, bb.msg.domain.Fetcher, "Clearing SRCREV cache due to cache policy of: %s" % srcrev_policy)
  85. pd.delDomain("BB_URI_HEADREVS")
  86. else:
  87. bb.msg.fatal(bb.msg.domain.Fetcher, "Invalid SRCREV cache policy of: %s" % srcrev_policy)
  88. # Make sure our domains exist
  89. pd.addDomain("BB_URI_HEADREVS")
  90. pd.addDomain("BB_URI_LOCALCOUNT")
  91. # Function call order is usually:
  92. # 1. init
  93. # 2. go
  94. # 3. localpaths
  95. # localpath can be called at any time
  96. def init(urls, d, setup = True):
  97. urldata = {}
  98. fn = bb.data.getVar('FILE', d, 1)
  99. if fn in urldata_cache:
  100. urldata = urldata_cache[fn]
  101. for url in urls:
  102. if url not in urldata:
  103. urldata[url] = FetchData(url, d)
  104. if setup:
  105. for url in urldata:
  106. if not urldata[url].setup:
  107. urldata[url].setup_localpath(d)
  108. urldata_cache[fn] = urldata
  109. return urldata
  110. def go(d):
  111. """
  112. Fetch all urls
  113. init must have previously been called
  114. """
  115. urldata = init([], d, True)
  116. for u in urldata:
  117. ud = urldata[u]
  118. m = ud.method
  119. if ud.localfile:
  120. if not m.forcefetch(u, ud, d) and os.path.exists(ud.md5):
  121. # File already present along with md5 stamp file
  122. # Touch md5 file to show activity
  123. try:
  124. os.utime(ud.md5, None)
  125. except:
  126. # Errors aren't fatal here
  127. pass
  128. continue
  129. lf = bb.utils.lockfile(ud.lockfile)
  130. if not m.forcefetch(u, ud, d) and os.path.exists(ud.md5):
  131. # If someone else fetched this before we got the lock,
  132. # notice and don't try again
  133. try:
  134. os.utime(ud.md5, None)
  135. except:
  136. # Errors aren't fatal here
  137. pass
  138. bb.utils.unlockfile(lf)
  139. continue
  140. m.go(u, ud, d)
  141. if ud.localfile:
  142. if not m.forcefetch(u, ud, d):
  143. Fetch.write_md5sum(u, ud, d)
  144. bb.utils.unlockfile(lf)
  145. def localpaths(d):
  146. """
  147. Return a list of the local filenames, assuming successful fetch
  148. """
  149. local = []
  150. urldata = init([], d, True)
  151. for u in urldata:
  152. ud = urldata[u]
  153. local.append(ud.localpath)
  154. return local
  155. srcrev_internal_call = False
  156. def get_srcrev(d):
  157. """
  158. Return the version string for the current package
  159. (usually to be used as PV)
  160. Most packages usually only have one SCM so we just pass on the call.
  161. In the multi SCM case, we build a value based on SRCREV_FORMAT which must
  162. have been set.
  163. """
  164. #
  165. # Ugly code alert. localpath in the fetchers will try to evaluate SRCREV which
  166. # could translate into a call to here. If it does, we need to catch this
  167. # and provide some way so it knows get_srcrev is active instead of being
  168. # some number etc. hence the srcrev_internal_call tracking and the magic
  169. # "SRCREVINACTION" return value.
  170. #
  171. # Neater solutions welcome!
  172. #
  173. if bb.fetch.srcrev_internal_call:
  174. return "SRCREVINACTION"
  175. scms = []
  176. # Only call setup_localpath on URIs which suppports_srcrev()
  177. urldata = init(bb.data.getVar('SRC_URI', d, 1).split(), d, False)
  178. for u in urldata:
  179. ud = urldata[u]
  180. if ud.method.suppports_srcrev():
  181. if not ud.setup:
  182. ud.setup_localpath(d)
  183. scms.append(u)
  184. if len(scms) == 0:
  185. bb.msg.error(bb.msg.domain.Fetcher, "SRCREV was used yet no valid SCM was found in SRC_URI")
  186. raise ParameterError
  187. if len(scms) == 1:
  188. return urldata[scms[0]].method.sortable_revision(scms[0], urldata[scms[0]], d)
  189. #
  190. # Mutiple SCMs are in SRC_URI so we resort to SRCREV_FORMAT
  191. #
  192. format = bb.data.getVar('SRCREV_FORMAT', d, 1)
  193. if not format:
  194. bb.msg.error(bb.msg.domain.Fetcher, "The SRCREV_FORMAT variable must be set when multiple SCMs are used.")
  195. raise ParameterError
  196. for scm in scms:
  197. if 'name' in urldata[scm].parm:
  198. name = urldata[scm].parm["name"]
  199. rev = urldata[scm].method.sortable_revision(scm, urldata[scm], d)
  200. format = format.replace(name, rev)
  201. return format
  202. def localpath(url, d, cache = True):
  203. """
  204. Called from the parser with cache=False since the cache isn't ready
  205. at this point. Also called from classed in OE e.g. patch.bbclass
  206. """
  207. ud = init([url], d)
  208. if ud[url].method:
  209. return ud[url].localpath
  210. return url
  211. def runfetchcmd(cmd, d, quiet = False):
  212. """
  213. Run cmd returning the command output
  214. Raise an error if interrupted or cmd fails
  215. Optionally echo command output to stdout
  216. """
  217. bb.msg.debug(1, bb.msg.domain.Fetcher, "Running %s" % cmd)
  218. # Need to export PATH as binary could be in metadata paths
  219. # rather than host provided
  220. pathcmd = 'export PATH=%s; %s' % (data.expand('${PATH}', d), cmd)
  221. stdout_handle = os.popen(pathcmd, "r")
  222. output = ""
  223. while 1:
  224. line = stdout_handle.readline()
  225. if not line:
  226. break
  227. if not quiet:
  228. print line,
  229. output += line
  230. status = stdout_handle.close() or 0
  231. signal = status >> 8
  232. exitstatus = status & 0xff
  233. if signal:
  234. raise FetchError("Fetch command %s failed with signal %s, output:\n%s" % (pathcmd, signal, output))
  235. elif status != 0:
  236. raise FetchError("Fetch command %s failed with exit code %s, output:\n%s" % (pathcmd, status, output))
  237. return output
  238. class FetchData(object):
  239. """
  240. A class which represents the fetcher state for a given URI.
  241. """
  242. def __init__(self, url, d):
  243. self.localfile = ""
  244. (self.type, self.host, self.path, self.user, self.pswd, self.parm) = bb.decodeurl(data.expand(url, d))
  245. self.date = Fetch.getSRCDate(self, d)
  246. self.url = url
  247. self.setup = False
  248. for m in methods:
  249. if m.supports(url, self, d):
  250. self.method = m
  251. return
  252. raise NoMethodError("Missing implementation for url %s" % url)
  253. def setup_localpath(self, d):
  254. self.setup = True
  255. if "localpath" in self.parm:
  256. # if user sets localpath for file, use it instead.
  257. self.localpath = self.parm["localpath"]
  258. else:
  259. bb.fetch.srcrev_internal_call = True
  260. self.localpath = self.method.localpath(self.url, self, d)
  261. bb.fetch.srcrev_internal_call = False
  262. # We have to clear data's internal caches since the cached value of SRCREV is now wrong.
  263. # Horrible...
  264. bb.data.delVar("ISHOULDNEVEREXIST", d)
  265. self.md5 = self.localpath + '.md5'
  266. self.lockfile = self.localpath + '.lock'
  267. class Fetch(object):
  268. """Base class for 'fetch'ing data"""
  269. def __init__(self, urls = []):
  270. self.urls = []
  271. def supports(self, url, urldata, d):
  272. """
  273. Check to see if this fetch class supports a given url.
  274. """
  275. return 0
  276. def localpath(self, url, urldata, d):
  277. """
  278. Return the local filename of a given url assuming a successful fetch.
  279. Can also setup variables in urldata for use in go (saving code duplication
  280. and duplicate code execution)
  281. """
  282. return url
  283. def setUrls(self, urls):
  284. self.__urls = urls
  285. def getUrls(self):
  286. return self.__urls
  287. urls = property(getUrls, setUrls, None, "Urls property")
  288. def forcefetch(self, url, urldata, d):
  289. """
  290. Force a fetch, even if localpath exists?
  291. """
  292. return False
  293. def suppports_srcrev(self):
  294. """
  295. The fetcher supports auto source revisions (SRCREV)
  296. """
  297. return False
  298. def go(self, url, urldata, d):
  299. """
  300. Fetch urls
  301. Assumes localpath was called first
  302. """
  303. raise NoMethodError("Missing implementation for url")
  304. def getSRCDate(urldata, d):
  305. """
  306. Return the SRC Date for the component
  307. d the bb.data module
  308. """
  309. if "srcdate" in urldata.parm:
  310. return urldata.parm['srcdate']
  311. pn = data.getVar("PN", d, 1)
  312. if pn:
  313. return data.getVar("SRCDATE_%s" % pn, d, 1) or data.getVar("CVSDATE_%s" % pn, d, 1) or data.getVar("SRCDATE", d, 1) or data.getVar("CVSDATE", d, 1) or data.getVar("DATE", d, 1)
  314. return data.getVar("SRCDATE", d, 1) or data.getVar("CVSDATE", d, 1) or data.getVar("DATE", d, 1)
  315. getSRCDate = staticmethod(getSRCDate)
  316. def srcrev_internal_helper(ud, d):
  317. """
  318. Return:
  319. a) a source revision if specified
  320. b) True if auto srcrev is in action
  321. c) False otherwise
  322. """
  323. if 'rev' in ud.parm:
  324. return ud.parm['rev']
  325. if 'tag' in ud.parm:
  326. return ud.parm['tag']
  327. rev = None
  328. if 'name' in ud.parm:
  329. pn = data.getVar("PN", d, 1)
  330. rev = data.getVar("SRCREV_pn-" + pn + "_" + ud.parm['name'], d, 1)
  331. if not rev:
  332. rev = data.getVar("SRCREV", d, 1)
  333. if not rev:
  334. return False
  335. if rev is "SRCREVINACTION":
  336. return True
  337. return rev
  338. srcrev_internal_helper = staticmethod(srcrev_internal_helper)
  339. def try_mirror(d, tarfn):
  340. """
  341. Try to use a mirrored version of the sources. We do this
  342. to avoid massive loads on foreign cvs and svn servers.
  343. This method will be used by the different fetcher
  344. implementations.
  345. d Is a bb.data instance
  346. tarfn is the name of the tarball
  347. """
  348. tarpath = os.path.join(data.getVar("DL_DIR", d, 1), tarfn)
  349. if os.access(tarpath, os.R_OK):
  350. bb.msg.debug(1, bb.msg.domain.Fetcher, "%s already exists, skipping checkout." % tarfn)
  351. return True
  352. pn = data.getVar('PN', d, True)
  353. src_tarball_stash = None
  354. if pn:
  355. src_tarball_stash = (data.getVar('SRC_TARBALL_STASH_%s' % pn, d, True) or data.getVar('CVS_TARBALL_STASH_%s' % pn, d, True) or data.getVar('SRC_TARBALL_STASH', d, True) or data.getVar('CVS_TARBALL_STASH', d, True) or "").split()
  356. for stash in src_tarball_stash:
  357. fetchcmd = data.getVar("FETCHCOMMAND_mirror", d, True) or data.getVar("FETCHCOMMAND_wget", d, True)
  358. uri = stash + tarfn
  359. bb.msg.note(1, bb.msg.domain.Fetcher, "fetch " + uri)
  360. fetchcmd = fetchcmd.replace("${URI}", uri)
  361. ret = os.system(fetchcmd)
  362. if ret == 0:
  363. bb.msg.note(1, bb.msg.domain.Fetcher, "Fetched %s from tarball stash, skipping checkout" % tarfn)
  364. return True
  365. return False
  366. try_mirror = staticmethod(try_mirror)
  367. def verify_md5sum(ud, got_sum):
  368. """
  369. Verify the md5sum we wanted with the one we got
  370. """
  371. wanted_sum = None
  372. if 'md5sum' in ud.parm:
  373. wanted_sum = ud.parm['md5sum']
  374. if not wanted_sum:
  375. return True
  376. return wanted_sum == got_sum
  377. verify_md5sum = staticmethod(verify_md5sum)
  378. def write_md5sum(url, ud, d):
  379. if bb.which(data.getVar('PATH', d), 'md5sum'):
  380. try:
  381. md5pipe = os.popen('md5sum ' + ud.localpath)
  382. md5data = (md5pipe.readline().split() or [ "" ])[0]
  383. md5pipe.close()
  384. except OSError:
  385. md5data = ""
  386. # verify the md5sum
  387. if not Fetch.verify_md5sum(ud, md5data):
  388. raise MD5SumError(url)
  389. md5out = file(ud.md5, 'w')
  390. md5out.write(md5data)
  391. md5out.close()
  392. write_md5sum = staticmethod(write_md5sum)
  393. def latest_revision(self, url, ud, d):
  394. """
  395. Look in the cache for the latest revision, if not present ask the SCM.
  396. """
  397. if not hasattr(self, "_latest_revision"):
  398. raise ParameterError
  399. pd = persist_data.PersistData(d)
  400. key = self._revision_key(url, ud, d)
  401. rev = pd.getValue("BB_URI_HEADREVS", key)
  402. if rev != None:
  403. return str(rev)
  404. rev = self._latest_revision(url, ud, d)
  405. pd.setValue("BB_URI_HEADREVS", key, rev)
  406. return rev
  407. def sortable_revision(self, url, ud, d):
  408. """
  409. """
  410. if hasattr(self, "_sortable_revision"):
  411. return self._sortable_revision(url, ud, d)
  412. pd = persist_data.PersistData(d)
  413. key = self._revision_key(url, ud, d)
  414. latest_rev = self._build_revision(url, ud, d)
  415. last_rev = pd.getValue("BB_URI_LOCALCOUNT", key + "_rev")
  416. count = pd.getValue("BB_URI_LOCALCOUNT", key + "_count")
  417. if last_rev == latest_rev:
  418. return str(count + "+" + latest_rev)
  419. if count is None:
  420. count = "0"
  421. else:
  422. count = str(int(count) + 1)
  423. pd.setValue("BB_URI_LOCALCOUNT", key + "_rev", latest_rev)
  424. pd.setValue("BB_URI_LOCALCOUNT", key + "_count", count)
  425. return str(count + "+" + latest_rev)
  426. import cvs
  427. import git
  428. import local
  429. import svn
  430. import wget
  431. import svk
  432. import ssh
  433. import perforce
  434. import bzr
  435. import hg
  436. methods.append(local.Local())
  437. methods.append(wget.Wget())
  438. methods.append(svn.Svn())
  439. methods.append(git.Git())
  440. methods.append(cvs.Cvs())
  441. methods.append(svk.Svk())
  442. methods.append(ssh.SSH())
  443. methods.append(perforce.Perforce())
  444. methods.append(bzr.Bzr())
  445. methods.append(hg.Hg())