You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.tsx 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /*
  2. * @Author: 赵伟
  3. * @Date: 2024-04-16 13:58:08
  4. * @Description: 创建服务版本
  5. */
  6. import CodeSelect from '@/components/CodeSelect';
  7. import PageTitle from '@/components/PageTitle';
  8. import ParameterSelect from '@/components/ParameterSelect';
  9. import ResourceSelect, {
  10. ResourceSelectorType,
  11. requiredValidator,
  12. type ParameterInputObject,
  13. } from '@/components/ResourceSelect';
  14. import SubAreaTitle from '@/components/SubAreaTitle';
  15. import {
  16. createServiceVersionReq,
  17. getServiceInfoReq,
  18. updateServiceVersionReq,
  19. } from '@/services/modelDeployment';
  20. import { changePropertyName } from '@/utils';
  21. import { to } from '@/utils/promise';
  22. import SessionStorage from '@/utils/sessionStorage';
  23. import { removeFormListItem } from '@/utils/ui';
  24. import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons';
  25. import { useNavigate, useParams } from '@umijs/max';
  26. import { App, Button, Col, Flex, Form, Input, InputNumber, Row } from 'antd';
  27. import { omit, pick } from 'lodash';
  28. import { useEffect, useState } from 'react';
  29. import { CreateServiceVersionFrom, ServiceOperationType, ServiceVersionData } from '../types';
  30. import styles from './index.less';
  31. // 表单数据
  32. export type FormData = {
  33. service_name: string; // 服务名称
  34. version: string; // 服务版本
  35. description: string; // 描述
  36. model: ParameterInputObject; // 模型
  37. image: ParameterInputObject; // 镜像
  38. code_config: ParameterInputObject; // 代码
  39. resource: string; // 资源规格
  40. replicas: string; // 副本数量
  41. mount_path: string; // 模型路径
  42. env_variables: { key: string; value: string }[]; // 环境变量
  43. };
  44. type ServiceVersionCache = ServiceVersionData & {
  45. operationType: ServiceOperationType;
  46. lastPage: CreateServiceVersionFrom;
  47. };
  48. // 参数表单数据
  49. export type FormEnvVariable = {
  50. key: string; // 参数名
  51. value: string; // 参数值
  52. };
  53. function CreateServiceVersion() {
  54. const navigate = useNavigate();
  55. const [form] = Form.useForm();
  56. const [operationType, setOperationType] = useState(ServiceOperationType.Create);
  57. const [lastPage, setLastPage] = useState(CreateServiceVersionFrom.ServiceInfo);
  58. const { message } = App.useApp();
  59. const [versionInfo, setVersionInfo] = useState<ServiceVersionData | undefined>(undefined);
  60. const params = useParams();
  61. const serviceId = params.serviceId;
  62. // 因为没有服务版本详情接口,需要从缓存中获取
  63. useEffect(() => {
  64. const res: ServiceVersionCache | undefined = SessionStorage.getItem(
  65. SessionStorage.serviceVersionInfoKey,
  66. true,
  67. );
  68. if (res) {
  69. setOperationType(res.operationType);
  70. setLastPage(res.lastPage);
  71. setVersionInfo(res);
  72. let model, codeConfig, envVariables;
  73. if (res.model && typeof res.model === 'object') {
  74. model = changePropertyName(res.model, { show_value: 'showValue' });
  75. // 接口返回是数据没有 value 值,但是 form 需要 value
  76. model.value = model.showValue;
  77. }
  78. if (res.code_config && typeof res.code_config === 'object') {
  79. codeConfig = changePropertyName(res.code_config, { show_value: 'showValue' });
  80. // 接口返回是数据没有 value 值,但是 form 需要 value
  81. codeConfig.value = codeConfig.showValue;
  82. }
  83. if (res.env_variables && typeof res.env_variables === 'object') {
  84. envVariables = Object.entries(res.env_variables).map(([key, value]) => ({
  85. key,
  86. value,
  87. }));
  88. }
  89. const formData = {
  90. ...omit(res, 'model', 'code_config', 'env_variables'),
  91. model: model,
  92. code_config: codeConfig,
  93. env_variables: envVariables,
  94. };
  95. form.setFieldsValue(formData);
  96. }
  97. return () => {
  98. SessionStorage.removeItem(SessionStorage.serviceVersionInfoKey);
  99. };
  100. }, [form]);
  101. useEffect(() => {
  102. // 获取服务详情,设置服务名称
  103. const getServiceInfo = async () => {
  104. const [res] = await to(getServiceInfoReq(serviceId));
  105. if (res && res.data) {
  106. form.setFieldsValue({
  107. service_name: res.data.service_name,
  108. });
  109. }
  110. };
  111. getServiceInfo();
  112. }, [serviceId, form]);
  113. // 创建版本
  114. const createServiceVersion = async (formData: FormData) => {
  115. const envList = formData['env_variables'];
  116. const model = formData['model'];
  117. const codeConfig = formData['code_config'];
  118. const envVariables = envList?.reduce((acc, cur) => {
  119. acc[cur.key] = cur.value;
  120. return acc;
  121. }, {} as Record<string, string>);
  122. // 根据后台要求,修改表单数据
  123. const object = {
  124. ...omit(formData, ['replicas', 'env_variables', 'model', 'code_config']),
  125. replicas: Number(formData.replicas),
  126. env_variables: envVariables,
  127. model: changePropertyName(
  128. pick(model, ['id', 'name', 'version', 'path', 'identifier', 'owner', 'showValue']),
  129. { showValue: 'show_value' },
  130. ),
  131. code_config: codeConfig
  132. ? changePropertyName(pick(codeConfig, ['code_path', 'branch', 'showValue']), {
  133. showValue: 'show_value',
  134. })
  135. : undefined,
  136. service_id: serviceId,
  137. };
  138. const params =
  139. operationType === ServiceOperationType.Create
  140. ? {
  141. ...object,
  142. deploy_type: 'web',
  143. }
  144. : {
  145. id: versionInfo?.id,
  146. rerun: operationType === ServiceOperationType.Restart ? true : false,
  147. deployment_name: versionInfo?.deployment_name,
  148. ...object,
  149. };
  150. const request =
  151. operationType === ServiceOperationType.Create
  152. ? createServiceVersionReq
  153. : updateServiceVersionReq;
  154. const [res] = await to(request(params));
  155. if (res) {
  156. message.success('操作成功');
  157. if (lastPage === CreateServiceVersionFrom.ServiceInfo) {
  158. navigate(-1);
  159. } else {
  160. navigate(`/dataset/modelDeployment/serviceInfo/${serviceId}`, { replace: true });
  161. }
  162. }
  163. };
  164. // 提交
  165. const handleSubmit = (values: FormData) => {
  166. createServiceVersion(values);
  167. };
  168. // 取消
  169. const cancel = () => {
  170. navigate(-1);
  171. };
  172. const disabled = operationType !== ServiceOperationType.Create;
  173. let buttonText = '新建';
  174. let title = '新增服务版本';
  175. if (operationType === ServiceOperationType.Update) {
  176. title = '更新服务版本';
  177. buttonText = '更新';
  178. } else if (operationType === ServiceOperationType.Restart) {
  179. title = '重启服务版本';
  180. buttonText = '重启';
  181. }
  182. return (
  183. <div className={styles['create-service-version']}>
  184. <PageTitle title={title}></PageTitle>
  185. <div className={styles['create-service-version__content']}>
  186. <div>
  187. <Form
  188. name="create-service-version"
  189. labelCol={{ flex: '100px' }}
  190. labelAlign="left"
  191. form={form}
  192. onFinish={handleSubmit}
  193. size="large"
  194. autoComplete="off"
  195. >
  196. <SubAreaTitle
  197. title="基本信息"
  198. image={require('@/assets/img/mirror-basic.png')}
  199. style={{ marginBottom: '26px' }}
  200. ></SubAreaTitle>
  201. <Row gutter={8}>
  202. <Col span={10}>
  203. <Form.Item
  204. label="服务名称"
  205. name="service_name"
  206. rules={[
  207. {
  208. required: true,
  209. message: '请输入服务名称',
  210. },
  211. ]}
  212. >
  213. <Input
  214. placeholder="请输入服务名称"
  215. maxLength={30}
  216. disabled
  217. showCount
  218. allowClear
  219. />
  220. </Form.Item>
  221. </Col>
  222. </Row>
  223. <Row gutter={8}>
  224. <Col span={10}>
  225. <Form.Item
  226. label="服务版本"
  227. name="version"
  228. rules={[
  229. {
  230. required: true,
  231. message: '请输入服务版本',
  232. },
  233. {
  234. pattern: /^[a-zA-Z0-9._-]+$/,
  235. message: '版本只支持字母、数字、点(.)、下划线(_)、中横线(-)',
  236. },
  237. ]}
  238. >
  239. <Input
  240. placeholder="请输入服务版本"
  241. maxLength={30}
  242. disabled={disabled}
  243. showCount
  244. allowClear
  245. />
  246. </Form.Item>
  247. </Col>
  248. </Row>
  249. <Row gutter={8}>
  250. <Col span={20}>
  251. <Form.Item
  252. label="版本描述"
  253. name="description"
  254. rules={[
  255. {
  256. required: true,
  257. message: '请输入版本描述',
  258. },
  259. ]}
  260. >
  261. <Input.TextArea
  262. autoSize={{ minRows: 2, maxRows: 6 }}
  263. placeholder="请输入版本描述,最长128字符"
  264. maxLength={128}
  265. showCount
  266. allowClear
  267. />
  268. </Form.Item>
  269. </Col>
  270. </Row>
  271. <SubAreaTitle
  272. title="部署构建"
  273. image={require('@/assets/img/model-deployment.png')}
  274. style={{ marginTop: '20px', marginBottom: '24px' }}
  275. ></SubAreaTitle>
  276. <Row gutter={8}>
  277. <Col span={10}>
  278. <Form.Item
  279. label="选择模型"
  280. name="model"
  281. rules={[
  282. {
  283. validator: requiredValidator,
  284. message: '请选择模型',
  285. },
  286. ]}
  287. required
  288. >
  289. <ResourceSelect
  290. type={ResourceSelectorType.Model}
  291. placeholder="请选择模型"
  292. disabled={disabled}
  293. canInput={false}
  294. />
  295. </Form.Item>
  296. </Col>
  297. </Row>
  298. <Row gutter={8}>
  299. <Col span={10}>
  300. <Form.Item
  301. label="选择镜像"
  302. name="image"
  303. rules={[
  304. {
  305. validator: requiredValidator,
  306. message: '请选择镜像',
  307. },
  308. ]}
  309. required
  310. >
  311. <ResourceSelect
  312. type={ResourceSelectorType.Mirror}
  313. placeholder="请选择镜像"
  314. canInput={false}
  315. disabled={disabled}
  316. />
  317. </Form.Item>
  318. </Col>
  319. </Row>
  320. <Row gutter={8}>
  321. <Col span={10}>
  322. <Form.Item label="代码配置" name="code_config">
  323. <CodeSelect
  324. placeholder="请选择代码配置"
  325. canInput={false}
  326. size="large"
  327. disabled={disabled}
  328. />
  329. </Form.Item>
  330. </Col>
  331. </Row>
  332. <Row gutter={8}>
  333. <Col span={10}>
  334. <Form.Item
  335. label="资源规格"
  336. name="computing_resource_id"
  337. rules={[
  338. {
  339. required: true,
  340. message: '请选择资源规格',
  341. },
  342. ]}
  343. >
  344. <ParameterSelect dataType="resource" placeholder="请选择资源规格" />
  345. </Form.Item>
  346. </Col>
  347. </Row>
  348. <Row gutter={8}>
  349. <Col span={10}>
  350. <Form.Item
  351. label="副本数量"
  352. name="replicas"
  353. rules={[
  354. {
  355. required: true,
  356. message: '请输入副本数量',
  357. },
  358. {
  359. pattern: /^[1-9]\d*$/,
  360. message: '副本数量必须是正整数',
  361. },
  362. ]}
  363. >
  364. <InputNumber
  365. style={{ width: '100%' }}
  366. placeholder="请输入副本数量"
  367. min={1}
  368. precision={0}
  369. />
  370. </Form.Item>
  371. </Col>
  372. </Row>
  373. <Row gutter={8}>
  374. <Col span={10}>
  375. <Form.Item
  376. label="挂载路径"
  377. name="mount_path"
  378. rules={[
  379. {
  380. required: true,
  381. message: '请输入模型挂载路径',
  382. },
  383. {
  384. pattern: /^\/[a-zA-Z0-9._/-]+$/,
  385. message:
  386. '请输入正确的挂载路径,以斜杠(/)开头,只支持字母、数字、点(.)、下划线(_)、中横线(-)、斜杠(/)',
  387. },
  388. ]}
  389. >
  390. <Input
  391. placeholder="请输入模型挂载路径"
  392. disabled={disabled}
  393. maxLength={64}
  394. showCount
  395. allowClear
  396. />
  397. </Form.Item>
  398. </Col>
  399. </Row>
  400. <Row gutter={8}>
  401. <Col span={10}>
  402. <Form.Item label="环境变量">
  403. <Form.List name="env_variables">
  404. {(fields, { add, remove }) => (
  405. <>
  406. {fields.map(({ key, name, ...restField }, index) => (
  407. <Flex
  408. key={key}
  409. gap="0 8px"
  410. style={{
  411. position: 'relative',
  412. }}
  413. >
  414. <Form.Item
  415. {...restField}
  416. name={[name, 'key']}
  417. style={{ flex: 1 }}
  418. rules={[
  419. {
  420. validator: (_, value) => {
  421. if (!value) {
  422. return Promise.reject(new Error('请输入变量名'));
  423. }
  424. if (!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(value)) {
  425. return Promise.reject(
  426. new Error(
  427. '变量名只支持字母、数字、下划线、中横线并且必须以字母或下划线开头',
  428. ),
  429. );
  430. }
  431. // 判断不能重名
  432. const list = form
  433. .getFieldValue('env_variables')
  434. .filter(
  435. (item: FormEnvVariable | undefined) =>
  436. item !== undefined && item !== null,
  437. );
  438. const names = list.map((item: FormEnvVariable) => item.key);
  439. if (new Set(names).size !== names.length) {
  440. return Promise.reject(new Error('名称不能重复'));
  441. }
  442. return Promise.resolve();
  443. },
  444. },
  445. ]}
  446. >
  447. <Input placeholder="请输入变量名" disabled={disabled} allowClear />
  448. </Form.Item>
  449. <span style={{ lineHeight: '46px' }}>=</span>
  450. <Form.Item
  451. {...restField}
  452. name={[name, 'value']}
  453. style={{ flex: 1 }}
  454. rules={[{ required: true, message: '请输入变量值' }]}
  455. >
  456. <Input placeholder="请输入变量值" disabled={disabled} allowClear />
  457. </Form.Item>
  458. <Flex
  459. style={{
  460. width: '76px',
  461. left: 'calc(100% + 10px)',
  462. height: '46px',
  463. marginBottom: '24px',
  464. position: 'absolute',
  465. }}
  466. align="center"
  467. >
  468. <Button
  469. style={{
  470. marginRight: '3px',
  471. }}
  472. shape="circle"
  473. size="middle"
  474. type="text"
  475. icon={<MinusCircleOutlined />}
  476. disabled={disabled}
  477. onClick={() => {
  478. removeFormListItem(
  479. form,
  480. 'env_variables',
  481. name,
  482. remove,
  483. ['key', 'value'],
  484. '删除后,该环境变量将不可恢复',
  485. );
  486. }}
  487. ></Button>
  488. {index === fields.length - 1 && (
  489. <Button
  490. shape="circle"
  491. size="middle"
  492. type="text"
  493. disabled={disabled}
  494. icon={<PlusCircleOutlined />}
  495. onClick={() => add()}
  496. ></Button>
  497. )}
  498. </Flex>
  499. </Flex>
  500. ))}
  501. {fields.length === 0 && (
  502. <Form.Item className={styles['create-service-version__content__env']}>
  503. <Button
  504. className={styles['create-service-version__content__env__add-btn']}
  505. color="primary"
  506. variant="dashed"
  507. disabled={disabled}
  508. icon={<PlusOutlined />}
  509. block
  510. onClick={() => add()}
  511. >
  512. 环境变量
  513. </Button>
  514. </Form.Item>
  515. )}
  516. </>
  517. )}
  518. </Form.List>
  519. </Form.Item>
  520. </Col>
  521. </Row>
  522. <Form.Item wrapperCol={{ offset: 0, span: 16 }} style={{ marginTop: '20px' }}>
  523. <Button type="primary" htmlType="submit">
  524. {buttonText}
  525. </Button>
  526. <Button
  527. type="default"
  528. htmlType="button"
  529. onClick={cancel}
  530. style={{ marginLeft: '20px' }}
  531. >
  532. 取消
  533. </Button>
  534. </Form.Item>
  535. </Form>
  536. </div>
  537. </div>
  538. </div>
  539. );
  540. }
  541. export default CreateServiceVersion;