Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improvements to symlinking #48

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ node_modules
.idea
.DS_Store
dist/
.vscode
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ branches:
- master

node_js:
- "10.18"
- 19

jobs:
include:
- stage: build-and-deploy
script:
- npm run build && npm run semantic-release
- npx semantic-release

stages:
- name: build-and-deploy
Expand Down
42 changes: 28 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,34 +24,48 @@ service: service-name
plugins:
- serverless-package-external

ecr:
images:
# Your images here

functions:
# Your functions here

custom:
packageExternal:
external:
- '../common'
- '../service-a/module'
common_utils:
# Optional command to run on the dir you're symlinking
cmd: pip install -r requirements.txt -t .
source: '../common_utils'
# if no functions specified, it will apply it to all
functions:
- service-a
- service-b
api_utils:
source: '../api_utils'
functions:
- service-b
```

#### Example Directory Structure

```
└── common
└── common_utils
└── resource.py
└── api_utils
└── resource.py
└── service-a
└── handler.py
└── serverless.yml
└── module
└── main.py
└── service-b
└── handler.py
└── serverless.yml
└── functions
└── service-a
└── handler.py
└── service-b
└── handler.py
serverless.yml
```

In handler.py, external code can be imported:
In service-b/handler.py, external code can be imported:
```py
from common.resource import shared_resource
from common_utils.resource import shared_resource
from api_utils.resource import shared_resource
```

#### Licensing
Expand Down
106 changes: 48 additions & 58 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,64 @@
'use strict';

const symlink = require('./src/symlink');
const path = require('path');

const fs = require('fs')
const path = require('path')
const cp = require('child_process')

class PackageExternal {
constructor(serverless, options) {
this.serverless = serverless;
this.options = Object.assign({
external: []
}, this.serverless.service.custom && this.serverless.service.custom.packageExternal || {});

this.symlinked = false;

this.commands = {
packageExternal: {
usage: 'create external package symlinks',
lifecycleEvents: ['run'],
commands: {
run: {
usage: 'remove symlinks',
lifecycleEvents: ['init'],
},
},
},
};

constructor(serverless) {
this.serverless = serverless
this.options = this.serverless.service?.custom?.packageExternal || {}
this.hooks = {
'before:package:createDeploymentArtifacts': this.beforeDeploy.bind(this),
'before:deploy:function:packageFunction': this.beforeDeploy.bind(this),
'after:deploy:function:packageFunction': this.afterDeploy.bind(this),
'after:package:createDeploymentArtifacts': this.afterDeploy.bind(this),
"before:offline:start:init": this.beforeDeploy.bind(this),
"before:offline:start": this.beforeDeploy.bind(this),
"before:offline:start:end": this.afterDeploy.bind(this),
"invoke:local:loadEnvVars": this.beforeDeploy.bind(this),
"invoke:local:invoke": this.afterDeploy.bind(this),
"packageExternal:run:init": this.beforeDeploy.bind(this),
};
'before:package:initialize': this.beforePackage.bind(this),
'after:package:finalize': this.afterPackage.bind(this)
}
this.handleExit(['SIGINT', 'SIGTERM', 'SIGQUIT'])
}

applyAction(callback) {
const slsFns = this.serverless.service?.functions || {}
const images = this.serverless.service?.provider?.ecr?.images || {}

this.handleExit();
for (const [externalFolder, { functions, source, cmd }] of Object.entries(this.options)) {
cmd && source && fs.existsSync(source) && cp.execSync(cmd, { cwd: source, env: process.env })
for (const name of functions || Object.keys(slsFns)) {
const slsFn = slsFns[name]
const imagePath = images?.[slsFn?.image?.name]?.path || slsFn?.image?.path
const target = path.join(process.cwd(), imagePath || slsFn?.module || '', externalFolder)
callback({ name, externalFolder, source, target, log: this.serverless.cli.log })
}
}
}

beforeDeploy() {
beforePackage() {
// Symlink external folders
return Promise.all(this.options.external.map(externalFolder => {
this.symlinked = true;
return symlink.createFolder(externalFolder, this.serverless);
}))
.then(() => {
this.serverless.cli.log(`[serverless-package-external] is complete`);
});
this.applyAction(({ name, externalFolder, source, target, log }) => {
const noSource = !fs.existsSync(source)
if (fs.existsSync(target) || noSource) {
const issue = noSource ? `${source} does not exist` : `${target} already exists`
log(`[serverless-package-external] cannot Symlink function: ${name}, ${issue}`)
} else {
// Junction is used on windows so that no administrator privileges are required
fs.symlinkSync(path.join(process.cwd(), source), target, process.platform === 'win32' && 'junction')
log(`[serverless-package-external] Symlinked "${externalFolder}" for function: ${name}`)
}
})
}

afterDeploy() {
if(this.symlinked) {
this.serverless.cli.log(`[serverless-package-external] cleaning up`);
this.options.external.forEach(externalFolder => {
const target = path.basename(externalFolder);
symlink.removeFolder(target);
});
}
afterPackage() {
// Cleanup generated symlinks
this.applyAction(({ name, externalFolder, target, log }) => {
if (fs.existsSync(target) && fs.rmSync(target, { recursive: true, force: true })) {
log(`[serverless-package-external] Cleanup "${externalFolder}" for function: ${name}`)
}
})
}

handleExit(func) {
['SIGINT', 'SIGTERM', 'SIGQUIT']
.forEach(signal => process.on(signal, () => {
this.afterDeploy();
}));
handleExit(signals) {
for (const signal of signals) {
process.on(signal, () => this.afterPackage())
}
}
}

module.exports = PackageExternal;
module.exports = PackageExternal
Loading