mixin.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. import * as R from 'ramda'
  2. import _ from 'lodash'
  3. import { SCHED_POLICY_OPTIONS_MAP, SERVER_TYPE, SELECT_IMAGE_KEY_SUFFIX, LOGIN_TYPES_MAP, NETWORK_OPTIONS_MAP } from '@Compute/constants'
  4. import OsSelect from '@Compute/sections/OsSelect'
  5. import ServerPassword from '@Compute/sections/ServerPassword'
  6. import CpuRadio from '@Compute/sections/CpuRadio'
  7. import MemRadio from '@Compute/sections/MemRadio'
  8. import sku from '@Compute/sections/SKU'
  9. import gpu from '@Compute/sections/GPU/index'
  10. import pci from '@Compute/sections/PCI'
  11. import { Decorator, GenCreateData } from '@Compute/utils/createServer'
  12. import ServerNetwork from '@Compute/sections/ServerNetwork'
  13. import ServerAccount from '@Compute/sections/ServerAccount'
  14. import SchedPolicy from '@Compute/sections/SchedPolicy'
  15. import Bios from '@Compute/sections/BIOS'
  16. import Backup from '@Compute/sections/Backup'
  17. import Duration from '@Compute/sections/Duration'
  18. import InstanceGroups from '@Compute/sections/InstanceGroups'
  19. import DataDisk from '@Compute/sections/DataDisk'
  20. import HostName from '@Compute/sections/HostName'
  21. import storage from '@/utils/storage'
  22. import { WORKFLOW_TYPES } from '@/constants/workflow'
  23. import workflowMixin from '@/mixins/workflow'
  24. import { Manager } from '@/utils/manager'
  25. import { isSuccess } from '@/utils/http'
  26. import NameRepeated from '@/sections/NameRepeated'
  27. import CloudregionZone from '@/sections/CloudregionZone'
  28. import HypervisorRadio from '@/sections/HypervisorRadio'
  29. import DomainProject from '@/sections/DomainProject'
  30. import { getInitialValue } from '@/utils/common/ant'
  31. import { IMAGES_TYPE_MAP } from '@/constants/compute'
  32. import { HYPERVISORS_MAP } from '@/constants'
  33. import i18n from '@/locales'
  34. import { deleteInvalid } from '@/utils/utils'
  35. import { hasSetupKey, isLicense2 } from '@/utils/auth'
  36. import Tag from '../components/Tag'
  37. import SystemDisk from '../components/SystemDisk'
  38. import Servertemplate from '../components/Servertemplate'
  39. import BottomBar from '../components/BottomBar'
  40. import CustomData from '../components/CustomData'
  41. import BastionHost from '../components/BastionHost'
  42. const CreateServerForm = {
  43. wrapperCol: {
  44. md: { span: 18 },
  45. xl: { span: 20 },
  46. xxl: { span: 22 },
  47. },
  48. labelCol: {
  49. md: { span: 6 },
  50. xl: { span: 4 },
  51. xxl: { span: 2 },
  52. },
  53. }
  54. export default {
  55. name: 'IDCCreate',
  56. components: {
  57. OsSelect,
  58. CloudregionZone,
  59. BottomBar,
  60. ServerPassword,
  61. HypervisorRadio,
  62. CpuRadio,
  63. MemRadio,
  64. sku,
  65. ServerNetwork,
  66. SystemDisk,
  67. DataDisk,
  68. gpu,
  69. SchedPolicy,
  70. Bios,
  71. Backup,
  72. DomainProject,
  73. Duration,
  74. InstanceGroups,
  75. Tag,
  76. Servertemplate,
  77. NameRepeated,
  78. ServerAccount,
  79. HostName,
  80. pci,
  81. CustomData,
  82. BastionHost,
  83. },
  84. mixins: [workflowMixin],
  85. props: {
  86. type: {
  87. type: String,
  88. required: true,
  89. validator: val => ['idc', 'private', 'public'].includes(val),
  90. },
  91. initFormData: {
  92. type: Object,
  93. default: () => ({}),
  94. },
  95. isInitForm: {
  96. type: Boolean,
  97. default: false,
  98. },
  99. },
  100. data () {
  101. const decorators = new Decorator(SERVER_TYPE[this.type]).createDecorators(this.initFormData)
  102. const initFd = getInitialValue(decorators)
  103. return {
  104. initSkuData: { name: this.initFormData?.sku },
  105. submiting: false,
  106. errors: {},
  107. formItemLayout: {
  108. wrapperCol: CreateServerForm.wrapperCol,
  109. labelCol: CreateServerForm.labelCol,
  110. },
  111. form: {
  112. fc: this.$form.createForm(this, { onValuesChange: this.onValuesChange }),
  113. fi: { // formInfo 存储着和表单相关的数据
  114. capability: {}, // 可用区下的可用资源
  115. imageMsg: {}, // 当前选中的 image
  116. imageType: '',
  117. cpuMem: {}, // cpu 和 内存 的关联关系
  118. createType: SERVER_TYPE[this.type],
  119. dataDiskDisabled: false, // 数据盘是否禁用
  120. sysDiskDisabled: false, // 系统盘是否禁用
  121. cpuDisabled: false,
  122. memDisabled: false,
  123. dataDiskMedium: '',
  124. networkVpcObj: {},
  125. showCpuSockets: false,
  126. cpuSockets: 1,
  127. },
  128. fd: { hypervisor: '', ...initFd, project: {}, os: '' },
  129. },
  130. decorators,
  131. capabilityParams: {}, // 防止 capability 反复调用,这里对当前的接口参数做记录
  132. price: null,
  133. collapseActive: [],
  134. hostNameValidate: {
  135. validateStatus: '',
  136. errorMsg: '',
  137. },
  138. custom_data: [],
  139. dataDiskInterval: null,
  140. tagDefaultChecked: {},
  141. }
  142. },
  143. provide () {
  144. return {
  145. form: this.form,
  146. }
  147. },
  148. computed: {
  149. isServertemplate () { // 主机模板
  150. return this.$route.query.source === 'servertemplate'
  151. },
  152. loginTypes () { // 主机模板隐藏手工输入密码
  153. let maps = R.clone(LOGIN_TYPES_MAP)
  154. if (this.isWindows) {
  155. delete maps.keypair
  156. }
  157. if (this.isInCloudSphere || this.isSangFor) {
  158. maps = {
  159. image: LOGIN_TYPES_MAP.image,
  160. }
  161. }
  162. const loginTypes = Object.keys(maps)
  163. // if (this.isServertemplate) {
  164. // return loginTypes.filter(val => (val !== LOGIN_TYPES_MAP.password.key && val !== LOGIN_TYPES_MAP.keypair.key))
  165. // }
  166. return loginTypes
  167. },
  168. project_domain () {
  169. return this.form.fd.domain ? this.form.fd.domain.key : this.$store.getters.userInfo.projectDomainId
  170. },
  171. project () {
  172. return this.form.fd.project ? this.form.fd.project.key : this.$store.getters.userInfo.projectId
  173. },
  174. scopeParams () {
  175. if (this.$store.getters.isAdminMode) {
  176. return {
  177. project_domain: this.project_domain,
  178. }
  179. }
  180. return { scope: this.$store.getters.scope }
  181. },
  182. gpuOptions () {
  183. const specs = this.form.fi.capability.specs || {}
  184. const data = specs.isolated_devices || {}
  185. const ret = []
  186. for (const key in data) {
  187. if (data.hasOwnProperty(key)) {
  188. const item = data[key]
  189. if (item.dev_type.startsWith('GPU')) {
  190. ret.push({
  191. ...item,
  192. key: `vendor=${item.vendor}:${item.model}`,
  193. label: `${item.vendor}/${item.model}`,
  194. })
  195. }
  196. }
  197. }
  198. return ret
  199. },
  200. pciDevTypeOptions () {
  201. const specs = this.form.fi.capability.specs || {}
  202. const data = specs.isolated_devices || {}
  203. const values = Object.values(data)
  204. return (this.form.fi?.capability?.pci_model_types || []).filter(item => {
  205. return (item.hypervisor === 'kvm' || item.hypervisor === 'zettakit') && values.some(l => item.dev_type === l.dev_type)
  206. })
  207. },
  208. pciOptions () {
  209. const specs = this.form.fi.capability.specs || {}
  210. const data = specs.isolated_devices || {}
  211. const ret = []
  212. for (const key in data) {
  213. if (data.hasOwnProperty(key)) {
  214. const item = data[key]
  215. if (!item.dev_type.startsWith('USB') && (item.hypervisor === 'kvm' || item.hypervisor === 'zettakit')) {
  216. ret.push({
  217. ...item,
  218. key: `vendor=${item.vendor}:${item.model}`,
  219. label: `${item.vendor}/${item.model}`,
  220. })
  221. }
  222. }
  223. }
  224. return ret
  225. },
  226. backupDisableds () { // 高可用判断哪些宿主机可用
  227. const ret = []
  228. if (this.form.fd.schedPolicyType === SCHED_POLICY_OPTIONS_MAP.host.key) {
  229. ret.push(this.form.fd.schedPolicyHost)
  230. }
  231. if (this.storageHostParams && this.storageHostParams.storageHosts && this.storageHostParams.storageHosts.length) {
  232. this.storageHostParams.storageHosts.map(item => {
  233. ret.push(item.id)
  234. })
  235. }
  236. return ret
  237. },
  238. policyHostDisabled () {
  239. if (this.form.fd.backupEnable) {
  240. return [this.form.fd.backup]
  241. }
  242. return []
  243. },
  244. dataDiskSizes () {
  245. const disk = this.form.fd.dataDiskSizes
  246. return R.is(Object, disk) ? Object.values(disk) : []
  247. },
  248. secgroupParams () {
  249. const params = {
  250. ...this.scopeParams,
  251. }
  252. if (this.type === 'public') { // 公有云
  253. if (R.is(Object, this.form.fd.sku)) {
  254. const cloudregion = this.form.fd.sku.cloudregion_id // 取 sku
  255. if (cloudregion) params.cloudregion_id = cloudregion
  256. }
  257. } else { // 私有云和IDC取 CloudregionZone 组件
  258. const cloudregion = _.get(this.form.fd, 'cloudregion.key')
  259. if (cloudregion) params.cloudregion_id = cloudregion
  260. }
  261. if (this.form.fi.networkVpcObj && this.form.fi.networkVpcObj.id) {
  262. params.vpc_id = this.form.fi.networkVpcObj.id
  263. delete params.cloudregion_id
  264. }
  265. return params
  266. },
  267. showSecgroupBind () {
  268. return this.form.fd.networkType === 'manual'
  269. },
  270. isOpenWorkflow () {
  271. if (this.isServertemplate) return false
  272. return this.checkWorkflowEnabled(WORKFLOW_TYPES.APPLY_MACHINE)
  273. },
  274. isHostImageType () { // 镜像类型为主机镜像
  275. return this.form.fd.imageType === IMAGES_TYPE_MAP.host.key
  276. },
  277. isSnapshotImageType () { // 镜像类型为主机快照
  278. return this.form.fd.imageType === IMAGES_TYPE_MAP.snapshot.key
  279. },
  280. isDomainMode () {
  281. return this.$store.getters.isDomainMode
  282. },
  283. hasMeterService () { // 是否有计费的服务
  284. const { services } = this.$store.getters.userInfo
  285. const meterService = services.find(val => val.type === 'meter')
  286. if (meterService && meterService.status === true) {
  287. return true
  288. }
  289. return false
  290. },
  291. hasBastionService () {
  292. if (isLicense2() && !hasSetupKey(['bastionhost'])) return false
  293. const { services } = this.$store.getters.userInfo
  294. const bastionService = services.find(val => val.type === 'bastionhost')
  295. if (bastionService && bastionService.status === true) {
  296. return true
  297. }
  298. return false
  299. },
  300. cloudregionZoneParams () {
  301. const params = {}
  302. if (this.type === 'public') { // 公有云
  303. if (R.is(Object, this.form.fd.sku)) {
  304. const cloudregion = this.form.fd.sku.cloudregion_id // 取 sku
  305. const zone = this.form.fd.zone // 取 areaSelect 组件
  306. if (cloudregion) params.cloudregion = cloudregion
  307. if (zone) params.zone = zone
  308. }
  309. } else { // 私有云和IDC取 CloudregionZone 组件
  310. const cloudregion = _.get(this.form.fd, 'cloudregion.key')
  311. const zone = _.get(this.form.fd, 'zone.key')
  312. if (cloudregion) params.cloudregion = cloudregion
  313. if (zone) params.zone = zone
  314. }
  315. return params
  316. },
  317. networkVpcParams () {
  318. const zone = _.get(this.form.fd, 'zone.key')
  319. const params = {
  320. // usable: true,
  321. limit: 0,
  322. // show_emulated: true,
  323. manager_id: this.form.fd.cloudprovider,
  324. ...this.scopeParams,
  325. }
  326. if (this.isZStack || this.isInCloudSphere || this.isPve || this.isGoogle || this.isCNware) {
  327. params.show_emulated = true
  328. }
  329. if (zone) {
  330. params.usable = true
  331. params.zone_id = zone
  332. }
  333. return params
  334. },
  335. vpcResource () {
  336. if (R.is(String, this.cloudregionZoneParams.cloudregion)) return `cloudregions/${this.cloudregionZoneParams.cloudregion}/vpcs`
  337. return ''
  338. },
  339. schedtagParams () { // 网络里指定调度标签
  340. return {
  341. limit: 0,
  342. resource_type: 'networks',
  343. ...this.scopeParams,
  344. }
  345. },
  346. policySchedtagParams () { // 高级配置里面调度策略选择 指定调度标签
  347. const ret = {
  348. limit: 0,
  349. 'filter.0': 'resource_type.equals(hosts)',
  350. ...this.scopeParams,
  351. }
  352. const zone = _.get(this.form.fd, 'zone.key')
  353. if (zone) {
  354. ret.zone_id = zone
  355. }
  356. return ret
  357. },
  358. isWindows () {
  359. let isWindows = false
  360. const osType = (_.get(this.form.fi, 'imageMsg.info.properties.os_type') || _.get(this.form.fi, 'imageMsg.properties.os_type') || '').toLowerCase()
  361. const os = (_.get(this.form.fd, 'os') || '').toLowerCase()
  362. if (~[osType, os].indexOf('windows')) {
  363. isWindows = true
  364. }
  365. return isWindows
  366. },
  367. osType () {
  368. let os_type = this.form.fi.imageMsg.info ? this.form.fi.imageMsg.info.properties?.os_type : this.form.fi.imageMsg.properties?.os_type
  369. if (!os_type && this.form.fi.imageMsg.os_type) {
  370. os_type = this.form.fi.imageMsg.os_type
  371. }
  372. return this.isWindows ? 'windows' : os_type?.toLowerCase()
  373. },
  374. enableEip () {
  375. const externalAccessMode = _.get(this.form.fi, 'networkVpcObj.external_access_mode')
  376. if (externalAccessMode === 'none') return false // "eip-distgw" "eip" 是正常可以使用EIP的,"none"不可以
  377. return true
  378. },
  379. isZStack () {
  380. return this.form.fd.hypervisor === HYPERVISORS_MAP.zstack.key
  381. },
  382. isInCloudSphere () {
  383. return this.form.fd.hypervisor === HYPERVISORS_MAP.incloudsphere.key
  384. },
  385. isSangFor () {
  386. return this.form.fd.hypervisor === HYPERVISORS_MAP.sangfor.key
  387. },
  388. isHCSO () {
  389. return this.form.fd.hypervisor === HYPERVISORS_MAP.hcso.key
  390. },
  391. isHCS () {
  392. return this.form.fd.hypervisor === HYPERVISORS_MAP.hcs.key
  393. },
  394. isPve () {
  395. return this.form.fd.hypervisor === HYPERVISORS_MAP.proxmox.key
  396. },
  397. isGoogle () {
  398. return this.form.fd.hypervisor === HYPERVISORS_MAP.google.key || this.hypervisor === HYPERVISORS_MAP.google.key
  399. },
  400. isCNware () {
  401. return this.form.fd.hypervisor === HYPERVISORS_MAP.cnware.key
  402. },
  403. showServerAccount () {
  404. return this.form.fd.loginType !== LOGIN_TYPES_MAP.image.key
  405. },
  406. hostNameTips () {
  407. if (this.isWindows) {
  408. return `${this.$t('compute.host_name_tips')} ${this.$t('compute.validate.windows')}`
  409. } else {
  410. return `${this.$t('compute.host_name_tips')} ${this.$t('compute.validate.others')}`
  411. }
  412. },
  413. showCustomData () {
  414. const showCustomDataHypervisors = [
  415. HYPERVISORS_MAP.kvm.key,
  416. HYPERVISORS_MAP.esxi.key,
  417. HYPERVISORS_MAP.aliyun.key,
  418. HYPERVISORS_MAP.google.key,
  419. HYPERVISORS_MAP.aws.key,
  420. HYPERVISORS_MAP.huawei.key,
  421. HYPERVISORS_MAP.azure.key,
  422. HYPERVISORS_MAP.qcloud.key,
  423. HYPERVISORS_MAP.ksyun.key,
  424. ]
  425. return showCustomDataHypervisors.includes(this.form.fd.hypervisor || this.hypervisor)
  426. },
  427. isOpenSourceVersion () {
  428. return !this.$appConfig.isPrivate
  429. },
  430. },
  431. created () {
  432. this.zoneM = new Manager('zones')
  433. this.serverM = new Manager('servers')
  434. this.servertemplateM = new Manager('servertemplates', 'v2')
  435. this.serverskusM = new Manager('serverskus')
  436. this.schedulerM = new Manager('schedulers', 'v1')
  437. this.zonesM2 = new Manager('zones', 'v2')
  438. this.$bus.$on('VMGetPrice', (price) => {
  439. this.price = price
  440. })
  441. this.$store.dispatch('app/fetchWorkflowEnabledKeys')
  442. },
  443. mounted () {
  444. this.initForm()
  445. },
  446. watch: {
  447. 'form.fi.imageMsg': {
  448. deep: true,
  449. handler (val, oldVal) {
  450. if (R.equals(val, oldVal)) return
  451. this.$nextTick(() => {
  452. if (!this.isInitForm) {
  453. this._resetDataDisk() // 重置数据盘数据
  454. }
  455. })
  456. },
  457. },
  458. isWindows (val) {
  459. const hostName = this.form.fd.hostName
  460. if (hostName) {
  461. this.hostNameValidate = {
  462. ...this.validateHostNameChange(hostName),
  463. }
  464. }
  465. },
  466. isKvm () {
  467. return this.form.fd.hypervisor === 'kvm'
  468. },
  469. },
  470. methods: {
  471. async capability (v, data) { // 可用区查询
  472. const params = {
  473. show_emulated: true,
  474. }
  475. if (this.$store.getters.isAdminMode) {
  476. params.project_domain = data?.extraData?.domain_id
  477. }
  478. return this.zonesM2.get({ id: `${v}/capability`, params })
  479. },
  480. async capability2 (v, data) { // 可用区查询
  481. const params = {
  482. show_emulated: true,
  483. }
  484. if (this.$store.getters.isAdminMode) {
  485. params.project_domain = data?.extraData?.domain_id
  486. }
  487. return new this.$Manager('cloudregions').get({ id: `${v}/capability`, params })
  488. },
  489. async initForm () {
  490. const initData = this.initFormData
  491. if (this.isInitForm && initData.extraData && this.form?.fc) {
  492. if (!this.form.fd.hypervisor) {
  493. this.form.fd.hypervisor = initData.hypervisor
  494. }
  495. try {
  496. if (initData.prefer_zone) {
  497. const { data: capabilityData } = await this.capability(initData.prefer_zone, initData)
  498. this.form.fi.capability = capabilityData
  499. } else if (initData.prefer_region) {
  500. const { data: capabilityData } = await this.capability2(initData.prefer_region, initData)
  501. this.form.fi.capability = capabilityData
  502. }
  503. } catch (error) { }
  504. this.$nextTick(() => {
  505. // 透传设备
  506. if (initData.isolated_devices && initData.isolated_devices.length) {
  507. this.$refs.pciRef.initData(initData.isolated_devices)
  508. }
  509. // 系统盘 高级功能回填
  510. if (this.$refs.systemDiskRef && this.$refs.systemDiskRef.$refs.disk) {
  511. const systemDisk = (initData.disks || []).filter(item => item.disk_type === 'sys')[0] || {}
  512. this.$refs.systemDiskRef.$refs.disk.initData(systemDisk, initData.hypervisor)
  513. }
  514. this.$nextTick(() => {
  515. // 数据盘
  516. if (this.$refs.dataDiskRef) {
  517. const dataDisks = initData.disks.filter(item => item.disk_type === 'data' || item.disk_type === 'swap')
  518. const { medium: dataDiskMedium } = dataDisks[0] || {}
  519. this.dataDiskInterval = setInterval(() => {
  520. dataDisks.forEach((v, i) => {
  521. const { schedtags = [] } = v
  522. this.$refs.dataDiskRef.add({
  523. diskType: v.backend,
  524. disabled: false,
  525. sizeDisabled: false,
  526. medium: dataDiskMedium,
  527. filetype: v.fs,
  528. mountPath: v.mountpoint,
  529. schedtag: schedtags[0]?.id,
  530. policy: schedtags[0]?.strategy,
  531. snapshot: v.snapshot_id,
  532. preallocation: v.preallocation,
  533. autoReset: v.auto_reset,
  534. ...v,
  535. size: v.size / 1024,
  536. })
  537. })
  538. clearInterval(this.dataDiskInterval)
  539. this.dataDiskInterval = null
  540. }, 500)
  541. }
  542. })
  543. // 初始化网络
  544. if (this.$refs.networkRef && initData.nets) {
  545. let initNetworkType = NETWORK_OPTIONS_MAP.default.key
  546. if (initData.nets[0] && initData.nets[0].hasOwnProperty('exit') && !initData.nets[0].exit) {
  547. initNetworkType = NETWORK_OPTIONS_MAP.default.key
  548. } else if (initData.nets[0] && initData.nets[0].hasOwnProperty('network') && initData.extraData?.nets && initData.extraData?.nets[0] && initData.extraData?.nets[0].hasOwnProperty('network')) {
  549. initNetworkType = NETWORK_OPTIONS_MAP.manual.key
  550. } else {
  551. initNetworkType = NETWORK_OPTIONS_MAP.schedtag.key
  552. }
  553. this.form.fc.setFieldsValue({
  554. networkType: initNetworkType,
  555. })
  556. this.$refs.networkRef.change({ target: { value: initNetworkType }, name: 'default' })
  557. if (initNetworkType === NETWORK_OPTIONS_MAP.manual.key) {
  558. this.$nextTick(() => {
  559. if (this.$refs.networkRef.$refs.networkConfigRef) {
  560. this.$refs.networkRef.$refs.networkConfigRef.initData(initData.extraData.nets)
  561. }
  562. })
  563. }
  564. if (initNetworkType === NETWORK_OPTIONS_MAP.schedtag.key) {
  565. this.$nextTick(() => {
  566. if (this.$refs.networkRef.$refs.networkSchedtagRef) {
  567. this.$refs.networkRef.$refs.networkSchedtagRef.initData(initData.nets)
  568. }
  569. })
  570. }
  571. }
  572. // 高级配置
  573. if (initData.hostname || initData.eip_charge_type || initData.public_ip_charge_type || initData.prefer_host || initData.schedtags || initData.secgroups || initData.bios || initData.vdi || initData.vga || initData.is_daemon || initData.groups || initData.encrypt_key_new || initData.keypair || initData.user_data || initData.bastion_server) {
  574. this.collapseActive = ['1']
  575. this.$nextTick(() => {
  576. this.form.fc.setFieldsValue({
  577. hostName: initData.hostname,
  578. })
  579. // eip
  580. if (this.$refs.eipConfigRef) {
  581. this.$refs.eipConfigRef.initData(initData)
  582. }
  583. // 安全组
  584. if (initData.secgroups && initData.secgroups.length) {
  585. setTimeout(() => {
  586. this.form.fc.setFieldsValue({
  587. secgroup_type: 'bind',
  588. secgroup: initData.secgroups,
  589. })
  590. }, 2000)
  591. }
  592. // 调度策略
  593. if (this.$refs.schedPolicyRef) {
  594. if (initData.prefer_host) {
  595. this.$refs.schedPolicyRef.change({ target: { value: 'host' }, name: 'default' })
  596. }
  597. if (initData.schedtags && initData.schedtags.length) {
  598. this.$refs.schedPolicyRef.change({ target: { value: 'schedtag' }, name: 'default' })
  599. setTimeout(() => {
  600. if (this.$refs.schedPolicyRef.$refs.policySchedtagRef) {
  601. this.$refs.schedPolicyRef.$refs.policySchedtagRef.initData(initData.schedtags)
  602. }
  603. }, 1000)
  604. }
  605. }
  606. // 自定义数据
  607. if (initData.user_data) {
  608. if (this.$refs.customData) {
  609. this.$refs.customData.handleMirrorDataChange(initData.user_data)
  610. }
  611. }
  612. // 堡垒机
  613. if (initData.bastion_server && this.$refs.bastionHostRef) {
  614. this.$refs.bastionHostRef.initData(initData.bastion_server)
  615. }
  616. })
  617. }
  618. // 初始化标签
  619. if (initData.__meta__) {
  620. const ret = {}
  621. R.forEachObjIndexed((value, key) => {
  622. ret[key] = R.is(Array, value) ? value : [value]
  623. }, initData.__meta__)
  624. this.tagDefaultChecked = ret
  625. }
  626. })
  627. }
  628. },
  629. baywatch (props, watcher) {
  630. const iterator = function (prop) {
  631. this.$watch(prop, watcher)
  632. }
  633. props.forEach(iterator, this)
  634. },
  635. updateFi (fiItems) { // 子组件更新fi
  636. if (R.is(Object, fiItems)) {
  637. R.forEachObjIndexed((item, key) => {
  638. this.$set(this.form.fi, key, item)
  639. }, fiItems)
  640. }
  641. },
  642. submit (e) {
  643. e.preventDefault()
  644. this.validateForm()
  645. .then(async formData => {
  646. this.submiting = true
  647. const genCreteData = new GenCreateData(formData, this.form.fi)
  648. const data = genCreteData.all()
  649. if (data.custom_data_type) {
  650. delete data.custom_data_type
  651. const { customData } = this.$refs.customData
  652. if (customData.length) {
  653. data.user_data = customData
  654. }
  655. }
  656. if (this.form.fd.bastion_host_enable) {
  657. const bastionServer = this.getBationServerData()
  658. data.bastion_server = bastionServer
  659. }
  660. data.extraData.reason = this.form.fd?.reason
  661. data.extraData.formType = this.type
  662. data.extraData.__resource_type__ = 'server'
  663. if (this.isServertemplate) { // 创建主机模板
  664. this.doCreateServertemplate(data)
  665. } else if (this.isOpenWorkflow) { // 提交工单
  666. await this.checkCreateData(data)
  667. await this.doForecast(genCreteData, data)
  668. await this.doCreateWorkflow(data)
  669. } else { // 创建主机
  670. await this.checkCreateData(data)
  671. await this.doForecast(genCreteData, data)
  672. await this.createServer(data)
  673. }
  674. })
  675. .catch(error => {
  676. throw error
  677. })
  678. .finally(() => {
  679. this.submiting = false
  680. })
  681. },
  682. doCreateServertemplate (data) {
  683. const { project_id, description, ...rest } = data
  684. const templateData = {
  685. name: this.form.fc.getFieldValue('servertemplate_name'),
  686. project: project_id,
  687. description,
  688. content: {
  689. ...rest,
  690. },
  691. }
  692. this.servertemplateM.create({ data: templateData })
  693. .then(() => {
  694. this.$message.success(i18n.t('compute.text_423'))
  695. this.$router.push('/servertemplate')
  696. })
  697. .catch((error) => {
  698. throw error
  699. })
  700. },
  701. async doCreateWorkflow (data) {
  702. const { workflow = '', order_set_id = '', order_set_idx = '' } = this.$route.query
  703. if (order_set_id && workflow) {
  704. const res = await new this.$Manager('resource_order_sets').get({ id: order_set_id })
  705. if (res.data && res.data.parameters && res.data.parameters[order_set_idx]) {
  706. const parameters = [...res.data.parameters]
  707. parameters[order_set_idx] = { ...res.data.parameters[order_set_idx], count: data.__count__, parameter: { ...data, price: this.price } }
  708. await new this.$Manager('resource_order_sets').update({ id: order_set_id, data: { parameters } })
  709. this.$message.success(this.$t('common.success'))
  710. this.$router.push('/workflow')
  711. return
  712. }
  713. return
  714. }
  715. const variables = {
  716. process_definition_key: WORKFLOW_TYPES.APPLY_MACHINE,
  717. initiator: this.$store.getters.userInfo.id,
  718. description: this.form.fd.reason,
  719. 'server-create-paramter': JSON.stringify(data),
  720. price: this.price,
  721. }
  722. this._getProjectDomainInfo(variables)
  723. if (workflow) {
  724. new this.$Manager('historic-process-instances', 'v1')
  725. .update({ id: `${workflow}/variables`, data: { variables } })
  726. .then(() => {
  727. this.$message.success(i18n.t('compute.text_1045', [data.generate_name]))
  728. this.$router.push('/workflow')
  729. })
  730. .catch((error) => {
  731. throw error
  732. })
  733. } else {
  734. new this.$Manager('process-instances', 'v1')
  735. .create({ data: { variables } })
  736. .then(() => {
  737. this.$message.success(i18n.t('compute.text_1045', [data.generate_name]))
  738. this.$router.push('/workflow')
  739. })
  740. .catch((error) => {
  741. throw error
  742. })
  743. }
  744. },
  745. async checkCreateData (data) {
  746. return new this.$Manager('servers').create({ data: { ...data, dry_run: true } })
  747. },
  748. doForecast (genCreateData, data) {
  749. return new Promise((resolve, reject) => {
  750. this.schedulerM.rpc({ methodname: 'DoForecast', params: data })
  751. .then(res => {
  752. if (res.data.can_create) {
  753. resolve(data)
  754. } else {
  755. this.errors = genCreateData.getForecastErrors(res.data)
  756. reject(this.errors)
  757. }
  758. })
  759. .catch(err => {
  760. this.$message.error(i18n.t('compute.text_321', [err]))
  761. reject(err)
  762. })
  763. })
  764. },
  765. createServer (data) {
  766. delete data.vcpu_count
  767. delete data.vmem_size
  768. return this.serverM.create({ data })
  769. .then(res => {
  770. if (R.is(Array, data.disks)) {
  771. const imageObj = data.disks.find(val => val.disk_type === 'sys')
  772. if (R.is(Object, imageObj)) {
  773. const image = imageObj.image_id
  774. storage.set(`${this.form.fi.createType}${SELECT_IMAGE_KEY_SUFFIX}`, `${this.form.fd.os}:${image}`)
  775. }
  776. }
  777. if (isSuccess(res)) {
  778. this.$message.success(i18n.t('compute.text_322'))
  779. }
  780. this.$store.commit('keepAlive/ADD_DELAY_EVENT', { name: 'VMInstanceListRefresh' })
  781. this.$router.push('/vminstance')
  782. })
  783. .catch(error => {
  784. throw error
  785. })
  786. },
  787. validateForm () {
  788. return new Promise((resolve, reject) => {
  789. this.form.fc.validateFieldsAndScroll({ scroll: { alignWithTop: true, offsetTop: 100 } }, (err, values) => {
  790. if (!err) {
  791. resolve(values)
  792. } else {
  793. this.collapseActive = ['1'] // 仅仅在报错的时候展开高级配置
  794. reject(err)
  795. }
  796. })
  797. })
  798. },
  799. cpuChange (cpu) {
  800. const memOpts = this.form.fi.cpuMem.cpu_mems_mb[cpu]
  801. if (!memOpts || !memOpts.length) { // 没有内存Opts,则内存为0
  802. let vcpu = cpu
  803. if (!this.form.fi.cpuMem.cpus.includes(cpu)) { // CPU的Opts不包括cpu的话
  804. if (this.form.fi.cpuMem.cpus && this.form.fi.cpuMem.cpus.length) { // 如果CPU的Opts有值
  805. vcpu = this.form.fi.cpuMem.cpus[0]
  806. } else { // 否则为0
  807. vcpu = 0
  808. }
  809. }
  810. this.form.fc.setFieldsValue({
  811. vcpu,
  812. vmem: 0,
  813. })
  814. return
  815. } else if (this.form.fc.getFieldValue('vcpu') !== cpu) { // 因之前未获取cpu设置为0,这一步设置回来
  816. this.form.fc.setFieldsValue({
  817. vcpu: cpu,
  818. })
  819. }
  820. this.form.fi.cpuMem.mems_mb = memOpts
  821. let defaultMem = 2048
  822. const currentMem = this.form.fc.getFieldValue('vmem')
  823. if (currentMem && this.form.fi.cpuMem.mems_mb.includes(currentMem)) {
  824. return
  825. }
  826. if (!this.form.fi.cpuMem.mems_mb.includes(2048)) { // 如果返回值不包括默认内存2G,选择第一项
  827. defaultMem = memOpts[0]
  828. }
  829. this.form.fc.setFieldsValue({
  830. vmem: defaultMem,
  831. })
  832. },
  833. _getProjectDomainInfo (variables) {
  834. variables.project = this.form.fd.project.key
  835. if (!variables.project) {
  836. variables.project = this.$store.getters.userInfo.projectName
  837. }
  838. variables.project_domain = _.get(this.form.fd, 'domain.label')
  839. if (!variables.project_domain) {
  840. variables.project_domain = this.$store.getters.userInfo.projectDomain
  841. }
  842. },
  843. _resetDataDisk () { // 重置数据盘
  844. const formValue = this.form.fc.getFieldsValue()
  845. if (formValue.dataDiskSizes) {
  846. const dataDiskKeys = Object.keys(formValue.dataDiskSizes)
  847. dataDiskKeys.forEach(key => this.$refs.dataDiskRef.decrease(key))
  848. }
  849. },
  850. _setNewFieldToFd (newField, formValue) { // vue-ant-form change 后赋值 fd
  851. const changeKeys = Object.keys(newField)
  852. R.forEachObjIndexed((item, key) => {
  853. this.$set(this.form.fd, key, item)
  854. }, newField)
  855. if (changeKeys.some(val => val.includes('dataDiskSizes'))) { // 动态赋值默认值的表单需要单独处理
  856. this.$set(this.form.fd, 'dataDiskSizes', formValue.dataDiskSizes)
  857. }
  858. },
  859. networkResourceMapper (list) {
  860. return list
  861. .map(val => {
  862. const remain = val.ports - val.ports_used
  863. if (remain <= 0) {
  864. return {
  865. ...val,
  866. __disabled: true,
  867. }
  868. }
  869. return val
  870. })
  871. .sort((a, b) => (b.ports - b.ports_used) - (a.ports - a.ports_used))
  872. },
  873. countBlur () {
  874. const count = this.form.fc.getFieldValue(this.decorators.count[0])
  875. if (!count) {
  876. this.form.fc.setFieldsValue({
  877. [this.decorators.count[0]]: 1,
  878. })
  879. }
  880. },
  881. fetchDomainCallback () {
  882. const domain = this.$route.query.domain_id
  883. if (!R.isNil(domain) && !R.isEmpty(domain)) {
  884. this.form.fc.setFieldsValue({
  885. domain: { key: domain },
  886. })
  887. }
  888. },
  889. fetchProjectCallback () {
  890. const project = this.$route.query.tenant_id
  891. if (!R.isNil(project) && !R.isEmpty(project)) {
  892. this.form.fc.setFieldsValue({
  893. project: { key: project },
  894. })
  895. }
  896. },
  897. validateHostNameChange (v) {
  898. const error = {
  899. validateStatus: 'success',
  900. errorMsg: null,
  901. }
  902. if (!v) return error
  903. if (this.isWindows) {
  904. if (v.length < 2 || v.length > 15) {
  905. error.validateStatus = 'error'
  906. error.errorMsg = this.$t('compute.validate.windows')
  907. return error
  908. }
  909. if (!/^[a-z0-9A-Z-]+$/.test(v)) {
  910. error.validateStatus = 'error'
  911. error.errorMsg = this.$t('compute.validate.windows')
  912. return error
  913. }
  914. if (/^[0-9]+$/.test(v)) { // 不能仅仅使用数字
  915. error.validateStatus = 'error'
  916. error.errorMsg = this.$t('compute.validate.others')
  917. return error
  918. }
  919. if (/(-)\1+/.test(v)) { // 不能连续使用连字符
  920. error.validateStatus = 'error'
  921. error.errorMsg = this.$t('compute.validate.others')
  922. return error
  923. }
  924. if (/^(?=(-)).*/.test(v)) { // 不能以连字符开头
  925. error.validateStatus = 'error'
  926. error.errorMsg = this.$t('compute.validate.others')
  927. return error
  928. }
  929. if (/.*?(-)$/.test(v)) { // 不能以连字符结尾
  930. error.validateStatus = 'error'
  931. error.errorMsg = this.$t('compute.validate.others')
  932. return error
  933. }
  934. } else {
  935. if (v.length < 2 || v.length > 60) {
  936. error.validateStatus = 'error'
  937. error.errorMsg = this.$t('compute.validate.others')
  938. }
  939. if (!/^[a-z0-9A-Z.-]+$/.test(v)) {
  940. error.validateStatus = 'error'
  941. error.errorMsg = this.$t('compute.validate.others')
  942. return error
  943. }
  944. if (/(\.|-)\1+/.test(v)) { // 不能连续使用点号或连字符
  945. error.validateStatus = 'error'
  946. error.errorMsg = this.$t('compute.validate.others')
  947. return error
  948. }
  949. if (/^(?=(\.|-)).*/.test(v)) { // 不能以点号或连字符开头
  950. error.validateStatus = 'error'
  951. error.errorMsg = this.$t('compute.validate.others')
  952. return error
  953. }
  954. if (/.*?(\.|-)$/.test(v)) { // 不能以点号或连字符结尾
  955. error.validateStatus = 'error'
  956. error.errorMsg = this.$t('compute.validate.others')
  957. return error
  958. }
  959. }
  960. return error
  961. },
  962. handleHostNameChange (v) {
  963. this.hostNameValidate = {
  964. ...this.validateHostNameChange(v),
  965. }
  966. },
  967. getBationServerData () {
  968. const {
  969. bastion_host_id,
  970. bastion_org_id,
  971. nodes,
  972. port,
  973. privileged_accounts,
  974. accounts,
  975. bastion_domain_id,
  976. reason,
  977. } = this.form.fd
  978. return {
  979. bastion_host_id,
  980. bastion_org_id,
  981. nodes,
  982. port,
  983. description: reason,
  984. accounts: [privileged_accounts].concat(accounts),
  985. bastion_domain_id,
  986. }
  987. },
  988. addShopCart () {
  989. this.validateForm()
  990. .then(async formData => {
  991. this.submiting = true
  992. const genCreateData = new GenCreateData(formData, this.form.fi)
  993. const data = genCreateData.all()
  994. if (this.form.fd.bastion_host_enable) {
  995. const bastionServer = this.getBationServerData()
  996. data.bastion_server = bastionServer
  997. }
  998. if (data.custom_data_type) {
  999. delete data.custom_data_type
  1000. const { customData } = this.$refs.customData
  1001. if (customData.length) {
  1002. data.user_data = customData
  1003. }
  1004. }
  1005. data.extraData.reason = this.form.fd?.reason
  1006. data.extraData.formType = this.type
  1007. data.extraData.__resource_type__ = 'server'
  1008. const { __count__, ...parameter } = deleteInvalid(data)
  1009. const shopCart = {
  1010. action: 'create',
  1011. auto_execute: true,
  1012. count: __count__,
  1013. resource: 'servers',
  1014. user_id: this.$store.getters.userInfo.id,
  1015. parameter: {
  1016. ...parameter,
  1017. price: this.price,
  1018. },
  1019. }
  1020. this._getProjectDomainInfo(shopCart)
  1021. this.$message.success(this.$t('common.success'))
  1022. this.$store.commit('shopcart/ADD_SHOP_CART', shopCart)
  1023. })
  1024. },
  1025. handleCancel () {
  1026. this.$router.push({
  1027. name: this.isServertemplate ? 'Servertemplate' : 'VMInstanceIndex',
  1028. })
  1029. },
  1030. },
  1031. }