mixin.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import * as R from 'ramda'
  2. import _ from 'lodash'
  3. import { mapGetters } from 'vuex'
  4. import { SCHED_POLICY_OPTIONS_MAP, SERVER_TYPE, LOGIN_TYPES_MAP } from '@Compute/constants'
  5. import OsSelect from '@Compute/sections/OsSelect'
  6. import ServerPassword from '@Compute/sections/ServerPassword'
  7. import CpuRadio from '@Compute/sections/CpuRadio'
  8. import MemRadio from '@Compute/sections/MemRadio'
  9. import sku from '@Compute/sections/SKU'
  10. import gpu from '@Compute/sections/GPU/index'
  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 storage from '@/utils/storage'
  21. import { WORKFLOW_TYPES } from '@/constants/workflow'
  22. import workflowMixin from '@/mixins/workflow'
  23. import { Manager } from '@/utils/manager'
  24. import NameRepeated from '@/sections/NameRepeated'
  25. import CloudregionZone from '@/sections/CloudregionZone'
  26. import HypervisorRadio from '@/sections/HypervisorRadio'
  27. import DomainProject from '@/sections/DomainProject'
  28. import { getInitialValue } from '@/utils/common/ant'
  29. import { IMAGES_TYPE_MAP } from '@/constants/compute'
  30. import { HYPERVISORS_MAP } from '@/constants'
  31. import i18n from '@/locales'
  32. import { PRICE_COMPARA_KEY_SUFFIX } from '@Cloudenv/constants'
  33. import { uuid } from '@/utils/utils'
  34. import { currencyUnitMap } from '@/constants/currency'
  35. import BottomBar from '../components/BottomBar'
  36. import SystemDisk from '../components/SystemDisk'
  37. import Tag from '../components/Tag'
  38. const CreateServerForm = {
  39. wrapperCol: {
  40. md: { span: 18 },
  41. xl: { span: 20 },
  42. xxl: { span: 22 },
  43. },
  44. labelCol: {
  45. md: { span: 6 },
  46. xl: { span: 4 },
  47. xxl: { span: 2 },
  48. },
  49. }
  50. export default {
  51. name: 'IDCCreate',
  52. components: {
  53. OsSelect,
  54. CloudregionZone,
  55. BottomBar,
  56. ServerPassword,
  57. HypervisorRadio,
  58. CpuRadio,
  59. MemRadio,
  60. sku,
  61. ServerNetwork,
  62. SystemDisk,
  63. DataDisk,
  64. gpu,
  65. SchedPolicy,
  66. Bios,
  67. Backup,
  68. DomainProject,
  69. Duration,
  70. InstanceGroups,
  71. Tag,
  72. NameRepeated,
  73. ServerAccount,
  74. },
  75. mixins: [workflowMixin],
  76. props: {
  77. type: {
  78. type: String,
  79. required: true,
  80. validator: val => ['idc', 'private', 'public'].includes(val),
  81. },
  82. },
  83. data () {
  84. const decorators = new Decorator(SERVER_TYPE[this.type]).createDecorators()
  85. const initFd = getInitialValue(decorators)
  86. return {
  87. submiting: false,
  88. errors: {},
  89. formItemLayout: {
  90. wrapperCol: CreateServerForm.wrapperCol,
  91. labelCol: CreateServerForm.labelCol,
  92. },
  93. form: {
  94. fc: this.$form.createForm(this, { onValuesChange: this.onValuesChange }),
  95. fi: { // formInfo 存储着和表单相关的数据
  96. capability: {}, // 可用区下的可用资源
  97. imageMsg: {}, // 当前选中的 image
  98. cpuMem: {}, // cpu 和 内存 的关联关系
  99. createType: SERVER_TYPE[this.type],
  100. dataDiskDisabled: false, // 数据盘是否禁用
  101. sysDiskDisabled: false, // 系统盘是否禁用
  102. cpuDisabled: false,
  103. memDisabled: false,
  104. },
  105. fd: { ...initFd, os: '' },
  106. },
  107. decorators: {
  108. ...decorators,
  109. name: [
  110. 'name',
  111. {
  112. initialValue: '',
  113. rules: [
  114. { required: false, message: i18n.t('compute.text_210') },
  115. ],
  116. },
  117. ],
  118. },
  119. capabilityParams: {}, // 防止 capability 反复调用,这里对当前的接口参数做记录
  120. price: null,
  121. collapseActive: [],
  122. }
  123. },
  124. provide () {
  125. return {
  126. form: this.form,
  127. }
  128. },
  129. computed: {
  130. ...mapGetters(['userInfo', 'l3PermissionEnable', 'isAdminMode']),
  131. loginTypes () { // 主机模板隐藏手工输入密码
  132. const maps = R.clone(LOGIN_TYPES_MAP)
  133. if (this.isWindows) {
  134. delete maps.keypair
  135. }
  136. const loginTypes = Object.keys(maps)
  137. // if (this.isServertemplate) {
  138. // return loginTypes.filter(val => (val !== LOGIN_TYPES_MAP.password.key && val !== LOGIN_TYPES_MAP.keypair.key))
  139. // }
  140. return loginTypes
  141. },
  142. project_domain () {
  143. return this.form.fd.domain ? this.form.fd.domain.key : this.$store.getters.userInfo.projectDomainId
  144. },
  145. project () {
  146. return this.form.fd.project ? this.form.fd.project.key : this.$store.getters.userInfo.projectId
  147. },
  148. scopeParams () {
  149. if (this.$store.getters.isAdminMode) {
  150. return {
  151. project_domain: this.project_domain,
  152. }
  153. }
  154. return { scope: this.$store.getters.scope }
  155. },
  156. gpuOptions () {
  157. const specs = this.form.fi.capability.specs || {}
  158. const data = specs.isolated_devices || {}
  159. const ret = []
  160. for (const key in data) {
  161. if (data.hasOwnProperty(key)) {
  162. const item = data[key]
  163. ret.push({
  164. ...item,
  165. key: `vendor=${item.vendor}:${item.model}`,
  166. label: `${item.vendor}/${item.model}`,
  167. })
  168. }
  169. }
  170. return ret
  171. },
  172. backupDisableds () { // 高可用判断哪些宿主机可用
  173. if (this.form.fd.schedPolicyType === SCHED_POLICY_OPTIONS_MAP.host.key) {
  174. return [this.form.fd.schedPolicyHost]
  175. }
  176. return []
  177. },
  178. policyHostDisabled () {
  179. if (this.form.fd.backupEnable) {
  180. return [this.form.fd.backup]
  181. }
  182. return []
  183. },
  184. dataDiskSizes () {
  185. const disk = this.form.fd.dataDiskSizes
  186. return R.is(Object, disk) ? Object.values(disk) : []
  187. },
  188. secgroupParams () {
  189. return this.scopeParams
  190. },
  191. isOpenWorkflow () {
  192. if (this.isServertemplate) return false
  193. return this.checkWorkflowEnabled(WORKFLOW_TYPES.APPLY_MACHINE)
  194. },
  195. isHostImageType () { // 镜像类型为主机镜像
  196. return this.form.fd.imageType === IMAGES_TYPE_MAP.host.key
  197. },
  198. isSnapshotImageType () { // 镜像类型为主机快照
  199. return this.form.fd.imageType === IMAGES_TYPE_MAP.snapshot.key
  200. },
  201. isDomainMode () {
  202. return this.$store.getters.isDomainMode
  203. },
  204. hasMeterService () { // 是否有计费的服务
  205. const { services } = this.$store.getters.userInfo
  206. const meterService = services.find(val => val.type === 'meter')
  207. if (meterService && meterService.status === true) {
  208. return true
  209. }
  210. return false
  211. },
  212. cloudregionZoneParams () {
  213. const params = {}
  214. if (this.type === 'public') { // 公有云
  215. if (R.is(Object, this.form.fd.sku)) {
  216. const cloudregion = this.form.fd.sku.cloudregion_id // 取 sku
  217. const zone = this.form.fd.zone // 取 areaSelect 组件
  218. if (cloudregion) params.cloudregion = cloudregion
  219. if (zone) params.zone = zone
  220. }
  221. } else { // 私有云和IDC取 CloudregionZone 组件
  222. const cloudregion = _.get(this.form.fd, 'cloudregion.key')
  223. const zone = _.get(this.form.fd, 'zone.key')
  224. if (cloudregion) params.cloudregion = cloudregion
  225. if (zone) params.zone = zone
  226. }
  227. return params
  228. },
  229. networkVpcParams () {
  230. const params = {
  231. // usable: true,
  232. limit: 0,
  233. // show_emulated: true,
  234. ...this.scopeParams,
  235. }
  236. if (this.isZStack) {
  237. params.show_emulated = true
  238. }
  239. return params
  240. },
  241. vpcResource () {
  242. if (R.is(String, this.cloudregionZoneParams.cloudregion)) return `cloudregions/${this.cloudregionZoneParams.cloudregion}/vpcs`
  243. return ''
  244. },
  245. schedtagParams () { // 网络里指定调度标签
  246. return {
  247. limit: 0,
  248. resource_type: 'networks',
  249. ...this.scopeParams,
  250. }
  251. },
  252. policySchedtagParams () { // 高级配置里面调度策略选择 指定调度标签
  253. const ret = {
  254. limit: 0,
  255. 'filter.0': 'resource_type.equals(hosts)',
  256. ...this.scopeParams,
  257. }
  258. const zone = _.get(this.form.fd, 'zone.key')
  259. if (zone) {
  260. ret.zone_id = zone
  261. }
  262. return ret
  263. },
  264. isWindows () {
  265. let isWindows = false
  266. const osType = (_.get(this.form.fi, 'imageMsg.info.properties.os_type') || '').toLowerCase()
  267. const os = (_.get(this.form.fd, 'os') || '').toLowerCase()
  268. if (~[osType, os].indexOf('windows')) {
  269. isWindows = true
  270. }
  271. return isWindows
  272. },
  273. osType () {
  274. return this.isWindows ? 'windows' : 'linux'
  275. },
  276. enableEip () {
  277. const externalAccessMode = _.get(this.form.fi, 'networkVpcObj.external_access_mode')
  278. if (externalAccessMode === 'none') return false // "eip-distgw" "eip" 是正常可以使用EIP的,"none"不可以
  279. return true
  280. },
  281. isZStack () {
  282. return this.form.fd.hypervisor === HYPERVISORS_MAP.zstack.key
  283. },
  284. showServerAccount () {
  285. return this.form.fd.loginType !== LOGIN_TYPES_MAP.image.key
  286. },
  287. },
  288. created () {
  289. this.zoneM = new Manager('zones')
  290. this.serverM = new Manager('servers')
  291. this.servertemplateM = new Manager('servertemplates', 'v2')
  292. this.serverskusM = new Manager('serverskus')
  293. this.schedulerM = new Manager('schedulers', 'v1')
  294. this.$bus.$on('VMGetPrice', (price) => {
  295. this.price = price
  296. })
  297. this.$store.dispatch('app/fetchWorkflowEnabledKeys')
  298. },
  299. watch: {
  300. 'form.fi.imageMsg': {
  301. deep: true,
  302. handler (val, oldVal) {
  303. if (R.equals(val, oldVal)) return
  304. this.$nextTick(() => {
  305. this._resetDataDisk() // 重置数据盘数据
  306. })
  307. },
  308. },
  309. },
  310. methods: {
  311. baywatch (props, watcher) {
  312. const iterator = function (prop) {
  313. this.$watch(prop, watcher)
  314. }
  315. props.forEach(iterator, this)
  316. },
  317. updateFi (fiItems) { // 子组件更新fi
  318. if (R.is(Object, fiItems)) {
  319. R.forEachObjIndexed((item, key) => {
  320. this.$set(this.form.fi, key, item)
  321. }, fiItems)
  322. }
  323. },
  324. submit (e) {
  325. e.preventDefault()
  326. this.validateForm()
  327. .then(async formData => {
  328. this.submiting = true
  329. const genCreteData = new GenCreateData(formData, this.form.fi)
  330. this.doAddToList(genCreteData)
  331. })
  332. .catch(error => {
  333. this.submiting = false
  334. throw error
  335. })
  336. },
  337. doAddToList (genCreateData) {
  338. const {
  339. sku,
  340. count,
  341. duration,
  342. zone,
  343. hypervisor,
  344. provider,
  345. cloudregion,
  346. billType,
  347. } = this.form.fd
  348. const getPrice = (originPrice) => {
  349. if (isNaN(parseFloat(originPrice))) {
  350. return '-'
  351. }
  352. let currency = currencyUnitMap.CNY.sign
  353. if (sku.currency && currencyUnitMap[sku.currency]) {
  354. currency = currencyUnitMap[sku.currency].sign
  355. }
  356. return `${currency}${parseFloat(originPrice).toFixed(2)}`
  357. }
  358. const getBrand = (v) => {
  359. const vs = {
  360. kvm: 'OneCloud',
  361. esxi: 'VMware',
  362. zstack: 'ZStack',
  363. openstack: 'OpenStack',
  364. }
  365. return vs[v.toLowerCase()] || v
  366. }
  367. const getDuration = (v) => {
  368. if (billType === 'quantity') return '1h'
  369. return v
  370. }
  371. const { dataDisk, dataDiskLabel, systemDisk, config, originPrice } = this.$refs.bottomBarRef
  372. const data = {
  373. id: uuid(),
  374. uid: this.userInfo.id,
  375. // 资源类型, 配置, 系统盘, 数据盘, 平台, 区域, 计费模式, 购买数量, 购买时长, 费用估算
  376. type: 'server',
  377. instance_type: sku.name,
  378. config,
  379. dataDisk: `${dataDisk}GB ${dataDiskLabel}`,
  380. systemDisk,
  381. brand: getBrand(hypervisor || provider),
  382. region: cloudregion?.label || sku.region,
  383. zone: zone?.label || sku.zone,
  384. billing_type: billType === 'package' ? 'prepaid' : 'postpaid', // "postpaid": "按量付费", "prepaid": "包年包月"
  385. count,
  386. duration: getDuration(duration),
  387. fee: getPrice(originPrice),
  388. }
  389. this.submiting = true
  390. let serverPriceComparator = storage.get(PRICE_COMPARA_KEY_SUFFIX) || []
  391. serverPriceComparator = serverPriceComparator.filter(v => v.uid === data.uid)
  392. storage.set(PRICE_COMPARA_KEY_SUFFIX, [data].concat(serverPriceComparator))
  393. this.$message.success(i18n.t('common.success'))
  394. this.$router.push('/pricecomparator')
  395. },
  396. validateForm () {
  397. return new Promise((resolve, reject) => {
  398. this.form.fc.validateFieldsAndScroll({ scroll: { alignWithTop: true, offsetTop: 100 } }, (err, values) => {
  399. if (!err) {
  400. resolve(values)
  401. } else {
  402. this.collapseActive = ['1'] // 仅仅在报错的时候展开高级配置
  403. reject(err)
  404. }
  405. })
  406. })
  407. },
  408. cpuChange (cpu) {
  409. const memOpts = this.form.fi.cpuMem.cpu_mems_mb[cpu]
  410. if (!memOpts || !memOpts.length) { // 没有内存Opts,则内存为0
  411. let vcpu = cpu
  412. if (!this.form.fi.cpuMem.cpus.includes(cpu)) { // CPU的Opts不包括cpu的话
  413. if (this.form.fi.cpuMem.cpus && this.form.fi.cpuMem.cpus.length) { // 如果CPU的Opts有值
  414. vcpu = this.form.fi.cpuMem.cpus[0]
  415. } else { // 否则为0
  416. vcpu = 0
  417. }
  418. }
  419. this.form.fc.setFieldsValue({
  420. vcpu,
  421. vmem: 0,
  422. })
  423. return
  424. }
  425. this.form.fi.cpuMem.mems_mb = memOpts
  426. let defaultMem = 2048
  427. if (!this.form.fi.cpuMem.mems_mb.includes(2048)) { // 如果返回值不包括默认内存2G,选择第一项
  428. defaultMem = memOpts[0]
  429. }
  430. this.form.fc.setFieldsValue({
  431. vcpu: cpu,
  432. vmem: defaultMem,
  433. })
  434. },
  435. _getProjectDomainInfo (variables) {
  436. variables.project = this.form.fd.project.key
  437. if (!variables.project) {
  438. variables.project = this.$store.getters.userInfo.projectName
  439. }
  440. variables.project_domain = _.get(this.form.fd, 'domain.label')
  441. if (!variables.project_domain) {
  442. variables.project_domain = this.$store.getters.userInfo.projectDomain
  443. }
  444. },
  445. _resetDataDisk () { // 重置数据盘
  446. const formValue = this.form.fc.getFieldsValue()
  447. if (formValue.dataDiskSizes) {
  448. const dataDiskKeys = Object.keys(formValue.dataDiskSizes)
  449. dataDiskKeys.forEach(key => this.$refs.dataDiskRef.decrease(key))
  450. }
  451. },
  452. _setNewFieldToFd (newField, formValue) { // vue-ant-form change 后赋值 fd
  453. const changeKeys = Object.keys(newField)
  454. R.forEachObjIndexed((item, key) => {
  455. this.$set(this.form.fd, key, item)
  456. }, newField)
  457. if (changeKeys.some(val => val.includes('dataDiskSizes'))) { // 动态赋值默认值的表单需要单独处理
  458. this.$set(this.form.fd, 'dataDiskSizes', formValue.dataDiskSizes)
  459. }
  460. },
  461. networkResourceMapper (list) {
  462. return list
  463. .map(val => {
  464. const remain = val.ports - val.ports_used
  465. if (remain <= 0) {
  466. return {
  467. ...val,
  468. __disabled: true,
  469. }
  470. }
  471. return val
  472. })
  473. .sort((a, b) => (b.ports - b.ports_used) - (a.ports - a.ports_used))
  474. },
  475. countBlur () {
  476. const count = this.form.fc.getFieldValue(this.decorators.count[0])
  477. if (!count) {
  478. this.form.fc.setFieldsValue({
  479. [this.decorators.count[0]]: 1,
  480. })
  481. }
  482. },
  483. fetchDomainCallback () {
  484. const domain = this.$route.query.domain_id
  485. if (!R.isNil(domain) && !R.isEmpty(domain)) {
  486. this.form.fc.setFieldsValue({
  487. domain,
  488. })
  489. }
  490. },
  491. fetchProjectCallback () {
  492. const project = this.$route.query.tenant_id
  493. if (!R.isNil(project) && !R.isEmpty(project)) {
  494. this.form.fc.setFieldsValue({
  495. project: { key: project },
  496. })
  497. }
  498. },
  499. },
  500. }