npm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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' NPM implementation
  5. The NPM fetcher is used to retrieve files from the npmjs repository
  6. Usage in the recipe:
  7. SRC_URI = "npm://registry.npmjs.org/;name=${PN};version=${PV}"
  8. Suported SRC_URI options are:
  9. - name
  10. - version
  11. npm://registry.npmjs.org/${PN}/-/${PN}-${PV}.tgz would become npm://registry.npmjs.org;name=${PN};ver=${PV}
  12. The fetcher all triggers off the existence of ud.localpath. If that exists and has the ".done" stamp, its assumed the fetch is good/done
  13. """
  14. import os
  15. import sys
  16. import urllib.request, urllib.parse, urllib.error
  17. import json
  18. import subprocess
  19. import signal
  20. import bb
  21. from bb import data
  22. from bb.fetch2 import FetchMethod
  23. from bb.fetch2 import FetchError
  24. from bb.fetch2 import ChecksumError
  25. from bb.fetch2 import runfetchcmd
  26. from bb.fetch2 import logger
  27. from bb.fetch2 import UnpackError
  28. from bb.fetch2 import ParameterError
  29. from distutils import spawn
  30. def subprocess_setup():
  31. # Python installs a SIGPIPE handler by default. This is usually not what
  32. # non-Python subprocesses expect.
  33. # SIGPIPE errors are known issues with gzip/bash
  34. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  35. class Npm(FetchMethod):
  36. """Class to fetch urls via 'npm'"""
  37. def init(self, d):
  38. pass
  39. def supports(self, ud, d):
  40. """
  41. Check to see if a given url can be fetched with npm
  42. """
  43. return ud.type in ['npm']
  44. def debug(self, msg):
  45. logger.debug(1, "NpmFetch: %s", msg)
  46. def clean(self, ud, d):
  47. logger.debug(2, "Calling cleanup %s" % ud.pkgname)
  48. bb.utils.remove(ud.localpath, False)
  49. bb.utils.remove(ud.pkgdatadir, True)
  50. bb.utils.remove(ud.fullmirror, False)
  51. def urldata_init(self, ud, d):
  52. """
  53. init NPM specific variable within url data
  54. """
  55. if 'downloadfilename' in ud.parm:
  56. ud.basename = ud.parm['downloadfilename']
  57. else:
  58. ud.basename = os.path.basename(ud.path)
  59. # can't call it ud.name otherwise fetcher base class will start doing sha1stuff
  60. # TODO: find a way to get an sha1/sha256 manifest of pkg & all deps
  61. ud.pkgname = ud.parm.get("name", None)
  62. if not ud.pkgname:
  63. raise ParameterError("NPM fetcher requires a name parameter", ud.url)
  64. ud.version = ud.parm.get("version", None)
  65. if not ud.version:
  66. raise ParameterError("NPM fetcher requires a version parameter", ud.url)
  67. ud.bbnpmmanifest = "%s-%s.deps.json" % (ud.pkgname, ud.version)
  68. ud.registry = "http://%s" % (ud.url.replace('npm://', '', 1).split(';'))[0]
  69. prefixdir = "npm/%s" % ud.pkgname
  70. ud.pkgdatadir = d.expand("${DL_DIR}/%s" % prefixdir)
  71. if not os.path.exists(ud.pkgdatadir):
  72. bb.utils.mkdirhier(ud.pkgdatadir)
  73. ud.localpath = d.expand("${DL_DIR}/npm/%s" % ud.bbnpmmanifest)
  74. self.basecmd = d.getVar("FETCHCMD_wget", True) or "/usr/bin/env wget -O -t 2 -T 30 -nv --passive-ftp --no-check-certificate "
  75. self.basecmd += " --directory-prefix=%s " % prefixdir
  76. ud.write_tarballs = ((data.getVar("BB_GENERATE_MIRROR_TARBALLS", d, True) or "0") != "0")
  77. ud.mirrortarball = 'npm_%s-%s.tar.xz' % (ud.pkgname, ud.version)
  78. ud.fullmirror = os.path.join(d.getVar("DL_DIR", True), ud.mirrortarball)
  79. def need_update(self, ud, d):
  80. if os.path.exists(ud.localpath):
  81. return False
  82. return True
  83. def _runwget(self, ud, d, command, quiet):
  84. logger.debug(2, "Fetching %s using command '%s'" % (ud.url, command))
  85. bb.fetch2.check_network_access(d, command)
  86. runfetchcmd(command, d, quiet)
  87. def _unpackdep(self, ud, pkg, data, destdir, dldir, d):
  88. file = data[pkg]['tgz']
  89. logger.debug(2, "file to extract is %s" % file)
  90. if file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
  91. cmd = 'tar xz --strip 1 --no-same-owner --warning=no-unknown-keyword -f %s/%s' % (dldir, file)
  92. else:
  93. bb.fatal("NPM package %s downloaded not a tarball!" % file)
  94. # Change to subdir before executing command
  95. save_cwd = os.getcwd()
  96. if not os.path.exists(destdir):
  97. os.makedirs(destdir)
  98. os.chdir(destdir)
  99. path = d.getVar('PATH', True)
  100. if path:
  101. cmd = "PATH=\"%s\" %s" % (path, cmd)
  102. bb.note("Unpacking %s to %s/" % (file, os.getcwd()))
  103. ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True)
  104. os.chdir(save_cwd)
  105. if ret != 0:
  106. raise UnpackError("Unpack command %s failed with return value %s" % (cmd, ret), ud.url)
  107. if 'deps' not in data[pkg]:
  108. return
  109. for dep in data[pkg]['deps']:
  110. self._unpackdep(ud, dep, data[pkg]['deps'], "%s/node_modules/%s" % (destdir, dep), dldir, d)
  111. def unpack(self, ud, destdir, d):
  112. dldir = d.getVar("DL_DIR", True)
  113. depdumpfile = "%s-%s.deps.json" % (ud.pkgname, ud.version)
  114. with open("%s/npm/%s" % (dldir, depdumpfile)) as datafile:
  115. workobj = json.load(datafile)
  116. dldir = "%s/%s" % (os.path.dirname(ud.localpath), ud.pkgname)
  117. self._unpackdep(ud, ud.pkgname, workobj, "%s/npmpkg" % destdir, dldir, d)
  118. def _parse_view(self, output):
  119. '''
  120. Parse the output of npm view --json; the last JSON result
  121. is assumed to be the one that we're interested in.
  122. '''
  123. pdata = None
  124. outdeps = {}
  125. datalines = []
  126. bracelevel = 0
  127. for line in output.splitlines():
  128. if bracelevel:
  129. datalines.append(line)
  130. elif '{' in line:
  131. datalines = []
  132. datalines.append(line)
  133. bracelevel = bracelevel + line.count('{') - line.count('}')
  134. if datalines:
  135. pdata = json.loads('\n'.join(datalines))
  136. return pdata
  137. def _getdependencies(self, pkg, data, version, d, ud, optional=False):
  138. pkgfullname = pkg
  139. if version != '*' and not '/' in version:
  140. pkgfullname += "@'%s'" % version
  141. logger.debug(2, "Calling getdeps on %s" % pkg)
  142. fetchcmd = "npm view %s --json --registry %s" % (pkgfullname, ud.registry)
  143. output = runfetchcmd(fetchcmd, d, True)
  144. pdata = self._parse_view(output)
  145. if not pdata:
  146. raise FetchError("The command '%s' returned no output" % fetchcmd)
  147. if optional:
  148. pkg_os = pdata.get('os', None)
  149. if pkg_os:
  150. if not isinstance(pkg_os, list):
  151. pkg_os = [pkg_os]
  152. if 'linux' not in pkg_os or '!linux' in pkg_os:
  153. logger.debug(2, "Skipping %s since it's incompatible with Linux" % pkg)
  154. return
  155. #logger.debug(2, "Output URL is %s - %s - %s" % (ud.basepath, ud.basename, ud.localfile))
  156. outputurl = pdata['dist']['tarball']
  157. data[pkg] = {}
  158. data[pkg]['tgz'] = os.path.basename(outputurl)
  159. self._runwget(ud, d, "%s %s" % (self.basecmd, outputurl), False)
  160. dependencies = pdata.get('dependencies', {})
  161. optionalDependencies = pdata.get('optionalDependencies', {})
  162. depsfound = {}
  163. optdepsfound = {}
  164. data[pkg]['deps'] = {}
  165. for dep in dependencies:
  166. if dep in optionalDependencies:
  167. optdepsfound[dep] = dependencies[dep]
  168. else:
  169. depsfound[dep] = dependencies[dep]
  170. for dep, version in optdepsfound.items():
  171. self._getdependencies(dep, data[pkg]['deps'], version, d, ud, optional=True)
  172. for dep, version in depsfound.items():
  173. self._getdependencies(dep, data[pkg]['deps'], version, d, ud)
  174. def _getshrinkeddependencies(self, pkg, data, version, d, ud, lockdown, manifest):
  175. logger.debug(2, "NPM shrinkwrap file is %s" % data)
  176. outputurl = "invalid"
  177. if ('resolved' not in data) or (not data['resolved'].startswith('http')):
  178. # will be the case for ${PN}
  179. fetchcmd = "npm view %s@%s dist.tarball --registry %s" % (pkg, version, ud.registry)
  180. logger.debug(2, "Found this matching URL: %s" % str(fetchcmd))
  181. outputurl = runfetchcmd(fetchcmd, d, True)
  182. else:
  183. outputurl = data['resolved']
  184. self._runwget(ud, d, "%s %s" % (self.basecmd, outputurl), False)
  185. manifest[pkg] = {}
  186. manifest[pkg]['tgz'] = os.path.basename(outputurl).rstrip()
  187. manifest[pkg]['deps'] = {}
  188. if pkg in lockdown:
  189. sha1_expected = lockdown[pkg][version]
  190. sha1_data = bb.utils.sha1_file("npm/%s/%s" % (ud.pkgname, manifest[pkg]['tgz']))
  191. if sha1_expected != sha1_data:
  192. msg = "\nFile: '%s' has %s checksum %s when %s was expected" % (manifest[pkg]['tgz'], 'sha1', sha1_data, sha1_expected)
  193. raise ChecksumError('Checksum mismatch!%s' % msg)
  194. else:
  195. logger.debug(2, "No lockdown data for %s@%s" % (pkg, version))
  196. if 'dependencies' in data:
  197. for obj in data['dependencies']:
  198. logger.debug(2, "Found dep is %s" % str(obj))
  199. self._getshrinkeddependencies(obj, data['dependencies'][obj], data['dependencies'][obj]['version'], d, ud, lockdown, manifest[pkg]['deps'])
  200. def download(self, ud, d):
  201. """Fetch url"""
  202. jsondepobj = {}
  203. shrinkobj = {}
  204. lockdown = {}
  205. if not os.listdir(ud.pkgdatadir) and os.path.exists(ud.fullmirror):
  206. dest = d.getVar("DL_DIR", True)
  207. bb.utils.mkdirhier(dest)
  208. save_cwd = os.getcwd()
  209. os.chdir(dest)
  210. runfetchcmd("tar -xJf %s" % (ud.fullmirror), d)
  211. os.chdir(save_cwd)
  212. return
  213. shwrf = d.getVar('NPM_SHRINKWRAP', True)
  214. logger.debug(2, "NPM shrinkwrap file is %s" % shwrf)
  215. try:
  216. with open(shwrf) as datafile:
  217. shrinkobj = json.load(datafile)
  218. except:
  219. logger.warning('Missing shrinkwrap file in NPM_SHRINKWRAP for %s, this will lead to unreliable builds!' % ud.pkgname)
  220. lckdf = d.getVar('NPM_LOCKDOWN', True)
  221. logger.debug(2, "NPM lockdown file is %s" % lckdf)
  222. try:
  223. with open(lckdf) as datafile:
  224. lockdown = json.load(datafile)
  225. except:
  226. logger.warning('Missing lockdown file in NPM_LOCKDOWN for %s, this will lead to unreproducible builds!' % ud.pkgname)
  227. if ('name' not in shrinkobj):
  228. self._getdependencies(ud.pkgname, jsondepobj, ud.version, d, ud)
  229. else:
  230. self._getshrinkeddependencies(ud.pkgname, shrinkobj, ud.version, d, ud, lockdown, jsondepobj)
  231. with open(ud.localpath, 'w') as outfile:
  232. json.dump(jsondepobj, outfile)
  233. def build_mirror_data(self, ud, d):
  234. # Generate a mirror tarball if needed
  235. if ud.write_tarballs and not os.path.exists(ud.fullmirror):
  236. # it's possible that this symlink points to read-only filesystem with PREMIRROR
  237. if os.path.islink(ud.fullmirror):
  238. os.unlink(ud.fullmirror)
  239. save_cwd = os.getcwd()
  240. os.chdir(d.getVar("DL_DIR", True))
  241. logger.info("Creating tarball of npm data")
  242. runfetchcmd("tar -cJf %s npm/%s npm/%s" % (ud.fullmirror, ud.bbnpmmanifest, ud.pkgname), d)
  243. runfetchcmd("touch %s.done" % (ud.fullmirror), d)
  244. os.chdir(save_cwd)