-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathgoogleProvider.js
330 lines (300 loc) · 11 KB
/
googleProvider.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
'use strict';
const path = require('path');
const os = require('os');
const _ = require('lodash');
const google = require('googleapis').google;
const pluginPackageJson = require('../package.json'); // eslint-disable-line import/newline-after-import
const googleApisPackageJson = require(require.resolve('googleapis/package.json')); // eslint-disable-line import/no-dynamic-require
const constants = {
providerName: 'google',
};
class GoogleProvider {
static getProviderName() {
return constants.providerName;
}
constructor(serverless) {
this.serverless = serverless;
this.provider = this; // only load plugin in a Google service context
this.serverless.setProvider(constants.providerName, this);
this.serverless.configSchemaHandler.defineProvider(constants.providerName, {
definitions: {
cloudFunctionRegion: {
// Source: https://cloud.google.com/functions/docs/locations
enum: [
// Tier pricing 1
'us-central1', // (Iowa)
'us-east1', // (South Carolina)
'us-east4', // (Northern Virginia)
'us-west1', // (Oregon)
'europe-west1', // (Belgium)
'europe-west2', // (London)
'asia-east1', // (Taiwan)
'asia-east2', // (Hong Kong)
'asia-northeast1', // (Tokyo)
'asia-northeast2', // (Osaka)
// Tier pricing 2
'us-west2', // (Los Angeles)
'us-west3', // (Salt Lake City)
'us-west4', // (Las Vegas)
'northamerica-northeast1', // (Montreal)
'southamerica-east1', // (Sao Paulo)
'europe-west3', // (Frankfurt)
'europe-west6', // (Zurich)
'europe-central2', // (Warsaw)
'australia-southeast1', // (Sydney)
'asia-south1', // (Mumbai)
'asia-southeast1', // (Singapore)
'asia-southeast2', // (Jakarta)
'asia-northeast3', // (Seoul)
],
},
cloudFunctionRuntime: {
// Source: https://cloud.google.com/functions/docs/concepts/exec#runtimes
enum: [
'nodejs6', // decommissioned
'nodejs8', // deprecated
'nodejs10',
'nodejs12',
'nodejs14',
'nodejs16', // recommended
'python37',
'python38',
'python39',
'go111',
'go113',
'go116', // recommended
'java11',
'dotnet3',
'ruby26',
'ruby27',
],
},
cloudFunctionMemory: {
// Source: https://cloud.google.com/functions/docs/concepts/exec#memory
enum: [
128,
256, // default
512,
1024,
2048,
4096,
],
},
cloudFunctionEnvironmentVariables: {
type: 'object',
patternProperties: {
'^.*$': { type: 'string' },
},
additionalProperties: false,
},
cloudFunctionSecretEnvironmentVariables: {
type: 'object',
patternProperties: {
'^[a-zA-Z0-9_]+$': {
type: 'object',
properties: {
projectId: {
type: 'string',
minLength: 1,
},
secret: {
type: 'string',
pattern: '^[a-zA-Z0-9_-]+$',
},
version: {
type: 'string',
pattern: '^(latest|[0-9.]+)$',
},
},
required: ['secret', 'version'],
},
},
},
cloudFunctionVpcEgress: {
enum: ['ALL', 'ALL_TRAFFIC', 'PRIVATE', 'PRIVATE_RANGES_ONLY'],
},
resourceManagerLabels: {
type: 'object',
propertyNames: {
type: 'string',
minLength: 1,
maxLength: 63,
},
patternProperties: {
'^[a-z][a-z0-9_.]*$': { type: 'string' },
},
additionalProperties: false,
},
},
provider: {
properties: {
credentials: { type: 'string' },
project: { type: 'string' },
region: { $ref: '#/definitions/cloudFunctionRegion' },
runtime: { $ref: '#/definitions/cloudFunctionRuntime' }, // Can be overridden by function configuration
serviceAccountEmail: { type: 'string' }, // Can be overridden by function configuration
memorySize: { $ref: '#/definitions/cloudFunctionMemory' }, // Can be overridden by function configuration
timeout: { type: 'string' }, // Can be overridden by function configuration
environment: { $ref: '#/definitions/cloudFunctionEnvironmentVariables' }, // Can be overridden by function configuration
secrets: { $ref: '#/definitions/cloudFunctionSecretEnvironmentVariables' }, // Can be overridden by function configuration
vpc: { type: 'string' }, // Can be overridden by function configuration
vpcEgress: { $ref: '#/definitions/cloudFunctionVpcEgress' }, // Can be overridden by function configuration
labels: { $ref: '#/definitions/resourceManagerLabels' }, // Can be overridden by function configuration
},
},
function: {
properties: {
handler: { type: 'string' },
runtime: { $ref: '#/definitions/cloudFunctionRuntime' }, // Override provider configuration
serviceAccountEmail: { type: 'string' }, // Override provider configuration
memorySize: { $ref: '#/definitions/cloudFunctionMemory' }, // Override provider configuration
timeout: { type: 'string' }, // Override provider configuration
minInstances: { type: 'number' },
environment: { $ref: '#/definitions/cloudFunctionEnvironmentVariables' }, // Override provider configuration
secrets: { $ref: '#/definitions/cloudFunctionSecretEnvironmentVariables' }, // Can be overridden by function configuration
vpc: { type: 'string' }, // Override provider configuration
vpcEgress: { $ref: '#/definitions/cloudFunctionVpcEgress' }, // Can be overridden by function configuration
labels: { $ref: '#/definitions/resourceManagerLabels' }, // Override provider configuration
},
},
});
const serverlessVersion = this.serverless.version;
const pluginVersion = pluginPackageJson.version;
const googleApisVersion = googleApisPackageJson.version;
google.options({
headers: {
'User-Agent': `Serverless/${serverlessVersion} Serverless-Google-Provider/${pluginVersion} Googleapis/${googleApisVersion}`,
},
});
this.sdk = {
google,
deploymentmanager: google.deploymentmanager('v2'),
storage: google.storage('v1'),
logging: google.logging('v2'),
cloudfunctions: google.cloudfunctions('v1'),
};
this.configurationVariablesSources = {
gs: {
async resolve({ address }) {
if (!address) {
throw new serverless.classes.Error(
'Missing address argument in variable "gs" source',
'GOOGLE_CLOUD_MISSING_GS_VAR ADDRESS'
);
}
const groups = address.split('/');
const bucket = groups.shift();
const object = groups.join('/');
return { value: await this.gsValue({ bucket, object }) };
},
},
};
// TODO: Remove with next major
this.variableResolvers = {
gs: (variableString) => {
const groups = variableString.split(':')[1].split('/');
const bucket = groups.shift();
const object = groups.join('/');
return this.gsValue({ bucket, object });
},
};
}
async getGsValue({ bucket, object }) {
return this.serverless
.getProvider('google')
.request('storage', 'objects', 'get', {
bucket,
object,
alt: 'media',
})
.catch((err) => {
throw new Error(`Error getting value for ${bucket}/${object}. ${err.message}`);
});
}
request() {
// grab necessary stuff from arguments array
const lastArg = arguments[Object.keys(arguments).pop()]; //eslint-disable-line
const hasParams = typeof lastArg === 'object';
const filArgs = _.filter(arguments, (v) => typeof v === 'string'); //eslint-disable-line
const params = hasParams ? lastArg : {};
const service = filArgs[0];
const serviceInstance = this.sdk[service];
this.isServiceSupported(service);
const authClient = this.getAuthClient();
return authClient.getClient().then(() => {
const requestParams = { auth: authClient };
// merge the params from the request call into the base functionParams
_.merge(requestParams, params);
return filArgs
.reduce((p, c) => p[c], this.sdk)
.bind(serviceInstance)(requestParams)
.then((result) => result.data)
.catch((error) => {
if (
error &&
error.errors &&
error.errors[0].message &&
_.includes(error.errors[0].message, 'project 1043443644444')
) {
throw new Error(
"Incorrect configuration. Please change the 'project' key in the 'provider' block in your Serverless config file."
);
} else if (error) {
throw error;
}
});
});
}
getAuthClient() {
let credentials = this.serverless.service.provider.credentials;
if (credentials) {
const credParts = this.serverless.service.provider.credentials.split(path.sep);
if (credParts[0] === '~') {
credParts[0] = os.homedir();
credentials = credParts.reduce((memo, part) => path.join(memo, part), '');
}
return new google.auth.GoogleAuth({
keyFile: credentials.toString(),
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
}
return new google.auth.GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
}
isServiceSupported(service) {
if (!_.includes(Object.keys(this.sdk), service)) {
const errorMessage = [
`Unsupported service API "${service}".`,
` Supported service APIs are: ${Object.keys(this.sdk).join(', ')}`,
].join('');
throw new Error(errorMessage);
}
}
getRuntime(funcObject) {
return (
_.get(funcObject, 'runtime') ||
_.get(this, 'serverless.service.provider.runtime') ||
'nodejs10'
);
}
getConfiguredSecrets(funcObject) {
const providerSecrets = _.get(this, 'serverless.service.provider.secrets', {});
const secrets = _.merge({}, providerSecrets, funcObject.secrets);
const keys = Object.keys(secrets).sort();
return keys.map((key) => {
return {
key,
...secrets[key],
};
});
}
getConfiguredEnvironment(funcObject) {
return _.merge(
{},
_.get(this, 'serverless.service.provider.environment'),
funcObject.environment
);
}
}
module.exports = GoogleProvider;