verify.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. 'use strict'
  2. const util = require('util')
  3. const pMap = require('p-map')
  4. const contentPath = require('./content/path')
  5. const fixOwner = require('./util/fix-owner')
  6. const fs = require('fs')
  7. const fsm = require('fs-minipass')
  8. const glob = util.promisify(require('glob'))
  9. const index = require('./entry-index')
  10. const path = require('path')
  11. const rimraf = util.promisify(require('rimraf'))
  12. const ssri = require('ssri')
  13. const hasOwnProperty = (obj, key) =>
  14. Object.prototype.hasOwnProperty.call(obj, key)
  15. const stat = util.promisify(fs.stat)
  16. const truncate = util.promisify(fs.truncate)
  17. const writeFile = util.promisify(fs.writeFile)
  18. const readFile = util.promisify(fs.readFile)
  19. const verifyOpts = (opts) => ({
  20. concurrency: 20,
  21. log: { silly () {} },
  22. ...opts,
  23. })
  24. module.exports = verify
  25. function verify (cache, opts) {
  26. opts = verifyOpts(opts)
  27. opts.log.silly('verify', 'verifying cache at', cache)
  28. const steps = [
  29. markStartTime,
  30. fixPerms,
  31. garbageCollect,
  32. rebuildIndex,
  33. cleanTmp,
  34. writeVerifile,
  35. markEndTime,
  36. ]
  37. return steps
  38. .reduce((promise, step, i) => {
  39. const label = step.name
  40. const start = new Date()
  41. return promise.then((stats) => {
  42. return step(cache, opts).then((s) => {
  43. s &&
  44. Object.keys(s).forEach((k) => {
  45. stats[k] = s[k]
  46. })
  47. const end = new Date()
  48. if (!stats.runTime)
  49. stats.runTime = {}
  50. stats.runTime[label] = end - start
  51. return Promise.resolve(stats)
  52. })
  53. })
  54. }, Promise.resolve({}))
  55. .then((stats) => {
  56. stats.runTime.total = stats.endTime - stats.startTime
  57. opts.log.silly(
  58. 'verify',
  59. 'verification finished for',
  60. cache,
  61. 'in',
  62. `${stats.runTime.total}ms`
  63. )
  64. return stats
  65. })
  66. }
  67. function markStartTime (cache, opts) {
  68. return Promise.resolve({ startTime: new Date() })
  69. }
  70. function markEndTime (cache, opts) {
  71. return Promise.resolve({ endTime: new Date() })
  72. }
  73. function fixPerms (cache, opts) {
  74. opts.log.silly('verify', 'fixing cache permissions')
  75. return fixOwner
  76. .mkdirfix(cache, cache)
  77. .then(() => {
  78. // TODO - fix file permissions too
  79. return fixOwner.chownr(cache, cache)
  80. })
  81. .then(() => null)
  82. }
  83. // Implements a naive mark-and-sweep tracing garbage collector.
  84. //
  85. // The algorithm is basically as follows:
  86. // 1. Read (and filter) all index entries ("pointers")
  87. // 2. Mark each integrity value as "live"
  88. // 3. Read entire filesystem tree in `content-vX/` dir
  89. // 4. If content is live, verify its checksum and delete it if it fails
  90. // 5. If content is not marked as live, rimraf it.
  91. //
  92. function garbageCollect (cache, opts) {
  93. opts.log.silly('verify', 'garbage collecting content')
  94. const indexStream = index.lsStream(cache)
  95. const liveContent = new Set()
  96. indexStream.on('data', (entry) => {
  97. if (opts.filter && !opts.filter(entry))
  98. return
  99. liveContent.add(entry.integrity.toString())
  100. })
  101. return new Promise((resolve, reject) => {
  102. indexStream.on('end', resolve).on('error', reject)
  103. }).then(() => {
  104. const contentDir = contentPath.contentDir(cache)
  105. return glob(path.join(contentDir, '**'), {
  106. follow: false,
  107. nodir: true,
  108. nosort: true,
  109. }).then((files) => {
  110. return Promise.resolve({
  111. verifiedContent: 0,
  112. reclaimedCount: 0,
  113. reclaimedSize: 0,
  114. badContentCount: 0,
  115. keptSize: 0,
  116. }).then((stats) =>
  117. pMap(
  118. files,
  119. (f) => {
  120. const split = f.split(/[/\\]/)
  121. const digest = split.slice(split.length - 3).join('')
  122. const algo = split[split.length - 4]
  123. const integrity = ssri.fromHex(digest, algo)
  124. if (liveContent.has(integrity.toString())) {
  125. return verifyContent(f, integrity).then((info) => {
  126. if (!info.valid) {
  127. stats.reclaimedCount++
  128. stats.badContentCount++
  129. stats.reclaimedSize += info.size
  130. } else {
  131. stats.verifiedContent++
  132. stats.keptSize += info.size
  133. }
  134. return stats
  135. })
  136. } else {
  137. // No entries refer to this content. We can delete.
  138. stats.reclaimedCount++
  139. return stat(f).then((s) => {
  140. return rimraf(f).then(() => {
  141. stats.reclaimedSize += s.size
  142. return stats
  143. })
  144. })
  145. }
  146. },
  147. { concurrency: opts.concurrency }
  148. ).then(() => stats)
  149. )
  150. })
  151. })
  152. }
  153. function verifyContent (filepath, sri) {
  154. return stat(filepath)
  155. .then((s) => {
  156. const contentInfo = {
  157. size: s.size,
  158. valid: true,
  159. }
  160. return ssri
  161. .checkStream(new fsm.ReadStream(filepath), sri)
  162. .catch((err) => {
  163. if (err.code !== 'EINTEGRITY')
  164. throw err
  165. return rimraf(filepath).then(() => {
  166. contentInfo.valid = false
  167. })
  168. })
  169. .then(() => contentInfo)
  170. })
  171. .catch((err) => {
  172. if (err.code === 'ENOENT')
  173. return { size: 0, valid: false }
  174. throw err
  175. })
  176. }
  177. function rebuildIndex (cache, opts) {
  178. opts.log.silly('verify', 'rebuilding index')
  179. return index.ls(cache).then((entries) => {
  180. const stats = {
  181. missingContent: 0,
  182. rejectedEntries: 0,
  183. totalEntries: 0,
  184. }
  185. const buckets = {}
  186. for (const k in entries) {
  187. /* istanbul ignore else */
  188. if (hasOwnProperty(entries, k)) {
  189. const hashed = index.hashKey(k)
  190. const entry = entries[k]
  191. const excluded = opts.filter && !opts.filter(entry)
  192. excluded && stats.rejectedEntries++
  193. if (buckets[hashed] && !excluded)
  194. buckets[hashed].push(entry)
  195. else if (buckets[hashed] && excluded) {
  196. // skip
  197. } else if (excluded) {
  198. buckets[hashed] = []
  199. buckets[hashed]._path = index.bucketPath(cache, k)
  200. } else {
  201. buckets[hashed] = [entry]
  202. buckets[hashed]._path = index.bucketPath(cache, k)
  203. }
  204. }
  205. }
  206. return pMap(
  207. Object.keys(buckets),
  208. (key) => {
  209. return rebuildBucket(cache, buckets[key], stats, opts)
  210. },
  211. { concurrency: opts.concurrency }
  212. ).then(() => stats)
  213. })
  214. }
  215. function rebuildBucket (cache, bucket, stats, opts) {
  216. return truncate(bucket._path).then(() => {
  217. // This needs to be serialized because cacache explicitly
  218. // lets very racy bucket conflicts clobber each other.
  219. return bucket.reduce((promise, entry) => {
  220. return promise.then(() => {
  221. const content = contentPath(cache, entry.integrity)
  222. return stat(content)
  223. .then(() => {
  224. return index
  225. .insert(cache, entry.key, entry.integrity, {
  226. metadata: entry.metadata,
  227. size: entry.size,
  228. })
  229. .then(() => {
  230. stats.totalEntries++
  231. })
  232. })
  233. .catch((err) => {
  234. if (err.code === 'ENOENT') {
  235. stats.rejectedEntries++
  236. stats.missingContent++
  237. return
  238. }
  239. throw err
  240. })
  241. })
  242. }, Promise.resolve())
  243. })
  244. }
  245. function cleanTmp (cache, opts) {
  246. opts.log.silly('verify', 'cleaning tmp directory')
  247. return rimraf(path.join(cache, 'tmp'))
  248. }
  249. function writeVerifile (cache, opts) {
  250. const verifile = path.join(cache, '_lastverified')
  251. opts.log.silly('verify', 'writing verifile to ' + verifile)
  252. try {
  253. return writeFile(verifile, '' + +new Date())
  254. } finally {
  255. fixOwner.chownr.sync(cache, verifile)
  256. }
  257. }
  258. module.exports.lastRun = lastRun
  259. function lastRun (cache) {
  260. return readFile(path.join(cache, '_lastverified'), 'utf8').then(
  261. (data) => new Date(+data)
  262. )
  263. }