-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
229 lines (206 loc) · 6.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
const util = require("util");
const exec = util.promisify(require("child_process").exec);
const merge = require("lodash.merge");
const pMap = require("p-map");
const os = require("os");
const prettyHrtime = require("pretty-hrtime");
const chalk = require("chalk");
const path = require("path");
const AdmZip = require("adm-zip");
const glob = require("glob");
const { readFileSync } = require("fs");
const ConfigDefaults = {
baseDir: ".",
binDir: ".bin",
cgo: 0,
cmd: 'GOOS=linux go build -ldflags="-s -w"',
monorepo: false,
supportedRuntimes: ["go1.x"],
buildProvidedRuntimeAsBootstrap: false,
};
// amazonProvidedRuntimes contains Amazon Linux runtimes. Update this array after each new version release.
const amazonProvidedRuntimes = ["provided.al2", "provided.al2023"];
module.exports = class Plugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options || {};
this.isInvoking = false;
this.hooks = {
"before:deploy:function:packageFunction": this.compileFunction.bind(this),
"before:package:createDeploymentArtifacts": this.compileFunctions.bind(
this
),
// Because of https://github.com/serverless/serverless/blob/master/lib/plugins/aws/invokeLocal/index.js#L361
// plugin needs to compile a function and then ignore packaging.
"before:invoke:local:invoke": this.compileFunctionAndIgnorePackage.bind(
this
),
"go:build:build": this.compileFunctions.bind(this),
};
this.commands = {
go: {
usage: "Manage Go functions",
lifecycleEvents: ["go"],
commands: {
build: {
usage: "Build all Go functions",
lifecycleEvents: ["build"],
},
},
},
};
}
async compileFunction() {
const name = this.options.function;
const func = this.serverless.service.functions[this.options.function];
const timeStart = process.hrtime();
await this.compile(name, func);
const timeEnd = process.hrtime(timeStart);
this.serverless.cli.consoleLog(
`Go Plugin: ${chalk.yellow(
`Compilation time (${name}): ${prettyHrtime(timeEnd)}`
)}`
);
}
async compileFunctions() {
if (this.isInvoking) {
return;
}
let names = Object.keys(this.serverless.service.functions);
const timeStart = process.hrtime();
await pMap(
names,
async (name) => {
const func = this.serverless.service.functions[name];
await this.compile(name, func);
},
{ concurrency: os.cpus().length }
);
const timeEnd = process.hrtime(timeStart);
this.serverless.cli.consoleLog(
`Go Plugin: ${chalk.yellow("Compilation time: " + prettyHrtime(timeEnd))}`
);
}
compileFunctionAndIgnorePackage() {
this.isInvoking = true;
return this.compileFunction();
}
async compile(name, func) {
const config = this.getConfig();
const runtime = func.runtime || this.serverless.service.provider.runtime;
if (!config.supportedRuntimes.includes(runtime)) {
return;
}
const absHandler = path.resolve(config.baseDir);
const absBin = path.resolve(config.binDir);
let compileBinPath = path.join(path.relative(absHandler, absBin), name); // binPath is based on cwd no baseDir
let cwd = config.baseDir;
let handler = func.handler;
// Exclude container functions
if (handler == null) return;
if (config.monorepo) {
if (func.handler.endsWith(".go")) {
cwd = path.relative(absHandler, path.dirname(func.handler));
handler = path.basename(handler);
} else {
cwd = path.relative(absHandler, func.handler);
handler = ".";
}
compileBinPath = path.relative(cwd, compileBinPath);
}
try {
const [env, command] = parseCommand(
`${config.cmd} -o ${compileBinPath} ${handler}`
);
await exec(command, {
cwd: cwd,
env: Object.assign(
{},
process.env,
{ CGO_ENABLED: config.cgo.toString() },
env
),
});
} catch (e) {
this.serverless.cli.consoleLog(
`Go Plugin: ${chalk.yellow(
`Error compiling "${name}" function (cwd: ${cwd}): ${e.message}`
)}`
);
process.exit(1);
}
let binPath = path.join(config.binDir, name);
if (process.platform === "win32") {
binPath = binPath.replace(/\\/g, "/");
}
this.serverless.service.functions[name].handler = binPath;
const packageConfig = this.generatePackageConfig(
runtime,
config,
binPath,
this.serverless.service.functions[name].package &&
this.serverless.service.functions[name].package.include
? this.serverless.service.functions[name].package.include
: []
);
this.serverless.service.functions[name].package = packageConfig;
}
generatePackageConfig(runtime, config, binPath, includes) {
if (
config.buildProvidedRuntimeAsBootstrap &&
amazonProvidedRuntimes.includes(runtime)
) {
const zip = new AdmZip();
zip.addFile("bootstrap", readFileSync(binPath), "", 0o755);
for (let i = 0; i < includes.length; i++) {
const files = glob.sync(includes[i]);
files.forEach((file) => {
const entryName = path.dirname(file);
zip.addLocalFile(file, entryName);
});
}
const zipPath = binPath + ".zip";
zip.writeZip(zipPath);
return {
individually: true,
artifact: zipPath,
};
}
return {
individually: true,
exclude: [`./**`],
include: [binPath].concat(includes),
};
}
getConfig() {
let config = ConfigDefaults;
if (this.serverless.service.custom && this.serverless.service.custom.go) {
config = merge(config, this.serverless.service.custom.go);
}
return config;
}
};
const envSetterRegex = /^(\w+)=('(.*)'|"(.*)"|(.*))/;
function parseCommand(cmd) {
const args = cmd.split(" ");
const envSetters = {};
let command = "";
for (let i = 0; i < args.length; i++) {
const match = envSetterRegex.exec(args[i]);
if (match) {
let value;
if (typeof match[3] !== "undefined") {
value = match[3];
} else if (typeof match[4] === "undefined") {
value = match[5];
} else {
value = match[4];
}
envSetters[match[1]] = value;
} else {
command = args.slice(i).join(" ");
break;
}
}
return [envSetters, command];
}