npm.py 13 KB

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