| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659 |
- import * as R from 'ramda'
- import _ from 'lodash'
- import { SCHED_POLICY_OPTIONS_MAP, SERVER_TYPE, SELECT_IMAGE_KEY_SUFFIX } from '@Compute/constants'
- import OsSelect from '@Compute/sections/OsSelect'
- import CpuRadio from '@Compute/sections/CpuRadio'
- import MemRadio from '@Compute/sections/MemRadio'
- import sku from '@Compute/sections/SKU'
- import gpu from '@Compute/sections/GPU/index'
- import pci from '@Compute/sections/PCI'
- import ServerNetwork from '@Compute/sections/ServerNetwork'
- import SchedPolicy from '@Compute/sections/SchedPolicy'
- import Duration from '@Compute/sections/Duration'
- import InstanceGroups from '@Compute/sections/InstanceGroups'
- import DataDisk from '@Compute/sections/DataDisk'
- import HostName from '@Compute/sections/HostName'
- import storage from '@/utils/storage'
- import workflowMixin from '@/mixins/workflow'
- import { Manager } from '@/utils/manager'
- import { isSuccess } from '@/utils/http'
- import NameRepeated from '@/sections/NameRepeated'
- import CloudregionZone from '@/sections/CloudregionZone'
- import DomainProject from '@/sections/DomainProject'
- import { getInitialValue } from '@/utils/common/ant'
- import { IMAGES_TYPE_MAP } from '@/constants/compute'
- import { HYPERVISORS_MAP } from '@/constants'
- import i18n from '@/locales'
- import { deleteInvalid } from '@/utils/utils'
- import Tag from '../components/Tag'
- import { Decorator, GenCreateData } from '../../utils/createServer'
- import BottomBar from '../components/BottomBar'
- const CreateServerForm = {
- wrapperCol: {
- md: { span: 18 },
- xl: { span: 20 },
- xxl: { span: 22 },
- },
- labelCol: {
- md: { span: 6 },
- xl: { span: 4 },
- xxl: { span: 2 },
- },
- }
- export default {
- name: 'IDCCreate',
- components: {
- OsSelect,
- CloudregionZone,
- BottomBar,
- CpuRadio,
- MemRadio,
- sku,
- ServerNetwork,
- DataDisk,
- gpu,
- SchedPolicy,
- DomainProject,
- Duration,
- InstanceGroups,
- Tag,
- NameRepeated,
- HostName,
- pci,
- },
- mixins: [workflowMixin],
- props: {
- type: {
- type: String,
- required: true,
- validator: val => ['idc', 'private', 'public'].includes(val),
- },
- },
- data () {
- const decorators = new Decorator(SERVER_TYPE[this.type]).createDecorators()
- const initFd = getInitialValue(decorators)
- return {
- submiting: false,
- errors: {},
- formItemLayout: {
- wrapperCol: CreateServerForm.wrapperCol,
- labelCol: CreateServerForm.labelCol,
- },
- form: {
- fc: this.$form.createForm(this, { onValuesChange: this.onValuesChange }),
- fi: { // formInfo 存储着和表单相关的数据
- capability: {}, // 可用区下的可用资源
- imageMsg: {}, // 当前选中的 image
- cpuMem: {}, // cpu 和 内存 的关联关系
- createType: SERVER_TYPE[this.type],
- dataDiskDisabled: false, // 数据盘是否禁用
- sysDiskDisabled: false, // 系统盘是否禁用
- cpuDisabled: false,
- memDisabled: false,
- dataDiskMedium: '',
- networkVpcObj: {},
- showCpuSockets: false,
- cpuSockets: 1,
- errPanes: [], // 表单校验错误的tabs
- containerPanes: [], // 子组件同步的tabs
- },
- fd: { ...initFd, os: '' },
- },
- decorators,
- capabilityParams: {}, // 防止 capability 反复调用,这里对当前的接口参数做记录
- price: null,
- collapseActive: [],
- hostNameValidate: {
- validateStatus: '',
- errorMsg: '',
- },
- }
- },
- provide () {
- return {
- form: this.form,
- }
- },
- computed: {
- project_domain () {
- return this.form.fd.domain ? this.form.fd.domain.key : this.$store.getters.userInfo.projectDomainId
- },
- project () {
- return this.form.fd.project ? this.form.fd.project.key : this.$store.getters.userInfo.projectId
- },
- scopeParams () {
- if (this.$store.getters.isAdminMode) {
- return {
- project_domain: this.project_domain,
- }
- }
- return { scope: this.$store.getters.scope }
- },
- gpuOptions () {
- const specs = this.form.fi.capability.specs || {}
- const data = specs.isolated_devices || {}
- const ret = []
- for (const key in data) {
- if (data.hasOwnProperty(key)) {
- const item = data[key]
- if (item.dev_type.startsWith('GPU')) {
- ret.push({
- ...item,
- key: `vendor=${item.vendor}:${item.model}`,
- label: `${item.vendor}/${item.model}`,
- })
- }
- }
- }
- return ret
- },
- pciDevTypeOptions () {
- return (this.form.fi?.capability?.pci_model_types || []).filter(item => item.hypervisor === 'pod')
- },
- pciOptions () {
- const specs = this.form.fi.capability.specs || {}
- const data = specs.isolated_devices || {}
- const ret = []
- for (const key in data) {
- if (data.hasOwnProperty(key)) {
- const item = data[key]
- if (!item.dev_type.startsWith('USB') && item.hypervisor === 'pod') {
- ret.push({
- ...item,
- key: `vendor=${item.vendor}:${item.model}`,
- label: `${item.vendor}/${item.model}`,
- })
- }
- }
- }
- return ret
- },
- backupDisableds () { // 高可用判断哪些宿主机可用
- const ret = []
- if (this.form.fd.schedPolicyType === SCHED_POLICY_OPTIONS_MAP.host.key) {
- ret.push(this.form.fd.schedPolicyHost)
- }
- if (this.storageHostParams && this.storageHostParams.storageHosts && this.storageHostParams.storageHosts.length) {
- this.storageHostParams.storageHosts.map(item => {
- ret.push(item.id)
- })
- }
- return ret
- },
- policyHostDisabled () {
- if (this.form.fd.backupEnable) {
- return [this.form.fd.backup]
- }
- return []
- },
- dataDiskSizes () {
- const disk = this.form.fd.dataDiskSizes
- return R.is(Object, disk) ? Object.values(disk) : []
- },
- secgroupParams () {
- const params = {
- ...this.scopeParams,
- }
- if (this.type === 'public') { // 公有云
- if (R.is(Object, this.form.fd.sku)) {
- const cloudregion = this.form.fd.sku.cloudregion_id // 取 sku
- if (cloudregion) params.cloudregion_id = cloudregion
- }
- } else { // 私有云和IDC取 CloudregionZone 组件
- const cloudregion = _.get(this.form.fd, 'cloudregion.key')
- if (cloudregion) params.cloudregion_id = cloudregion
- }
- if (this.form.fi.networkVpcObj && this.form.fi.networkVpcObj.id) {
- params.vpc_id = this.form.fi.networkVpcObj.id
- delete params.cloudregion_id
- }
- return params
- },
- showSecgroupBind () {
- return this.form.fd.networkType === 'manual'
- },
- isHostImageType () { // 镜像类型为主机镜像
- return this.form.fd.imageType === IMAGES_TYPE_MAP.host.key
- },
- isSnapshotImageType () { // 镜像类型为主机快照
- return this.form.fd.imageType === IMAGES_TYPE_MAP.snapshot.key
- },
- isDomainMode () {
- return this.$store.getters.isDomainMode
- },
- hasMeterService () { // 是否有计费的服务
- const { services } = this.$store.getters.userInfo
- const meterService = services.find(val => val.type === 'meter')
- if (meterService && meterService.status === true) {
- return true
- }
- return false
- },
- cloudregionZoneParams () {
- const params = {}
- if (this.type === 'public') { // 公有云
- if (R.is(Object, this.form.fd.sku)) {
- const cloudregion = this.form.fd.sku.cloudregion_id // 取 sku
- const zone = this.form.fd.zone // 取 areaSelect 组件
- if (cloudregion) params.cloudregion = cloudregion
- if (zone) params.zone = zone
- }
- } else { // 私有云和IDC取 CloudregionZone 组件
- const cloudregion = _.get(this.form.fd, 'cloudregion.key')
- const zone = _.get(this.form.fd, 'zone.key')
- if (cloudregion) params.cloudregion = cloudregion
- if (zone) params.zone = zone
- }
- return params
- },
- networkVpcParams () {
- const zone = _.get(this.form.fd, 'zone.key')
- const params = {
- limit: 0,
- manager_id: this.form.fd.cloudprovider,
- ...this.scopeParams,
- }
- if (zone) {
- params.usable = true
- params.zone_id = zone
- }
- return params
- },
- vpcResource () {
- if (R.is(String, this.cloudregionZoneParams.cloudregion)) return `cloudregions/${this.cloudregionZoneParams.cloudregion}/vpcs`
- return ''
- },
- schedtagParams () { // 网络里指定调度标签
- return {
- limit: 0,
- resource_type: 'networks',
- ...this.scopeParams,
- }
- },
- policySchedtagParams () { // 高级配置里面调度策略选择 指定调度标签
- const ret = {
- limit: 0,
- 'filter.0': 'resource_type.equals(hosts)',
- ...this.scopeParams,
- }
- const zone = _.get(this.form.fd, 'zone.key')
- if (zone) {
- ret.zone_id = zone
- }
- return ret
- },
- isWindows () {
- let isWindows = false
- const osType = (_.get(this.form.fi, 'imageMsg.info.properties.os_type') || _.get(this.form.fi, 'imageMsg.properties.os_type') || '').toLowerCase()
- const os = (_.get(this.form.fd, 'os') || '').toLowerCase()
- if (~[osType, os].indexOf('windows')) {
- isWindows = true
- }
- return isWindows
- },
- osType () {
- let os_type = this.form.fi.imageMsg.info ? this.form.fi.imageMsg.info.properties?.os_type : this.form.fi.imageMsg.properties?.os_type
- if (!os_type && this.form.fi.imageMsg.os_type) {
- os_type = this.form.fi.imageMsg.os_type
- }
- return this.isWindows ? 'windows' : os_type?.toLowerCase()
- },
- enableEip () {
- const externalAccessMode = _.get(this.form.fi, 'networkVpcObj.external_access_mode')
- if (externalAccessMode === 'none') return false // "eip-distgw" "eip" 是正常可以使用EIP的,"none"不可以
- return true
- },
- isZStack () {
- return this.form.fd.hypervisor === HYPERVISORS_MAP.zstack.key
- },
- isInCloudSphere () {
- return this.form.fd.hypervisor === HYPERVISORS_MAP.incloudsphere.key
- },
- hostNameTips () {
- if (this.isWindows) {
- return `${this.$t('compute.host_name_tips')} ${this.$t('compute.validate.windows')}`
- } else {
- return `${this.$t('compute.host_name_tips')} ${this.$t('compute.validate.others')}`
- }
- },
- isOpenSourceVersion () {
- return !this.$appConfig.isPrivate
- },
- },
- created () {
- this.zoneM = new Manager('zones')
- this.serverM = new Manager('servers')
- this.servertemplateM = new Manager('servertemplates', 'v2')
- this.serverskusM = new Manager('serverskus')
- this.schedulerM = new Manager('schedulers', 'v1')
- this.$bus.$on('VMGetPrice', (price) => {
- this.price = price
- })
- this.$store.dispatch('app/fetchWorkflowEnabledKeys')
- },
- watch: {
- 'form.fi.imageMsg': {
- deep: true,
- handler (val, oldVal) {
- if (R.equals(val, oldVal)) return
- this.$nextTick(() => {
- this._resetDataDisk() // 重置数据盘数据
- })
- },
- },
- isWindows (val) {
- const hostName = this.form.fd.hostName
- if (hostName) {
- this.hostNameValidate = {
- ...this.validateHostNameChange(hostName),
- }
- }
- },
- isKvm () {
- return this.form.fd.hypervisor === 'kvm'
- },
- },
- methods: {
- baywatch (props, watcher) {
- const iterator = function (prop) {
- this.$watch(prop, watcher)
- }
- props.forEach(iterator, this)
- },
- updateFi (fiItems) { // 子组件更新fi
- if (R.is(Object, fiItems)) {
- R.forEachObjIndexed((item, key) => {
- this.$set(this.form.fi, key, item)
- }, fiItems)
- }
- },
- submit (e) {
- e.preventDefault()
- this.validateForm()
- .then(async formData => {
- this.submiting = true
- const genCreteData = new GenCreateData(formData, this.form.fi)
- const data = genCreteData.all()
- await this.checkCreateData(data)
- await this.doForecast(genCreteData, data)
- await this.createServer(data)
- })
- .catch(error => {
- throw error
- })
- .finally(() => {
- this.submiting = false
- })
- },
- async checkCreateData (data) {
- return new this.$Manager('servers').create({ data: { ...data, dry_run: true } })
- },
- doForecast (genCreateData, data) {
- return new Promise((resolve, reject) => {
- this.schedulerM.rpc({ methodname: 'DoForecast', params: data })
- .then(res => {
- if (res.data.can_create) {
- resolve(data)
- } else {
- this.errors = genCreateData.getForecastErrors(res.data)
- reject(this.errors)
- }
- })
- .catch(err => {
- this.$message.error(i18n.t('compute.text_321', [err]))
- reject(err)
- })
- })
- },
- createServer (data) {
- return this.serverM.create({ data })
- .then(res => {
- if (R.is(Array, data.disks)) {
- const imageObj = data.disks.find(val => val.disk_type === 'sys')
- if (R.is(Object, imageObj)) {
- const image = imageObj.image_id
- storage.set(`${this.form.fi.createType}${SELECT_IMAGE_KEY_SUFFIX}`, `${this.form.fd.os}:${image}`)
- }
- }
- if (isSuccess(res)) {
- this.$message.success(i18n.t('compute.text_322'))
- }
- this.$router.push('/vminstance-container')
- })
- .catch(error => {
- throw error
- })
- },
- validateForm () {
- return new Promise((resolve, reject) => {
- this.form.fc.validateFieldsAndScroll({ scroll: { alignWithTop: true, offsetTop: 100 } }, (err, values) => {
- if (!err) {
- resolve(values)
- } else {
- this.collapseActive = ['1'] // 仅仅在报错的时候展开高级配置
- reject(err)
- }
- })
- })
- },
- cpuChange (cpu) {
- const memOpts = this.form.fi.cpuMem.cpu_mems_mb[cpu]
- if (!memOpts || !memOpts.length) { // 没有内存Opts,则内存为0
- let vcpu = cpu
- if (!this.form.fi.cpuMem.cpus.includes(cpu)) { // CPU的Opts不包括cpu的话
- if (this.form.fi.cpuMem.cpus && this.form.fi.cpuMem.cpus.length) { // 如果CPU的Opts有值
- vcpu = this.form.fi.cpuMem.cpus[0]
- } else { // 否则为0
- vcpu = 0
- }
- }
- this.form.fc.setFieldsValue({
- vcpu,
- vmem: 0,
- })
- return
- } else if (this.form.fc.getFieldValue('vcpu') !== cpu) { // 因之前未获取cpu设置为0,这一步设置回来
- this.form.fc.setFieldsValue({
- vcpu: cpu,
- })
- }
- this.form.fi.cpuMem.mems_mb = memOpts
- let defaultMem = 2048
- const currentMem = this.form.fc.getFieldValue('vmem')
- if (currentMem && this.form.fi.cpuMem.mems_mb.includes(currentMem)) {
- return
- }
- if (!this.form.fi.cpuMem.mems_mb.includes(2048)) { // 如果返回值不包括默认内存2G,选择第一项
- defaultMem = memOpts[0]
- }
- this.form.fc.setFieldsValue({
- vmem: defaultMem,
- })
- },
- _getProjectDomainInfo (variables) {
- variables.project = this.form.fd.project.key
- if (!variables.project) {
- variables.project = this.$store.getters.userInfo.projectName
- }
- variables.project_domain = _.get(this.form.fd, 'domain.label')
- if (!variables.project_domain) {
- variables.project_domain = this.$store.getters.userInfo.projectDomain
- }
- },
- _resetDataDisk () { // 重置数据盘
- const formValue = this.form.fc.getFieldsValue()
- if (formValue.dataDiskSizes) {
- const dataDiskKeys = Object.keys(formValue.dataDiskSizes)
- dataDiskKeys.forEach(key => this.$refs.dataDiskRef.decrease(key))
- }
- },
- _setNewFieldToFd (newField, formValue) { // vue-ant-form change 后赋值 fd
- const changeKeys = Object.keys(newField)
- R.forEachObjIndexed((item, key) => {
- this.$set(this.form.fd, key, item)
- }, newField)
- if (changeKeys.some(val => val.includes('dataDiskSizes'))) { // 动态赋值默认值的表单需要单独处理
- this.$set(this.form.fd, 'dataDiskSizes', formValue.dataDiskSizes)
- }
- },
- networkResourceMapper (list) {
- return list
- .map(val => {
- const remain = val.ports - val.ports_used
- if (remain <= 0) {
- return {
- ...val,
- __disabled: true,
- }
- }
- return val
- })
- .sort((a, b) => (b.ports - b.ports_used) - (a.ports - a.ports_used))
- },
- countBlur () {
- const count = this.form.fc.getFieldValue(this.decorators.count[0])
- if (!count) {
- this.form.fc.setFieldsValue({
- [this.decorators.count[0]]: 1,
- })
- }
- },
- fetchDomainCallback () {
- const domain = this.$route.query.domain_id
- if (!R.isNil(domain) && !R.isEmpty(domain)) {
- this.form.fc.setFieldsValue({
- domain: { key: domain },
- })
- }
- },
- fetchProjectCallback () {
- const project = this.$route.query.tenant_id
- if (!R.isNil(project) && !R.isEmpty(project)) {
- this.form.fc.setFieldsValue({
- project: { key: project },
- })
- }
- },
- validateHostNameChange (v) {
- const error = {
- validateStatus: 'success',
- errorMsg: null,
- }
- if (!v) return error
- if (this.isWindows) {
- if (v.length < 2 || v.length > 15) {
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.windows')
- return error
- }
- if (!/^[a-z0-9A-Z-]+$/.test(v)) {
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.windows')
- return error
- }
- if (/^[0-9]+$/.test(v)) { // 不能仅仅使用数字
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- return error
- }
- if (/(-)\1+/.test(v)) { // 不能连续使用连字符
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- return error
- }
- if (/^(?=(-)).*/.test(v)) { // 不能以连字符开头
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- return error
- }
- if (/.*?(-)$/.test(v)) { // 不能以连字符结尾
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- return error
- }
- } else {
- if (v.length < 2 || v.length > 60) {
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- }
- if (!/^[a-z0-9A-Z.-]+$/.test(v)) {
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- return error
- }
- if (/(\.|-)\1+/.test(v)) { // 不能连续使用点号或连字符
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- return error
- }
- if (/^(?=(\.|-)).*/.test(v)) { // 不能以点号或连字符开头
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- return error
- }
- if (/.*?(\.|-)$/.test(v)) { // 不能以点号或连字符结尾
- error.validateStatus = 'error'
- error.errorMsg = this.$t('compute.validate.others')
- return error
- }
- }
- return error
- },
- handleHostNameChange (v) {
- this.hostNameValidate = {
- ...this.validateHostNameChange(v),
- }
- },
- getBationServerData () {
- const {
- bastion_host_id,
- nodes,
- port,
- privileged_accounts,
- accounts,
- } = this.form.fd
- return {
- bastion_host_id,
- nodes,
- port,
- accounts: [privileged_accounts].concat(accounts),
- }
- },
- addShopCart () {
- this.validateForm()
- .then(async formData => {
- this.submiting = true
- const genCreateData = new GenCreateData(formData, this.form.fi)
- const data = genCreateData.all()
- // if (this.form.fd.bastion_host_enable) {
- // const bastionServer = this.getBationServerData()
- // data.bastion_server = bastionServer
- // }
- const { __count__, ...parameter } = deleteInvalid(data)
- const shopCart = {
- action: 'create',
- auto_execute: true,
- count: __count__,
- resource: 'servers',
- user_id: this.$store.getters.userInfo.id,
- parameter: {
- ...parameter,
- price: this.price,
- },
- }
- this._getProjectDomainInfo(shopCart)
- this.$message.success(this.$t('common.success'))
- this.$store.commit('shopcart/ADD_SHOP_CART', shopCart)
- })
- },
- handleCancel () {
- this.$router.push({
- name: 'VMContainerInstance',
- })
- },
- },
- }
|