forked from alibaba/funcraft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
package.js
218 lines (173 loc) · 6.86 KB
/
package.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
'use strict';
const { ensureFilesModified } = require('../utils/file');
const { isEmptyDir } = require('../nas/cp/file');
const { getOssClient } = require('../client');
const { parseMountDirPrefix } = require('../fc');
const { red, green, yellow } = require('colors');
const { getTpl, detectNasBaseDir, getNasYmlPath } = require('../tpl');
const { validateNasAndVpcConfig, SERVICE_RESOURCE, iterateResources, isNasAutoConfig, isVpcAutoConfig, getUserIdAndGroupId } = require('../definition');
const fs = require('fs-extra');
const {
promptForConfirmContinue,
promptForInputContinue
} = require('../init/prompt');
const { getProfile } = require('../profile');
const nas = require('../nas');
const path = require('path');
const util = require('../import/utils');
const nasSupport = require('../nas/support');
const _ = require('lodash');
const {
zipToOss,
uploadNasService,
processNasPythonPaths,
transformFlowDefinition,
uploadAndUpdateFunctionCode,
generateRosTemplateForRegionMap,
generateRosTemplateForVpcConfig,
generateRosTemplateForNasConfig,
generateRosTemplateForNasService,
generateRosTemplateForEventOutputs,
generateRosTemplateForNasCpInvoker,
generateRosTemplateForWaitCondition,
generateRosTemplateForDefaultOutputs,
generateRosTemplateForDefaultResources
} = require('./template');
async function processNasAutoToRosTemplate({ tpl, baseDir, tplPath,
ossClient,
bucketName
}) {
const cloneTpl = _.cloneDeep(tpl);
const servicesNeedUpdate = [];
iterateResources(cloneTpl.Resources, SERVICE_RESOURCE, (serviceName, serviceRes) => {
const nasConfig = (serviceRes.Properties || {}).NasConfig;
const vpcConfig = (serviceRes.Properties || {}).VpcConfig;
const nasAuto = isNasAutoConfig(nasConfig);
const vpcAuto = isVpcAutoConfig(vpcConfig);
if (nasAuto && !_.isEmpty(vpcConfig) && !vpcAuto) {
throw new Error(`When 'NasConfig: Auto' is specified, 'VpcConfig' is not supported.`);
}
if (nasAuto && (vpcAuto || _.isEmpty(vpcConfig))) {
servicesNeedUpdate.push({
serviceName,
serviceRes
});
}
});
if (_.isEmpty(servicesNeedUpdate)) { return cloneTpl; }
const serviceNasMapping = await nas.convertTplToServiceNasMappings(detectNasBaseDir(tplPath), tpl);
const mergedNasMapping = await nasSupport.mergeNasMappingsInNasYml(getNasYmlPath(tplPath), serviceNasMapping);
let count = 0;
let totalObjectNames = [];
for (const { serviceName, serviceRes } of servicesNeedUpdate) {
const serviceProp = (serviceRes.Properties || {});
const nasConfig = serviceProp.NasConfig;
const { userId, groupId } = getUserIdAndGroupId(nasConfig);
serviceProp.VpcConfig = generateRosTemplateForVpcConfig();
serviceProp.NasConfig = generateRosTemplateForNasConfig(serviceName, userId, groupId);
const objectNames = [];
for (const { localNasDir, remoteNasDir } of mergedNasMapping[serviceName]) {
const srcPath = path.resolve(baseDir, localNasDir);
if (!await fs.pathExists(srcPath)) {
console.warn(`\n${srcPath} is not exist, skiping.`);
continue;
}
if (await isEmptyDir(srcPath)) {
console.warn(`\n${srcPath} is empty directory, skiping.`);
continue;
}
const prefix = path.relative(parseMountDirPrefix(nasConfig), remoteNasDir);
const objectName = await zipToOss(ossClient, srcPath, null, 'nas.zip', prefix);
if (!objectName) {
console.warn(`\n${srcPath} is empty directory, skiping.`);
continue;
}
objectNames.push(objectName);
totalObjectNames.push(objectName);
}
if (_.isEmpty(objectNames)) {
console.warn(red(`\nwarning: There is no local NAS directory available under service: ${serviceName}.`));
continue;
}
const customizer = (objValue, srcValue) => {
return _.isEmpty(objValue) ? srcValue : _.merge(objValue, srcValue);
};
_.assignWith(cloneTpl, generateRosTemplateForEventOutputs(bucketName, objectNames, serviceName), customizer);
Object.assign(cloneTpl.Resources, generateRosTemplateForNasCpInvoker(serviceName, bucketName, objectNames));
count ++;
}
Object.assign(cloneTpl, generateRosTemplateForRegionMap());
Object.assign(cloneTpl.Resources, generateRosTemplateForDefaultResources());
if (_.isEmpty(totalObjectNames)) { return cloneTpl; }
const codeUri = await uploadNasService(ossClient);
Object.assign(cloneTpl.Resources, generateRosTemplateForNasService(codeUri));
Object.assign(cloneTpl.Resources, generateRosTemplateForWaitCondition(count));
return _.merge(cloneTpl, generateRosTemplateForDefaultOutputs());
}
async function generateDefaultOSSBucket() {
const profile = await getProfile();
const bucketName = `fun-gen-${profile.defaultRegion}-${profile.accountId}`;
console.log(yellow(`using oss-bucket: ${bucketName}`));
const ossClient = await getOssClient();
let bucketExist = false;
try {
await ossClient.getBucketLocation(bucketName);
bucketExist = true;
} catch (ex) {
if (!ex.code || ex.code !== 'NoSuchBucket') {
throw ex;
}
}
if (bucketExist) {
return bucketName;
}
if (!await promptForConfirmContinue('Auto generate OSS bucket for you:')) {
return (await promptForInputContinue('Input OSS bucket name:')).input;
}
await ossClient.putBucket(bucketName);
return bucketName;
}
async function pack(tplPath, bucket, outputTemplateFile) {
const tpl = await getTpl(tplPath);
validateNasAndVpcConfig(tpl.Resources);
const baseDir = path.dirname(tplPath);
if (!bucket) {
bucket = await generateDefaultOSSBucket();
}
if (!bucket) {
throw new Error('Missing OSS bucket');
}
await ensureFilesModified(tplPath);
const ossClient = await getOssClient(bucket);
const updatedEnvTpl = await processNasPythonPaths(tpl, tplPath);
const updatedCodeTpl = await uploadAndUpdateFunctionCode({ tpl: updatedEnvTpl, tplPath, baseDir, ossClient });
const updatedFlowTpl = await transformFlowDefinition(baseDir, updatedCodeTpl);
const updatedTpl = await processNasAutoToRosTemplate({ ossClient, baseDir, tplPath,
tpl: updatedFlowTpl,
bucketName: bucket
});
let packedYmlPath;
if (outputTemplateFile) {
packedYmlPath = path.resolve(process.cwd(), outputTemplateFile);
} else {
packedYmlPath = path.join(process.cwd(), 'template.packaged.yml');
}
util.outputTemplateFile(packedYmlPath, updatedTpl);
console.log(green('\nPackage success'));
showPackageNextTips(packedYmlPath);
}
function showPackageNextTips(packedYmlPath) {
const deployTip = 'fun deploy';
const relative = path.relative(process.cwd(), packedYmlPath);
const DEFAULT_PACKAGED_YAML_NAME = 'template.packaged.yml';
let templateParam = '';
if (relative !== DEFAULT_PACKAGED_YAML_NAME) {
templateParam = ` -t ${relative}`;
}
console.log(yellow(`\nTips for next step
======================
* Deploy Resources: ${deployTip}${templateParam}`));
}
module.exports = {
pack
};