unpkg/server/IngestLogsWorker.js

273 lines
8.4 KiB
JavaScript
Raw Normal View History

2017-05-20 05:41:24 +00:00
const parseURL = require('url').parse
const invariant = require('invariant')
const gunzip = require('gunzip-maybe')
const ndjson = require('ndjson')
2017-05-29 05:41:01 +00:00
const startOfDay = require('date-fns/start_of_day')
const addDays = require('date-fns/add_days')
const PackageURL = require('./PackageURL')
2017-08-16 17:31:34 +00:00
const cf = require('./CloudflareAPI')
const db = require('./RedisClient')
2017-05-29 05:41:01 +00:00
const {
createDayKey,
createHourKey
} = require('./StatsServer')
2017-05-20 05:41:24 +00:00
2017-05-23 22:00:09 +00:00
/**
* Domains we want to analyze.
*/
const DomainNames = [
'unpkg.com'
2017-05-24 23:51:03 +00:00
//'npmcdn.com' // We don't have log data on npmcdn.com yet :/
2017-05-23 22:00:09 +00:00
]
/**
* The window of time to download in a single fetch.
*/
const LogWindowSeconds = 30
function getZones(domain) {
2017-08-16 17:31:34 +00:00
return cf.getJSON(`/zones?name=${domain}`)
}
2017-05-20 05:41:24 +00:00
function getLogs(zoneId, startTime, endTime) {
2017-08-16 17:31:34 +00:00
return cf.get(
`/zones/${zoneId}/logs/requests?start=${startTime}&end=${endTime}`,
{ 'Accept-Encoding': 'gzip' }
).then(function (res) {
return res.body.pipe(gunzip())
})
}
2017-05-20 05:41:24 +00:00
function toSeconds(millis) {
return Math.floor(millis / 1000)
}
2017-05-20 05:41:24 +00:00
function stringifySeconds(seconds) {
return new Date(seconds * 1000).toISOString()
}
2017-05-20 05:41:24 +00:00
function getPackageName(pathname) {
const parsed = PackageURL.parse(pathname)
return parsed && parsed.packageName
2017-05-20 05:41:24 +00:00
}
const oneSecond = 1000
const oneMinute = oneSecond * 60
const oneHour = oneMinute * 60
function getSeconds(date) {
return Math.floor(date.getTime() / 1000)
}
2017-05-29 05:41:01 +00:00
function computeCounters(stream) {
return new Promise(function (resolve, reject) {
const counters = {}
2017-05-29 05:41:01 +00:00
const expireat = {}
function incrCounter(counterName, by = 1) {
2017-05-24 19:25:08 +00:00
counters[counterName] = (counters[counterName] || 0) + by
}
2017-05-23 22:00:09 +00:00
function incrCounterMember(counterName, member, by = 1) {
2017-05-24 19:25:08 +00:00
counters[counterName] = counters[counterName] || {}
counters[counterName][member] = (counters[counterName][member] || 0) + by
}
2017-05-23 22:00:09 +00:00
stream
.pipe(ndjson.parse())
.on('error', reject)
.on('data', function (entry) {
2017-05-23 22:00:09 +00:00
const date = new Date(Math.round(entry.timestamp / 1000000))
2017-05-29 05:41:01 +00:00
const nextDay = startOfDay(addDays(date, 1))
const thirtyDaysLater = getSeconds(addDays(nextDay, 30))
2017-05-23 22:00:09 +00:00
2017-05-29 05:41:01 +00:00
const dayKey = createDayKey(date)
const hourKey = createHourKey(date)
2017-05-23 22:00:09 +00:00
// Q: How many requests are served by origin/cache/edge per day/hour?
2017-05-23 22:00:09 +00:00
if (entry.origin) {
2017-05-24 19:25:08 +00:00
incrCounter(`stats-originRequests-${dayKey}`)
2017-05-29 05:41:01 +00:00
expireat[`stats-originRequests-${dayKey}`] = thirtyDaysLater
2017-05-24 19:25:08 +00:00
incrCounter(`stats-originRequests-${hourKey}`)
2017-05-29 05:41:01 +00:00
expireat[`stats-originRequests-${hourKey}`] = thirtyDaysLater
2017-05-23 22:00:09 +00:00
} else if (entry.cache) {
2017-05-24 19:25:08 +00:00
incrCounter(`stats-cacheRequests-${dayKey}`)
2017-05-29 05:41:01 +00:00
expireat[`stats-cacheRequests-${dayKey}`] = thirtyDaysLater
2017-05-24 19:25:08 +00:00
incrCounter(`stats-cacheRequests-${hourKey}`)
2017-05-29 05:41:01 +00:00
expireat[`stats-cacheRequests-${hourKey}`] = thirtyDaysLater
2017-05-23 22:00:09 +00:00
} else {
2017-05-24 19:25:08 +00:00
incrCounter(`stats-edgeRequests-${dayKey}`)
2017-05-29 05:41:01 +00:00
expireat[`stats-edgeRequests-${dayKey}`] = thirtyDaysLater
2017-05-24 19:25:08 +00:00
incrCounter(`stats-edgeRequests-${hourKey}`)
2017-05-29 05:41:01 +00:00
expireat[`stats-edgeRequests-${hourKey}`] = thirtyDaysLater
2017-05-23 22:00:09 +00:00
}
const clientRequest = entry.clientRequest
const edgeResponse = entry.edgeResponse
2017-05-23 22:00:09 +00:00
// Q: How many requests do we receive for a package per day?
// Q: How many bytes do we serve for a package per day?
2017-05-23 22:00:09 +00:00
const uri = clientRequest.uri
const package = getPackageName(parseURL(uri).pathname)
if (package) {
2017-05-24 19:25:08 +00:00
incrCounterMember(`stats-packageRequests-${dayKey}`, package)
2017-05-29 05:41:01 +00:00
expireat[`stats-packageRequests-${dayKey}`] = thirtyDaysLater
2017-05-24 19:25:08 +00:00
incrCounterMember(`stats-packageBytes-${dayKey}`, package, edgeResponse.bytes)
2017-05-29 05:41:01 +00:00
expireat[`stats-packageBytes-${dayKey}`] = thirtyDaysLater
}
2017-05-23 22:00:09 +00:00
// Q: How many requests per day do we receive via each protocol?
const protocol = clientRequest.httpProtocol
2017-05-29 05:41:01 +00:00
if (protocol) {
2017-05-24 19:25:08 +00:00
incrCounterMember(`stats-protocolRequests-${dayKey}`, protocol)
2017-05-29 05:41:01 +00:00
expireat[`stats-protocolRequests-${dayKey}`] = thirtyDaysLater
}
2017-05-23 22:00:09 +00:00
// Q: How many requests do we receive from a hostname per day?
// Q: How many bytes do we serve to a hostname per day?
2017-05-23 22:00:09 +00:00
const referer = clientRequest.referer
2017-05-23 23:06:49 +00:00
const hostname = referer && parseURL(referer).hostname
2017-05-23 22:00:09 +00:00
if (hostname) {
2017-05-24 19:25:08 +00:00
incrCounterMember(`stats-hostnameRequests-${dayKey}`, hostname)
2017-05-29 05:41:01 +00:00
expireat[`stats-hostnameRequests-${dayKey}`] = thirtyDaysLater
2017-05-24 19:25:08 +00:00
incrCounterMember(`stats-hostnameBytes-${dayKey}`, hostname, edgeResponse.bytes)
2017-05-29 05:41:01 +00:00
expireat[`stats-hostnameBytes-${dayKey}`] = thirtyDaysLater
}
2017-05-23 22:00:09 +00:00
})
.on('end', function () {
2017-05-29 05:41:01 +00:00
resolve({ counters, expireat })
2017-05-23 22:00:09 +00:00
})
})
}
2017-05-23 22:00:09 +00:00
function processLogs(stream) {
return computeCounters(stream).then(function ({ counters, expireat }) {
Object.keys(counters).forEach(function (key) {
const value = counters[key]
if (typeof value === 'number') {
// Simple counter.
db.incrby(key, value)
} else {
// Sorted set.
Object.keys(value).forEach(function (member) {
db.zincrby(key, value[member], member)
})
}
2017-05-29 05:41:01 +00:00
if (expireat[key])
db.expireat(key, expireat[key])
2017-05-23 22:00:09 +00:00
})
})
}
2017-05-23 22:00:09 +00:00
function ingestLogs(zone, startSeconds, endSeconds) {
return new Promise(function (resolve) {
2017-05-20 05:41:24 +00:00
console.log(
2017-08-12 16:17:35 +00:00
'info: Started ingesting logs for %s from %s to %s',
2017-05-20 05:41:24 +00:00
zone.name,
stringifySeconds(startSeconds),
stringifySeconds(endSeconds)
)
const startFetchTime = Date.now()
2017-05-23 22:00:09 +00:00
resolve(
getLogs(zone.id, startSeconds, endSeconds).then(function (stream) {
2017-05-23 22:00:09 +00:00
const endFetchTime = Date.now()
2017-05-20 05:41:24 +00:00
2017-05-23 22:00:09 +00:00
console.log(
2017-08-12 16:17:35 +00:00
'info: Fetched %ds worth of logs for %s in %dms',
2017-05-23 22:00:09 +00:00
endSeconds - startSeconds,
zone.name,
endFetchTime - startFetchTime
)
2017-05-20 05:41:24 +00:00
2017-05-23 22:00:09 +00:00
const startProcessTime = Date.now()
2017-05-20 05:41:24 +00:00
return processLogs(stream).then(function () {
2017-05-23 22:00:09 +00:00
const endProcessTime = Date.now()
2017-05-20 05:41:24 +00:00
console.log(
2017-08-12 16:17:35 +00:00
'info: Processed %ds worth of logs for %s in %dms',
2017-05-23 22:00:09 +00:00
endSeconds - startSeconds,
2017-05-20 05:41:24 +00:00
zone.name,
2017-05-23 22:00:09 +00:00
endProcessTime - startProcessTime
2017-05-20 05:41:24 +00:00
)
})
2017-05-23 22:00:09 +00:00
})
)
2017-05-20 05:41:24 +00:00
})
}
2017-05-20 05:41:24 +00:00
function startZone(zone) {
const startSecondsKey = `ingestLogsWorker-nextStartSeconds-${zone.name.replace('.', '-')}`
2017-05-20 05:41:24 +00:00
function takeATurn() {
db.get(startSecondsKey, function (error, value) {
let startSeconds = value && parseInt(value, 10)
2017-05-20 05:41:24 +00:00
const now = Date.now()
// Cloudflare keeps logs around for 72 hours.
2017-05-23 22:00:09 +00:00
// https://support.cloudflare.com/hc/en-us/articles/216672448-Enterprise-Log-Share-REST-API
2017-05-20 05:41:24 +00:00
const minSeconds = toSeconds(now - oneHour * 72)
if (startSeconds == null) {
startSeconds = minSeconds
} else if (startSeconds < minSeconds) {
console.warn(
2017-08-12 16:17:35 +00:00
'warning: Dropped logs for %s from %s to %s!',
2017-05-20 05:41:24 +00:00
zone.name,
stringifySeconds(startSeconds),
stringifySeconds(minSeconds)
)
startSeconds = minSeconds
}
2017-05-23 22:00:09 +00:00
// The log for a request is typically available within thirty (30) minutes
// of the request taking place under normal conditions. We deliver logs
// ordered by the time that the logs were created, i.e. the timestamp of
// the request when it was received by the edge. Given the order of
// delivery, we recommend waiting a full thirty minutes to ingest a full
// set of logs. This will help ensure that any congestion in the log
// pipeline has passed and a full set of logs can be ingested.
// https://support.cloudflare.com/hc/en-us/articles/216672448-Enterprise-Log-Share-REST-API
const maxSeconds = toSeconds(now - (oneMinute * 30))
2017-05-23 22:00:09 +00:00
if (startSeconds < maxSeconds) {
const endSeconds = startSeconds + LogWindowSeconds
2017-05-20 05:41:24 +00:00
ingestLogs(zone, startSeconds, endSeconds).then(function () {
db.set(startSecondsKey, endSeconds)
2017-05-23 22:00:09 +00:00
setTimeout(takeATurn)
}, function (error) {
2017-05-23 22:00:09 +00:00
console.error(error.stack)
process.exit(1)
2017-05-20 05:41:24 +00:00
})
} else {
2017-05-23 22:00:09 +00:00
setTimeout(takeATurn, (startSeconds - maxSeconds) * 1000)
2017-05-20 05:41:24 +00:00
}
})
}
takeATurn()
}
Promise.all(DomainNames.map(getZones)).then(function (results) {
const zones = results.reduce(function (memo, zones) {
return memo.concat(zones)
})
2017-05-23 22:00:09 +00:00
zones.forEach(startZone)
2017-05-20 05:41:24 +00:00
})