verify.js 6.7 KB

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