diff --git a/README.md b/README.md index 44674ce..d524828 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ plugins: custom: serverless-layers: packagePath: './myfolder/package.json' + layersDeploymentBucket: "your_layers_bucket" # if not specified will get root deploymentBucket ``` ## Contributing diff --git a/lib/index.js b/lib/index.js index 5399d7c..d5a82a5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -61,7 +61,8 @@ function () { var inboundSettings = (serverless.service.custom || {})['serverless-layers']; var defaultSettings = { compileDir: '.serverless', - packagePath: 'package.json' + packagePath: 'package.json', + layersDeploymentBucket: this.service.provider.deploymentBucket }; this.settings = Object.assign({}, defaultSettings, inboundSettings); var localpackageJson = path.join(process.env.PWD, this.settings.packagePath); @@ -95,11 +96,11 @@ function () { }, { key: "getBucketName", value: function getBucketName() { - if (!this.service.provider.deploymentBucket) { + if (!this.settings.layersDeploymentBucket) { throw new Error('Please, you should specify "deploymentBucket" for this plugin!\n'); } - return this.service.provider.deploymentBucket; + return this.settings.layersDeploymentBucket; } }, { key: "publishLayerVersion", diff --git a/lib/index.js.map b/lib/index.js.map index e55a815..4c90d41 100644 --- a/lib/index.js.map +++ b/lib/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.js"],"names":["BbPromise","require","install","mkdirp","fs","copyFile","path","archiver","MAX_LAYER_MB_SIZE","ServerlessLayers","serverless","options","cacheObject","service","provider","getProvider","region","getRegion","log","bind","main","hooks","then","finalizeDeploy","inboundSettings","custom","defaultSettings","compileDir","packagePath","settings","Object","assign","localpackageJson","join","process","env","PWD","localPackage","e","exit","stage","params","StackName","getStackName","request","Stacks","Outputs","catch","deploymentBucket","Error","getBucketName","bucketName","Content","S3Bucket","S3Key","getBucketLayersPath","LayerName","Description","CompatibleRuntimes","result","LayerVersionArn","console","message","cwd","Promise","resolve","reject","layersDir","oldCwd","zipFileName","getPathZipFileName","output","createWriteStream","zip","create","on","MB","pointer","toFixed","err","chdir","pipe","directory","finalize","Bucket","Key","Body","createReadStream","JSON","parse","toString","serviceStage","getDeploymentPrefix","getOutputs","outputs","logicalId","getOutputLogicalId","find","x","OutputKey","OutputValue","naming","getLambdaLayerOutputLogicalId","layerArn","functions","keys","forEach","funcName","layers","push","resources","outputName","Value","Export","Name","layerName","downloadPackageJson","remotePackage","isDifferent","isDiff","dependencies","getLayerArn","currentLayerARN","relateLayerWithFunctions","installDependencies","uploadPackageJson","createPackageLayer","uploadPackageLayer","publishLayerVersion","version","depsA","depsB","depsKeyA","depsKeyB","isSizeEqual","length","hasDifference","dependence","map","initialCwd","nodeJsDir","sync","copyErr","opts","saveDev","cache","silent","getDependenciesList","installErr","msg","cli","module","exports"],"mappings":";;;;;;;;;;;;;;AAAA,IAAMA,SAAS,GAAGC,OAAO,CAAC,UAAD,CAAzB;;AACA,IAAMC,OAAO,GAAGD,OAAO,CAAC,qBAAD,CAAvB;;AACA,IAAME,MAAM,GAAGF,OAAO,CAAC,QAAD,CAAtB;;AACA,IAAMG,EAAE,GAAGH,OAAO,CAAC,IAAD,CAAlB;;AACA,IAAMI,QAAQ,GAAGJ,OAAO,CAAC,cAAD,CAAxB,C,CAA0C;;;AAC1C,IAAMK,IAAI,GAAGL,OAAO,CAAC,MAAD,CAApB;;AACA,IAAMM,QAAQ,GAAGN,OAAO,CAAC,UAAD,CAAxB;;AAEA,IAAMO,iBAAiB,GAAG,GAA1B;;IAEMC,gB;;;AACJ,4BAAYC,UAAZ,EAAwBC,OAAxB,EAAiC;AAAA;;AAAA;AAC/B,SAAKC,WAAL,GAAmB,EAAnB;AACA,SAAKD,OAAL,GAAeA,OAAf;AACA,SAAKD,UAAL,GAAkBA,UAAlB;AAEA,SAAKG,OAAL,GAAeH,UAAU,CAACG,OAA1B;AACA,SAAKC,QAAL,GAAgBJ,UAAU,CAACK,WAAX,CAAuB,KAAvB,CAAhB;AACA,SAAKJ,OAAL,CAAaK,MAAb,GAAsB,KAAKF,QAAL,CAAcG,SAAd,EAAtB,CAP+B,CAS/B;;AACA,SAAKC,GAAL,GA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ACE,OAAD,EAAa;AACrF,wBAAIA,OAAJ,EAAa,MAAMA,OAAN,CADwE,CAGrF;;AACA5G,oBAAAA,OAAO,CAAC8C,KAAR,CAAc4D,SAAd;AAEA,wBAAMG,IAAI,GAAG;AAAEC,sBAAAA,OAAO,EAAE,KAAX;AAAkBC,sBAAAA,KAAK,EAAE,IAAzB;AAA+BC,sBAAAA,MAAM,EAAE;AAAvC,qBAAb;AAEAhJ,oBAAAA,OAAO,CAAC,MAAI,CAACiJ,mBAAL,EAAD,EAA6BJ,IAA7B,EAAmC,UAACK,UAAD,EAAgB;AACxDlH,sBAAAA,OAAO,CAAC8C,KAAR,CAAc2D,UAAd;AACA,0BAAIS,UAAJ,EAAgB,MAAMA,UAAN;AAChBnF,sBAAAA,OAAO;AACR,qBAJM,CAAP;AAKD,mBAbO,CAAR;AAcD,iBAfM,C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAmBuB,KAAKwD,WAAL,E;;;AAAxBC,gBAAAA,e;AACN5F,gBAAAA,MAAM,CAAC2E,IAAP,CAAY,KAAK5F,OAAL,CAAa2F,SAAzB,EAAoCE,OAApC,CAA4C,UAAAC,QAAQ,EAAI;AACtD,kBAAA,OAAI,CAACzF,GAAL,oBAAqByF,QAArB,uBAA0Ce,eAA1C;AACD,iBAFD;;;;;;;;;;;;;;;;;;wBAKE2B,G,EAAK;AACP,WAAK3I,UAAL,CAAgB4I,GAAhB,CAAoBpI,GAApB,2BAA2CmI,GAA3C;AACD;;;;;AAGHE,MAAM,CAACC,OAAP,GAAiB/I,gBAAjB","sourcesContent":["const BbPromise = require('bluebird');\nconst install = require('npm-install-package');\nconst mkdirp = require('mkdirp');\nconst fs = require('fs');\nconst copyFile = require('fs-copy-file'); // v6.10.3 support\nconst path = require('path');\nconst archiver = require('archiver');\n\nconst MAX_LAYER_MB_SIZE = 250;\n\nclass ServerlessLayers {\n constructor(serverless, options) {\n this.cacheObject = {};\n this.options = options;\n this.serverless = serverless;\n\n this.service = serverless.service;\n this.provider = serverless.getProvider('aws');\n this.options.region = this.provider.getRegion();\n\n // bindings\n this.log = this.log.bind(this);\n this.main = this.main.bind(this);\n\n // hooks\n this.hooks = {\n 'package:initialize': () => BbPromise.bind(this)\n .then(() => this.main()),\n 'aws:info:displayLayers': () => BbPromise.bind(this)\n .then(() => this.finalizeDeploy())\n };\n\n const inboundSettings = (serverless.service.custom || {})[\n 'serverless-layers'\n ];\n const defaultSettings = {\n compileDir: '.serverless',\n packagePath: 'package.json'\n };\n\n this.settings = Object.assign({}, defaultSettings, inboundSettings);\n\n const localpackageJson = path.join(\n process.env.PWD,\n this.settings.packagePath\n );\n\n try {\n this.localPackage = require(localpackageJson);\n } catch (e) {\n this.log(`Error: Can not find ${localpackageJson}!`);\n process.exit(1);\n }\n }\n\n getStackName() {\n return `${this.serverless.service.service}-${this.options.stage}`;\n }\n\n getOutputs() {\n const params = { StackName: this.getStackName() };\n return this.provider.request('CloudFormation', 'describeStacks', params)\n .then(({ Stacks }) => Stacks && Stacks[0].Outputs)\n .catch(() => []);\n }\n\n getBucketName() {\n if (!this.service.provider.deploymentBucket) {\n throw new Error(\n 'Please, you should specify \"deploymentBucket\" for this plugin!\\n'\n );\n }\n return this.service.provider.deploymentBucket;\n }\n\n async publishLayerVersion() {\n const bucketName = await this.getBucketName();\n const params = {\n Content: {\n S3Bucket: bucketName,\n S3Key: `${path.join(this.getBucketLayersPath(), this.getStackName())}.zip`\n },\n LayerName: this.getStackName(),\n Description: 'created by serverless-layers',\n CompatibleRuntimes: ['nodejs']\n };\n return this.provider.request('Lambda', 'publishLayerVersion', params)\n .then((result) => {\n this.log('New layer version published...');\n this.cacheObject.LayerVersionArn = result.LayerVersionArn;\n return result;\n })\n .catch(e => {\n console.log(e.message);\n process.exit(1);\n });\n }\n\n getPathZipFileName() {\n return `${path.join(process.cwd(), this.settings.compileDir, this.getStackName())}.zip`;\n }\n\n createPackageLayer() {\n return new Promise((resolve, reject) => {\n const layersDir = path.join(process.cwd(), this.settings.compileDir);\n const oldCwd = process.cwd();\n const zipFileName = this.getPathZipFileName();\n const output = fs.createWriteStream(zipFileName);\n const zip = archiver.create('zip');\n\n output.on('close', () => {\n const MB = (zip.pointer() / 1024 / 1024).toFixed(1);\n\n if (MB > MAX_LAYER_MB_SIZE) {\n this.log('Package error!');\n throw new Error(\n 'Layers can\\'t exceed the unzipped deployment package size limit of 250 MB! \\n'\n + 'Read more: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html\\n\\n'\n );\n }\n\n this.log(`Created layer package ${zipFileName} (${MB} MB)`);\n resolve();\n });\n\n zip.on('error', (err) => {\n reject(err);\n process.chdir(oldCwd);\n });\n\n process.chdir(layersDir);\n\n zip.pipe(output);\n\n zip.directory('layers', false);\n\n zip.finalize()\n .then(() => {\n process.chdir(oldCwd);\n });\n });\n }\n\n async uploadPackageLayer() {\n this.log('Uploading layer package...');\n\n const bucketName = await this.getBucketName();\n const params = {\n Bucket: bucketName,\n Key: `${path.join(this.getBucketLayersPath(), this.getStackName())}.zip`,\n Body: fs.createReadStream(this.getPathZipFileName())\n };\n\n return this.provider.request('S3', 'putObject', params)\n .then((result) => {\n this.log('OK...');\n return result;\n })\n .catch(e => {\n console.log(e.message);\n process.exit(1);\n });\n }\n\n async uploadPackageJson() {\n this.log('Uploading remote package.json...');\n\n const bucketName = await this.getBucketName();\n const params = {\n Bucket: bucketName,\n Key: path.join(this.getBucketLayersPath(), 'package.json'),\n Body: fs.createReadStream(this.settings.packagePath)\n };\n return this.provider.request('S3', 'putObject', params)\n .then((result) => {\n this.log('OK...');\n return result;\n })\n .catch(e => {\n console.log(e.message);\n process.exit(1);\n });\n }\n\n async downloadPackageJson() {\n this.log('Downloading package.json from bucket...');\n const bucketName = await this.getBucketName();\n const params = {\n Bucket: bucketName,\n Key: path.join(this.getBucketLayersPath(), 'package.json')\n };\n return this.provider.request('S3', 'getObject', params)\n .then((result) => JSON.parse(result.Body.toString()))\n .catch(() => {\n this.log('package.json does not exists at bucket...');\n return null;\n });\n }\n\n getBucketLayersPath() {\n const serviceStage = `${this.serverless.service.service}/${this.options.stage}`;\n return path.join(\n this.provider.getDeploymentPrefix(),\n serviceStage,\n 'layers'\n );\n }\n\n async getLayerArn() {\n if (this.cacheObject.LayerVersionArn) {\n return this.cacheObject.LayerVersionArn;\n }\n const outputs = await this.getOutputs();\n if (!outputs) return null;\n const logicalId = this.getOutputLogicalId();\n return (outputs.find(x => x.OutputKey === logicalId) || {}).OutputValue;\n }\n\n getOutputLogicalId() {\n return this.provider.naming.getLambdaLayerOutputLogicalId(this.getStackName());\n }\n\n relateLayerWithFunctions(layerArn) {\n this.log('Associating layers...');\n\n const { functions } = this.service;\n\n Object.keys(functions).forEach(funcName => {\n functions[funcName].layers = functions[funcName].layers || [];\n functions[funcName].layers.push(layerArn);\n this.log(`function.${funcName} - ${layerArn}`);\n });\n\n this.service.resources = this.service.resources || {};\n this.service.resources.Outputs = this.service.resources.Outputs || {};\n\n const outputName = this.getOutputLogicalId();\n Object.assign(this.service.resources.Outputs, {\n [outputName]: {\n Value: layerArn,\n Export: {\n Name: outputName\n }\n }\n });\n }\n\n async main() {\n this.settings.layerName = this.settings.layerName || this.serverless.service.service;\n\n const remotePackage = await this.downloadPackageJson();\n\n let isDifferent = true;\n if (remotePackage) {\n this.log('Comparing package.json dependencies...');\n isDifferent = await this.isDiff(remotePackage.dependencies, this.localPackage.dependencies);\n }\n\n const currentLayerARN = await this.getLayerArn();\n\n if (!isDifferent && currentLayerARN) {\n this.log(`Not has changed! Using same layer arn: ${currentLayerARN}`);\n this.relateLayerWithFunctions(currentLayerARN);\n return;\n }\n\n await this.installDependencies();\n await this.uploadPackageJson();\n await this.createPackageLayer();\n await this.uploadPackageLayer();\n const version = await this.publishLayerVersion();\n\n this.relateLayerWithFunctions(version.LayerVersionArn);\n }\n\n isDiff(depsA, depsB) {\n const depsKeyA = Object.keys(depsA);\n const depsKeyB = Object.keys(depsB);\n const isSizeEqual = depsKeyA.length === depsKeyB.length;\n\n if (!isSizeEqual) return true;\n\n let hasDifference = false;\n Object.keys(depsA).forEach(dependence => {\n if (depsA[dependence] !== depsB[dependence]) {\n hasDifference = true;\n }\n });\n\n return hasDifference;\n }\n\n getDependenciesList() {\n return Object.keys(this.localPackage.dependencies).map(x => (\n `${x}@${this.localPackage.dependencies[x]}`\n ));\n }\n\n async installDependencies() {\n this.log('Dependencies has changed! Re-installing...');\n\n const initialCwd = process.cwd();\n const nodeJsDir = path.join(process.cwd(), this.settings.compileDir, 'layers', 'nodejs');\n\n await mkdirp.sync(nodeJsDir);\n\n return new Promise((resolve) => {\n copyFile(this.settings.packagePath, path.join(nodeJsDir, 'package.json'), (copyErr) => {\n if (copyErr) throw copyErr;\n\n // install deps\n process.chdir(nodeJsDir);\n\n const opts = { saveDev: false, cache: true, silent: false };\n\n install(this.getDependenciesList(), opts, (installErr) => {\n process.chdir(initialCwd);\n if (installErr) throw installErr;\n resolve();\n });\n });\n });\n }\n\n async finalizeDeploy() {\n const currentLayerARN = await this.getLayerArn();\n Object.keys(this.service.functions).forEach(funcName => {\n this.log(`function.${funcName} = layers.${currentLayerARN}`);\n });\n }\n\n log(msg) {\n this.serverless.cli.log(`[LayersPlugin]: ${msg}`);\n }\n}\n\nmodule.exports = ServerlessLayers;\n"],"file":"index.js"} \ No newline at end of file +{"version":3,"sources":["../src/index.js"],"names":["BbPromise","require","install","mkdirp","fs","copyFile","path","archiver","MAX_LAYER_MB_SIZE","ServerlessLayers","serverless","options","cacheObject","service","provider","getProvider","region","getRegion","log","bind","main","hooks","then","finalizeDeploy","inboundSettings","custom","defaultSettings","compileDir","packagePath","layersDeploymentBucket","deploymentBucket","settings","Object","assign","localpackageJson","join","process","env","PWD","localPackage","e","exit","stage","params","StackName","getStackName","request","Stacks","Outputs","catch","Error","getBucketName","bucketName","Content","S3Bucket","S3Key","getBucketLayersPath","LayerName","Description","CompatibleRuntimes","result","LayerVersionArn","console","message","cwd","Promise","resolve","reject","layersDir","oldCwd","zipFileName","getPathZipFileName","output","createWriteStream","zip","create","on","MB","pointer","toFixed","err","chdir","pipe","directory","finalize","Bucket","Key","Body","createReadStream","JSON","parse","toString","serviceStage","getDeploymentPrefix","getOutputs","outputs","logicalId","getOutputLogicalId","find","x","OutputKey","OutputValue","naming","getLambdaLayerOutputLogicalId","layerArn","functions","keys","forEach","funcName","layers","push","resources","outputName","Value","Export","Name","layerName","downloadPackageJson","remotePackage","isDifferent","isDiff","dependencies","getLayerArn","currentLayerARN","relateLayerWithFunctions","installDependencies","uploadPackageJson","createPackageLayer","uploadPackageLayer","publishLayerVersion","version","depsA","depsB","depsKeyA","depsKeyB","isSizeEqual","length","hasDifference","dependence","map","initialCwd","nodeJsDir","sync","copyErr","opts","saveDev","cache","silent","getDependenciesList","installErr","msg","cli","module","exports"],"mappings":";;;;;;;;;;;;;;AAAA,IAAMA,SAAS,GAAGC,OAAO,CAAC,UAAD,CAAzB;;AACA,IAAMC,OAAO,GAAGD,OAAO,CAAC,qBAAD,CAAvB;;AACA,IAAME,MAAM,GAAGF,OAAO,CAAC,QAAD,CAAtB;;AACA,IAAMG,EAAE,GAAGH,OAAO,CAAC,IAAD,CAAlB;;AACA,IAAMI,QAAQ,GAAGJ,OAAO,CAAC,cAAD,CAAxB,C,CAA0C;;;AAC1C,IAAMK,IAAI,GAAGL,OAAO,CAAC,MAAD,CAApB;;AACA,IAAMM,QAAQ,GAAGN,OAAO,CAAC,UAAD,CAAxB;;AAEA,IAAMO,iBAAiB,GAAG,GAA1B;;IAEMC,gB;;;AACJ,4BAAYC,UAAZ,EAAwBC,OAAxB,EAAiC;AAAA;;AAAA;AAC/B,SAAKC,WAAL,GAAmB,EAAnB;AACA,SAAKD,OAAL,GAAeA,OAAf;AACA,SAAKD,UAAL,GAAkBA,UAAlB;AAEA,SAAKG,OAAL,GAAeH,UAAU,CAACG,OAA1B;AACA,SAAKC,QAAL,GAAgBJ,UAAU,CAACK,WAAX,CAAuB,KAAvB,CAAhB;AACA,SAAKJ,OAAL,CAA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kBAAAA,QAAQ,CAAC,MAAI,CAAC0B,QAAL,CAAcH,WAAf,EAA4BtB,IAAI,CAAC6B,IAAL,CAAU0G,SAAV,EAAqB,cAArB,CAA5B,EAAkE,UAACE,OAAD,EAAa;AACrF,wBAAIA,OAAJ,EAAa,MAAMA,OAAN,CADwE,CAGrF;;AACA3G,oBAAAA,OAAO,CAAC6C,KAAR,CAAc4D,SAAd;AAEA,wBAAMG,IAAI,GAAG;AAAEC,sBAAAA,OAAO,EAAE,KAAX;AAAkBC,sBAAAA,KAAK,EAAE,IAAzB;AAA+BC,sBAAAA,MAAM,EAAE;AAAvC,qBAAb;AAEAjJ,oBAAAA,OAAO,CAAC,MAAI,CAACkJ,mBAAL,EAAD,EAA6BJ,IAA7B,EAAmC,UAACK,UAAD,EAAgB;AACxDjH,sBAAAA,OAAO,CAAC6C,KAAR,CAAc2D,UAAd;AACA,0BAAIS,UAAJ,EAAgB,MAAMA,UAAN;AAChBnF,sBAAAA,OAAO;AACR,qBAJM,CAAP;AAKD,mBAbO,CAAR;AAcD,iBAfM,C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAmBuB,KAAKwD,WAAL,E;;;AAAxBC,gBAAAA,e;AACN3F,gBAAAA,MAAM,CAAC0E,IAAP,CAAY,KAAK7F,OAAL,CAAa4F,SAAzB,EAAoCE,OAApC,CAA4C,UAAAC,QAAQ,EAAI;AACtD,kBAAA,OAAI,CAAC1F,GAAL,oBAAqB0F,QAArB,uBAA0Ce,eAA1C;AACD,iBAFD;;;;;;;;;;;;;;;;;;wBAKE2B,G,EAAK;AACP,WAAK5I,UAAL,CAAgB6I,GAAhB,CAAoBrI,GAApB,2BAA2CoI,GAA3C;AACD;;;;;AAGHE,MAAM,CAACC,OAAP,GAAiBhJ,gBAAjB","sourcesContent":["const BbPromise = require('bluebird');\nconst install = require('npm-install-package');\nconst mkdirp = require('mkdirp');\nconst fs = require('fs');\nconst copyFile = require('fs-copy-file'); // v6.10.3 support\nconst path = require('path');\nconst archiver = require('archiver');\n\nconst MAX_LAYER_MB_SIZE = 250;\n\nclass ServerlessLayers {\n constructor(serverless, options) {\n this.cacheObject = {};\n this.options = options;\n this.serverless = serverless;\n\n this.service = serverless.service;\n this.provider = serverless.getProvider('aws');\n this.options.region = this.provider.getRegion();\n\n // bindings\n this.log = this.log.bind(this);\n this.main = this.main.bind(this);\n\n // hooks\n this.hooks = {\n 'package:initialize': () => BbPromise.bind(this)\n .then(() => this.main()),\n 'aws:info:displayLayers': () => BbPromise.bind(this)\n .then(() => this.finalizeDeploy())\n };\n\n const inboundSettings = (serverless.service.custom || {})[\n 'serverless-layers'\n ];\n const defaultSettings = {\n compileDir: '.serverless',\n packagePath: 'package.json',\n layersDeploymentBucket: this.service.provider.deploymentBucket\n };\n\n this.settings = Object.assign({}, defaultSettings, inboundSettings);\n\n const localpackageJson = path.join(\n process.env.PWD,\n this.settings.packagePath\n );\n\n try {\n this.localPackage = require(localpackageJson);\n } catch (e) {\n this.log(`Error: Can not find ${localpackageJson}!`);\n process.exit(1);\n }\n }\n\n getStackName() {\n return `${this.serverless.service.service}-${this.options.stage}`;\n }\n\n getOutputs() {\n const params = { StackName: this.getStackName() };\n return this.provider.request('CloudFormation', 'describeStacks', params)\n .then(({ Stacks }) => Stacks && Stacks[0].Outputs)\n .catch(() => []);\n }\n\n getBucketName() {\n if (!this.settings.layersDeploymentBucket) {\n throw new Error(\n 'Please, you should specify \"deploymentBucket\" for this plugin!\\n'\n );\n }\n return this.settings.layersDeploymentBucket;\n }\n\n async publishLayerVersion() {\n const bucketName = await this.getBucketName();\n const params = {\n Content: {\n S3Bucket: bucketName,\n S3Key: `${path.join(this.getBucketLayersPath(), this.getStackName())}.zip`\n },\n LayerName: this.getStackName(),\n Description: 'created by serverless-layers',\n CompatibleRuntimes: ['nodejs']\n };\n return this.provider.request('Lambda', 'publishLayerVersion', params)\n .then((result) => {\n this.log('New layer version published...');\n this.cacheObject.LayerVersionArn = result.LayerVersionArn;\n return result;\n })\n .catch(e => {\n console.log(e.message);\n process.exit(1);\n });\n }\n\n getPathZipFileName() {\n return `${path.join(process.cwd(), this.settings.compileDir, this.getStackName())}.zip`;\n }\n\n createPackageLayer() {\n return new Promise((resolve, reject) => {\n const layersDir = path.join(process.cwd(), this.settings.compileDir);\n const oldCwd = process.cwd();\n const zipFileName = this.getPathZipFileName();\n const output = fs.createWriteStream(zipFileName);\n const zip = archiver.create('zip');\n\n output.on('close', () => {\n const MB = (zip.pointer() / 1024 / 1024).toFixed(1);\n\n if (MB > MAX_LAYER_MB_SIZE) {\n this.log('Package error!');\n throw new Error(\n 'Layers can\\'t exceed the unzipped deployment package size limit of 250 MB! \\n'\n + 'Read more: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html\\n\\n'\n );\n }\n\n this.log(`Created layer package ${zipFileName} (${MB} MB)`);\n resolve();\n });\n\n zip.on('error', (err) => {\n reject(err);\n process.chdir(oldCwd);\n });\n\n process.chdir(layersDir);\n\n zip.pipe(output);\n\n zip.directory('layers', false);\n\n zip.finalize()\n .then(() => {\n process.chdir(oldCwd);\n });\n });\n }\n\n async uploadPackageLayer() {\n this.log('Uploading layer package...');\n\n const bucketName = await this.getBucketName();\n const params = {\n Bucket: bucketName,\n Key: `${path.join(this.getBucketLayersPath(), this.getStackName())}.zip`,\n Body: fs.createReadStream(this.getPathZipFileName())\n };\n\n return this.provider.request('S3', 'putObject', params)\n .then((result) => {\n this.log('OK...');\n return result;\n })\n .catch(e => {\n console.log(e.message);\n process.exit(1);\n });\n }\n\n async uploadPackageJson() {\n this.log('Uploading remote package.json...');\n\n const bucketName = await this.getBucketName();\n const params = {\n Bucket: bucketName,\n Key: path.join(this.getBucketLayersPath(), 'package.json'),\n Body: fs.createReadStream(this.settings.packagePath)\n };\n return this.provider.request('S3', 'putObject', params)\n .then((result) => {\n this.log('OK...');\n return result;\n })\n .catch(e => {\n console.log(e.message);\n process.exit(1);\n });\n }\n\n async downloadPackageJson() {\n this.log('Downloading package.json from bucket...');\n const bucketName = await this.getBucketName();\n const params = {\n Bucket: bucketName,\n Key: path.join(this.getBucketLayersPath(), 'package.json')\n };\n return this.provider.request('S3', 'getObject', params)\n .then((result) => JSON.parse(result.Body.toString()))\n .catch(() => {\n this.log('package.json does not exists at bucket...');\n return null;\n });\n }\n\n getBucketLayersPath() {\n const serviceStage = `${this.serverless.service.service}/${this.options.stage}`;\n return path.join(\n this.provider.getDeploymentPrefix(),\n serviceStage,\n 'layers'\n );\n }\n\n async getLayerArn() {\n if (this.cacheObject.LayerVersionArn) {\n return this.cacheObject.LayerVersionArn;\n }\n const outputs = await this.getOutputs();\n if (!outputs) return null;\n const logicalId = this.getOutputLogicalId();\n return (outputs.find(x => x.OutputKey === logicalId) || {}).OutputValue;\n }\n\n getOutputLogicalId() {\n return this.provider.naming.getLambdaLayerOutputLogicalId(this.getStackName());\n }\n\n relateLayerWithFunctions(layerArn) {\n this.log('Associating layers...');\n\n const { functions } = this.service;\n\n Object.keys(functions).forEach(funcName => {\n functions[funcName].layers = functions[funcName].layers || [];\n functions[funcName].layers.push(layerArn);\n this.log(`function.${funcName} - ${layerArn}`);\n });\n\n this.service.resources = this.service.resources || {};\n this.service.resources.Outputs = this.service.resources.Outputs || {};\n\n const outputName = this.getOutputLogicalId();\n Object.assign(this.service.resources.Outputs, {\n [outputName]: {\n Value: layerArn,\n Export: {\n Name: outputName\n }\n }\n });\n }\n\n async main() {\n this.settings.layerName = this.settings.layerName || this.serverless.service.service;\n\n const remotePackage = await this.downloadPackageJson();\n\n let isDifferent = true;\n if (remotePackage) {\n this.log('Comparing package.json dependencies...');\n isDifferent = await this.isDiff(remotePackage.dependencies, this.localPackage.dependencies);\n }\n\n const currentLayerARN = await this.getLayerArn();\n\n if (!isDifferent && currentLayerARN) {\n this.log(`Not has changed! Using same layer arn: ${currentLayerARN}`);\n this.relateLayerWithFunctions(currentLayerARN);\n return;\n }\n\n await this.installDependencies();\n await this.uploadPackageJson();\n await this.createPackageLayer();\n await this.uploadPackageLayer();\n const version = await this.publishLayerVersion();\n\n this.relateLayerWithFunctions(version.LayerVersionArn);\n }\n\n isDiff(depsA, depsB) {\n const depsKeyA = Object.keys(depsA);\n const depsKeyB = Object.keys(depsB);\n const isSizeEqual = depsKeyA.length === depsKeyB.length;\n\n if (!isSizeEqual) return true;\n\n let hasDifference = false;\n Object.keys(depsA).forEach(dependence => {\n if (depsA[dependence] !== depsB[dependence]) {\n hasDifference = true;\n }\n });\n\n return hasDifference;\n }\n\n getDependenciesList() {\n return Object.keys(this.localPackage.dependencies).map(x => (\n `${x}@${this.localPackage.dependencies[x]}`\n ));\n }\n\n async installDependencies() {\n this.log('Dependencies has changed! Re-installing...');\n\n const initialCwd = process.cwd();\n const nodeJsDir = path.join(process.cwd(), this.settings.compileDir, 'layers', 'nodejs');\n\n await mkdirp.sync(nodeJsDir);\n\n return new Promise((resolve) => {\n copyFile(this.settings.packagePath, path.join(nodeJsDir, 'package.json'), (copyErr) => {\n if (copyErr) throw copyErr;\n\n // install deps\n process.chdir(nodeJsDir);\n\n const opts = { saveDev: false, cache: true, silent: false };\n\n install(this.getDependenciesList(), opts, (installErr) => {\n process.chdir(initialCwd);\n if (installErr) throw installErr;\n resolve();\n });\n });\n });\n }\n\n async finalizeDeploy() {\n const currentLayerARN = await this.getLayerArn();\n Object.keys(this.service.functions).forEach(funcName => {\n this.log(`function.${funcName} = layers.${currentLayerARN}`);\n });\n }\n\n log(msg) {\n this.serverless.cli.log(`[LayersPlugin]: ${msg}`);\n }\n}\n\nmodule.exports = ServerlessLayers;\n"],"file":"index.js"} \ No newline at end of file diff --git a/src/index.js b/src/index.js index 9cc8d6e..b1fa67c 100644 --- a/src/index.js +++ b/src/index.js @@ -35,7 +35,8 @@ class ServerlessLayers { ]; const defaultSettings = { compileDir: '.serverless', - packagePath: 'package.json' + packagePath: 'package.json', + layersDeploymentBucket: this.service.provider.deploymentBucket }; this.settings = Object.assign({}, defaultSettings, inboundSettings); @@ -65,12 +66,12 @@ class ServerlessLayers { } getBucketName() { - if (!this.service.provider.deploymentBucket) { + if (!this.settings.layersDeploymentBucket) { throw new Error( 'Please, you should specify "deploymentBucket" for this plugin!\n' ); } - return this.service.provider.deploymentBucket; + return this.settings.layersDeploymentBucket; } async publishLayerVersion() {