Skip to content

Commit b4c3f0d

Browse files
committed
fix: nas config and logConfig
1 parent df2d6bc commit b4c3f0d

File tree

4 files changed

+151
-15
lines changed

4 files changed

+151
-15
lines changed

__tests__/e2e/nodejs/s_oss_config_auto.yaml

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,39 @@ resources:
3838
handler: index.handler
3939
memorySize: 128
4040
timeout: 60
41-
ossMountConfig: auto|mountDir=/mnt/test-oss-bucket|bucketPath=/|rules=[{"allowedOrigin":"*","allowedMethod":["GET","POST","PUT","DELETE","HEAD"],"allowedHeader":"*","exposeHeader":"Content-Length","maxAgeSeconds":30}]
41+
ossMountConfig: auto|mountDir=/mnt/test-oss-bucket|bucketPath=/|rules=[{"allowedOrigin":"*","allowedMethod":["GET","POST","PUT","DELETE","HEAD"],"allowedHeader":"*","exposeHeader":"Content-Length","maxAgeSeconds":30}]
42+
43+
fcDemo3: # 业务名称/模块名称
44+
component: ${env('fc_component_version', path('../../../'))}
45+
actions:
46+
pre-deploy:
47+
- run: npm install
48+
path: ./test-auto-code
49+
props: # 组件的属性值
50+
region: ${vars.region}
51+
functionName: fc3-event-${env('fc_component_function_name', 'nodejs18')}-nasConfig
52+
role: acs:ram::${config('AccountID')}:role/aliyunaliyunfcdefaultrole
53+
runtime: ${env('fc_component_runtime', 'nodejs18')}
54+
code: ./test-auto-code
55+
handler: index.handler
56+
memorySize: 128
57+
timeout: 60
58+
nasConfig: auto|mountDir=/custom/nas/mount/path|serverAddr=/custom/nas/mount/path
59+
vpcConfig: auto
60+
61+
fcDemo4: # 业务名称/模块名称
62+
component: ${env('fc_component_version', path('../../../'))}
63+
actions:
64+
pre-deploy:
65+
- run: npm install
66+
path: ./test-auto-code
67+
props: # 组件的属性值
68+
region: ${vars.region}
69+
functionName: fc3-event-${env('fc_component_function_name', 'nodejs18')}-logConfig
70+
role: acs:ram::${config('AccountID')}:role/aliyunaliyunfcdefaultrole
71+
runtime: ${env('fc_component_runtime', 'nodejs18')}
72+
code: ./test-auto-code
73+
handler: index.handler
74+
memorySize: 128
75+
timeout: 60
76+
logConfig: auto|enableRequestMetrics=false|enableInstanceMetrics=false

src/subCommands/deploy/impl/function.ts

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,12 @@ import FC, { GetApiType } from '../../../resources/fc';
1818
import VPC_NAS from '../../../resources/vpc-nas';
1919
import Base from './base';
2020
import { ICredentials } from '@serverless-devs/component-interface';
21-
import { calculateCRC64, getFileSize } from '../../../utils';
21+
import {
22+
calculateCRC64,
23+
getFileSize,
24+
parseAutoConfig,
25+
validateAndNormalizePath,
26+
} from '../../../utils';
2227
import OSS from '../../../resources/oss';
2328
import { setNodeModulesBinPermissions } from '../../../resources/fc/impl/utils';
2429

@@ -349,22 +354,33 @@ export default class Service extends Base {
349354
if (slsAuto) {
350355
const sls = new Sls(region, credential as ICredentials);
351356
const { project, logstore } = await sls.deploy();
357+
const logAutoConfig = parseAutoConfig(this.local.logConfig as string);
358+
const logParams = logAutoConfig?.params || {};
359+
const existingLogConfig =
360+
typeof this.local.logConfig === 'object' && this.local.logConfig !== null
361+
? this.local.logConfig
362+
: {};
363+
const customFields: Record<string, any> = { ...existingLogConfig, ...logParams };
352364
logger.write(
353365
yellow(`Created log resource succeeded, please replace logConfig: auto in yaml with:
354366
logConfig:
355-
enableInstanceMetrics: true
356-
enableRequestMetrics: true
357-
logBeginRule: DefaultRegex
367+
enableInstanceMetrics: ${customFields.enableInstanceMetrics}
368+
enableRequestMetrics: ${customFields.enableRequestMetrics}
369+
logBeginRule: ${customFields.logBeginRule}
358370
logstore: ${logstore}
359371
project: ${project}\n`),
360372
);
373+
361374
this.createResource.sls = { project, logstore };
362375
_.set(this.local, 'logConfig', {
363-
enableInstanceMetrics: true,
364-
enableRequestMetrics: true,
365-
logBeginRule: 'DefaultRegex',
376+
enableInstanceMetrics:
377+
'enableInstanceMetrics' in customFields ? customFields.enableInstanceMetrics : true,
378+
enableRequestMetrics:
379+
'enableRequestMetrics' in customFields ? customFields.enableRequestMetrics : true,
380+
logBeginRule: 'logBeginRule' in customFields ? customFields.logBeginRule : 'DefaultRegex',
366381
logstore,
367382
project,
383+
...customFields,
368384
});
369385
}
370386

@@ -443,7 +459,12 @@ vpcConfig:
443459
_.set(this.local, 'vpcConfig', vpcConfig);
444460
}
445461
if (nasAuto) {
446-
let serverAddr = `${mountTargetDomain}:/${functionName}`;
462+
const { params } = parseAutoConfig(this.local.nasConfig as string);
463+
const customMountDir = params.mountDir
464+
? validateAndNormalizePath(params.mountDir, 'mountDir')
465+
: `/mnt/${functionName}`;
466+
const customServerAddr = params.serverAddr ? params.serverAddr : `${functionName}`;
467+
let serverAddr = `${mountTargetDomain}:/${customServerAddr}`;
447468
if (serverAddr.length > 128) {
448469
serverAddr = serverAddr.substring(0, 128);
449470
}
@@ -454,8 +475,9 @@ nasConfig:
454475
userId: 0
455476
mountPoints:
456477
- serverAddr: ${serverAddr}
457-
mountDir: /mnt/${functionName}
458-
enableTLS: false\n`),
478+
mountDir: ${customMountDir}
479+
enableTLS: false
480+
`),
459481
);
460482
this.createResource.nas = { mountTargetDomain, fileSystemId };
461483
_.set(this.local, 'nasConfig', {
@@ -464,7 +486,7 @@ nasConfig:
464486
mountPoints: [
465487
{
466488
serverAddr,
467-
mountDir: `/mnt/${functionName}`,
489+
mountDir: customMountDir,
468490
enableTLS: false,
469491
},
470492
],

src/subCommands/model/index.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { OSSMountPoint, VPCConfig } from '@alicloud/fc20230330';
1414
import { MODEL_DOWNLOAD_TIMEOUT } from './constants';
1515
import { initClient } from './utils';
1616
import * as $Dev20230714 from '@alicloud/devs20230714';
17+
import { parseAutoConfig, validateAndNormalizePath } from '../../utils';
1718

1819
const commandsList = Object.keys(commandsHelp.subCommands);
1920

@@ -239,7 +240,13 @@ vpcConfig:
239240
}
240241

241242
if (nasAuto) {
242-
let serverAddr = `${mountTargetDomain}:/${functionName}`;
243+
const nasAutoConfig = parseAutoConfig(this.local.nasConfig as string);
244+
const params = nasAutoConfig?.params || {};
245+
const customMountDir = params.mountDir
246+
? validateAndNormalizePath(params.mountDir, 'mountDir')
247+
: `/mnt/${functionName}`;
248+
const customServerAddr = params.serverAddr ? params.serverAddr : `${functionName}`;
249+
let serverAddr = `${mountTargetDomain}:/${customServerAddr}`;
243250
if (serverAddr.length > 128) {
244251
serverAddr = serverAddr.substring(0, 128);
245252
}
@@ -250,7 +257,7 @@ groupId: 0
250257
userId: 0
251258
mountPoints:
252259
- serverAddr: ${serverAddr}
253-
mountDir: /mnt/${functionName}
260+
mountDir: ${customMountDir}
254261
enableTLS: false\n`),
255262
);
256263
this.createResource.nas = { mountTargetDomain, fileSystemId };
@@ -260,7 +267,7 @@ mountPoints:
260267
mountPoints: [
261268
{
262269
serverAddr,
263-
mountDir: `/mnt/${functionName}`,
270+
mountDir: customMountDir,
264271
enableTLS: false,
265272
},
266273
],

src/utils/index.ts

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,40 @@ export const isAuto = (config: unknown): boolean => {
4949
return _.toUpper(autoConfig) === 'AUTO';
5050
};
5151

52+
export const parseAutoConfig = (
53+
config: string,
54+
): { isAuto: boolean; params: Record<string, any> } => {
55+
if (!_.isString(config)) {
56+
return { isAuto: false, params: {} };
57+
}
58+
59+
const parts = config.split('|');
60+
const baseConfig = parts[0];
61+
logger.debug(`parseAutoConfig, baseConfig = ${baseConfig}`);
62+
63+
if (_.toUpper(baseConfig) === 'AUTO') {
64+
const params: Record<string, any> = {};
65+
for (let i = 1; i < parts.length; i++) {
66+
const [key, value] = parts[i].split('=');
67+
if (key && value) {
68+
const trimmedValue = value.trim();
69+
if (typeof trimmedValue === 'string') {
70+
try {
71+
params[key.trim()] = JSON.parse(trimmedValue);
72+
} catch (error) {
73+
params[key.trim()] = trimmedValue;
74+
}
75+
} else {
76+
params[key.trim()] = trimmedValue;
77+
}
78+
}
79+
}
80+
return { isAuto: true, params };
81+
}
82+
83+
return { isAuto: false, params: {} };
84+
};
85+
5286
export const isAutoVpcConfig = (config: unknown): boolean => {
5387
logger.debug(`isAutoVpcConfig, vpcConfig = ${JSON.stringify(config)}`);
5488
if (_.isString(config)) {
@@ -223,3 +257,41 @@ export function getUserAgent(userAgent: string, command: string) {
223257
}
224258
return `${function_ai}Component:fc3;Nodejs:${process.version};OS:${process.platform}-${process.arch}command:${command}`;
225259
}
260+
261+
/**
262+
* 验证并规范化路径
263+
*/
264+
export function validateAndNormalizePath(path: string, paramName = 'path'): string {
265+
if (typeof path !== 'string') {
266+
const message = `Invalid ${paramName}, expected string but got ${typeof path}`;
267+
if (logger) logger.warn(message);
268+
return '/';
269+
}
270+
271+
if (!path) {
272+
if (logger) logger.debug(`Empty ${paramName}, using default value`);
273+
return '/';
274+
}
275+
276+
let normalizedPath = path.trim();
277+
278+
if (!normalizedPath.startsWith('/')) {
279+
normalizedPath = `/${normalizedPath}`;
280+
if (logger) logger.debug(`${paramName} does not start with '/', prepending '/'`);
281+
}
282+
283+
if (normalizedPath.length > 1 && normalizedPath.endsWith('/')) {
284+
normalizedPath = normalizedPath.slice(0, -1);
285+
if (logger) logger.debug(`${paramName} ends with '/', removing trailing '/'`);
286+
}
287+
288+
if (normalizedPath.length > 1024) {
289+
normalizedPath = normalizedPath.substring(0, 1024);
290+
if (logger)
291+
logger.warn(
292+
`${paramName} is too long (${normalizedPath.length}), truncating to 1024 characters`,
293+
);
294+
}
295+
296+
return normalizedPath;
297+
}

0 commit comments

Comments
 (0)