|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const nco = require('nco'); |
| 4 | +const semver = require('semver'); |
| 5 | + |
| 6 | +const validRetentionInDays = [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]; |
| 7 | + |
| 8 | +class AwsAddLogRetention { |
| 9 | + constructor(serverless, options) { |
| 10 | + if(!semver.satisfies(serverless.version, '>= 1.20.2')) { |
| 11 | + throw new Error('serverless-plugin-log-retention requires serverless 1.20.2 or higher'); |
| 12 | + } |
| 13 | + |
| 14 | + this.serverless = serverless; |
| 15 | + this.options = options; |
| 16 | + this.provider = this.serverless.getProvider('aws'); |
| 17 | + this.hooks = { |
| 18 | + 'before:deploy:createDeploymentArtifacts': this.beforeDeploy.bind(this), |
| 19 | + }; |
| 20 | + } |
| 21 | + |
| 22 | + sanitizeRetentionValue(inputValue) { |
| 23 | + const value = Number(inputValue); |
| 24 | + if(Number.isInteger(value) && validRetentionInDays.includes(value)) { |
| 25 | + return value; |
| 26 | + } else { |
| 27 | + throw new Error(`RetentionInDays value must be one of ${validRetentionInDays}`); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + addLogRetentionForFunctions(globalLogRetentionInDays) { |
| 32 | + const service = this.serverless.service; |
| 33 | + if(typeof service.functions !== 'object') { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + const resources = nco(service.resources, {}); |
| 38 | + resources.Resources = nco(resources.Resources, {}); |
| 39 | + |
| 40 | + Object.keys(service.functions).forEach(functionName => { |
| 41 | + const localLogRentationInDays = nco(service.functions[functionName].logRetentionInDays, null); |
| 42 | + if(localLogRentationInDays === null && globalLogRetentionInDays === null) { |
| 43 | + return; |
| 44 | + } |
| 45 | + const functionLogRetentionInDays = localLogRentationInDays === null ? globalLogRetentionInDays : sanitizeRetentionValue(localLogRentationInDays); |
| 46 | + const logGroupLogicalId = this.provider.naming.getLogGroupLogicalId(functionName); |
| 47 | + |
| 48 | + const resource = { |
| 49 | + Type: 'AWS::Logs::LogGroup', |
| 50 | + Properties: { |
| 51 | + RetentionInDays: functionLogRetentionInDays |
| 52 | + } |
| 53 | + }; |
| 54 | + resources.Resources[logGroupLogicalId] = resource; |
| 55 | + }); |
| 56 | + } |
| 57 | + |
| 58 | + beforeDeploy() { |
| 59 | + const service = this.serverless.service; |
| 60 | + const globalLogRetentionInDays = service.provider && service.provider.logRetentionInDays |
| 61 | + ? sanitizeRetentionValue(service.provider.logRetentionInDays) |
| 62 | + : null; |
| 63 | + this.addLogRetentionForFunctions(globalLogRetentionInDays); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +module.exports = AwsAddLogRetention; |
0 commit comments