storage: support backup and recovery feature (#260)

* Add custom component Configure Backup Schedule wizard
* Support for backup user-defined schedule
* Restore volume and attach it to a VM from a backup
* Add offering support that imports external offering

Signed-off-by: Rohit Yadav <rohit.yadav@shapeblue.com>
This commit is contained in:
Hoang Nguyen 2020-04-22 13:29:43 +07:00 committed by Rohit Yadav
parent 5d0825ca8d
commit 33e939097f
11 changed files with 1069 additions and 15 deletions

View File

@ -162,8 +162,9 @@ export default {
icon: 'schedule',
label: 'Configure Backup Schedule',
dataView: true,
args: ['virtualmachineid', 'intervaltype', 'schedule', 'timezone'],
popup: true,
show: (record) => { return record.backupofferingid },
component: () => import('@/views/compute/BackupScheduleWizard.vue'),
mapping: {
virtualmachineid: {
value: (record, params) => { return record.id }

View File

@ -144,7 +144,8 @@ export default {
icon: 'plus',
label: 'Import Offering',
listView: true,
args: ['name', 'description', 'zoneid', 'externalid']
popup: true,
component: () => import('@/views/offering/ImportBackupOffering.vue')
}, {
api: 'deleteBackupOffering',
icon: 'delete',

View File

@ -271,15 +271,8 @@ export default {
icon: 'paper-clip',
label: 'Restore Volume and Attach',
dataView: true,
args: ['backupid', 'virtualmachineid', 'volumeid'],
mapping: {
backupid: {
value: (record) => { return record.id }
},
volumeid: {
options: ['todo: handle custom volume ID']
}
}
popup: true,
component: () => import('@/views/storage/RestoreAttachBackupVolume.vue')
},
{
api: 'removeVirtualMachineFromBackupOffering',

View File

@ -84,6 +84,7 @@
"all": "All",
"allocatediops": "IOPS Allocated",
"allocationstate": "Allocation State",
"allowuserdrivenbackups": "Allow User Driven Backups",
"annotation": "Annotation",
"apikey": "API Key",
"associatednetwork": "Associated Network",
@ -218,7 +219,7 @@
"fingerprint": "FingerPrint",
"firewall": "Firewall",
"firstname": "First Name",
"forced": "Force Stop",
"forced": "Force",
"forceencap": "Force UDP Encapsulation of ESP Packets",
"forgedtransmits": "Forged Transmits",
"format": "Format",
@ -588,7 +589,9 @@
"label.ha.configure": "Configure HA",
"label.ha.disable": "Disable HA",
"label.ha.enable": "Enable HA",
"label.scheduled.backups": "Scheduled Backups",
"label.scheduled.snapshots": "Scheduled Snapshots",
"label.header.backup.schedule": "You can set up recurring backup schedules by selecting from the available options below and applying your policy preference",
"label.header.volume.snapshot": "You can set up recurring snapshot schedules by selecting from the available options below and applying your policy preference",
"label.header.volume.take.snapshot": "Please confirm that you want to take a snapshot of this volume.",
"label.instanciate.template.associate.profile.blade": "Instanciate Template and Associate Profile to Blade",
@ -1263,6 +1266,5 @@
"label.launch.zone": "Launch Zone",
"label.done": "Done",
"label.fix.errors": "Fix errors",
"label.zone": "Zone",
"error.something.went.wrong.please.correct.the.following": "Something went wrong; please correct the following"
}

View File

@ -0,0 +1,95 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
<template>
<div class="backup-layout">
<a-tabs defaultActiveKey="1" :animated="false">
<a-tab-pane :tab="$t('schedule')" key="1">
<FormSchedule
:loading="loading"
:resource="resource"
:dataSource="dataSource"/>
</a-tab-pane>
<a-tab-pane :tab="$t('label.scheduled.backups')" key="2">
<BackupSchedule
:loading="loading"
:resource="resource"
:dataSource="dataSource" />
</a-tab-pane>
</a-tabs>
</div>
</template>
<script>
import { api } from '@/api'
import FormSchedule from '@views/compute/backup/FormSchedule'
import BackupSchedule from '@views/compute/backup/BackupSchedule'
export default {
name: 'BackupScheduleWizard',
components: {
FormSchedule,
BackupSchedule
},
props: {
resource: {
type: Object,
required: true
}
},
data () {
return {
loading: false,
dataSource: {}
}
},
provide () {
return {
refreshSchedule: this.fetchData,
closeSchedule: this.closeAction
}
},
mounted () {
this.fetchData()
},
methods: {
fetchData () {
const params = {}
this.dataSource = {}
this.loading = true
params.virtualmachineid = this.resource.id
api('listBackupSchedule', params).then(json => {
this.dataSource = json.listbackupscheduleresponse.backupschedule || {}
}).finally(() => {
this.loading = false
})
},
closeAction () {
this.$emit('close-action')
}
}
}
</script>
<style scoped lang="less">
.backup-layout {
width: 80vw;
@media (min-width: 800px) {
width: 600px;
}
}
</style>

View File

@ -0,0 +1,220 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
<template>
<div class="list-schedule">
<a-table
size="small"
:columns="columns"
:dataSource="dataSchedules"
:rowKey="record => record.virtualmachineid"
:pagination="false"
:loading="loading">
<div slot="icon" slot-scope="text, record">
<label class="interval-icon">
<span v-if="record.intervaltype==='HOURLY'">
<a-icon type="clock-circle" />
</span>
<span class="custom-icon icon-daily" v-else-if="record.intervaltype==='DAILY'">
<a-icon type="calendar" />
</span>
<span class="custom-icon icon-weekly" v-else-if="record.intervaltype==='WEEKLY'">
<a-icon type="calendar" />
</span>
<span class="custom-icon icon-monthly" v-else-if="record.intervaltype==='MONTHLY'">
<a-icon type="calendar" />
</span>
</label>
</div>
<div slot="time" slot-scope="text, record">
<label class="interval-content">
<span v-if="record.intervaltype==='HOURLY'">{{ record.schedule + ' ' + $t('label.min.past.hour') }}</span>
<span v-else>{{ record.schedule.split(':')[1] + ':' + record.schedule.split(':')[0] }}</span>
</label>
</div>
<div slot="interval" slot-scope="text, record">
<span v-if="record.intervaltype==='WEEKLY'">
{{ $t('label.interval.weekly').replace('{number}', $t(listDayOfWeek[record.schedule.split(':')[2] - 1])) }}
</span>
<span v-else-if="record.intervaltype==='MONTHLY'">
{{ $t('label.interval.monthly').replace('{number}', record.schedule.split(':')[2]) }}
</span>
</div>
<div slot="timezone" slot-scope="text, record">
<label>{{ getTimeZone(record.timezone) }}</label>
</div>
<div slot="action" class="account-button-action" slot-scope="text, record">
<a-tooltip placement="top">
<template slot="title">
{{ $t('label.delete') }}
</template>
<a-button
type="danger"
shape="circle"
icon="close"
size="small"
:loading="actionLoading"
@click="handleClickDelete(record)"/>
</a-tooltip>
</div>
</a-table>
</div>
</template>
<script>
import { api } from '@/api'
import { timeZoneName } from '@/utils/timezone'
export default {
name: 'BackupSchedule',
props: {
loading: {
type: Boolean,
default: false
},
dataSource: {
type: Object,
required: true
},
resource: {
type: Object,
required: true
}
},
data () {
return {
actionLoading: false,
dataSchedules: [],
listDayOfWeek: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
}
},
computed: {
columns () {
return [
{
title: '',
dataIndex: 'icon',
width: 30,
scopedSlots: { customRender: 'icon' }
},
{
title: this.$t('time'),
dataIndex: 'schedule',
scopedSlots: { customRender: 'time' }
},
{
title: '',
dataIndex: 'interval',
scopedSlots: { customRender: 'interval' }
},
{
title: this.$t('timezone'),
dataIndex: 'timezone',
scopedSlots: { customRender: 'timezone' }
},
{
title: this.$t('action'),
dataIndex: 'action',
width: 50,
scopedSlots: { customRender: 'action' }
}
]
}
},
mounted () {
this.dataSchedules = []
if (this.dataSource && Object.keys(this.dataSource).length > 0) {
this.dataSchedules.push(this.dataSource)
}
},
inject: ['refreshSchedule'],
watch: {
dataSource (newData, oldData) {
this.dataSchedules = []
if (newData && Object.keys(newData).length > 0) {
this.dataSchedules.push(newData)
}
}
},
methods: {
handleClickDelete (record) {
const params = {}
params.virtualmachineid = record.virtualmachineid
this.actionLoading = true
api('deleteBackupSchedule', params).then(json => {
if (json.deletebackupscheduleresponse.success) {
this.$notification.success({
message: this.$t('label.scheduled.backups'),
description: 'Successfully deleted Configure VM backup schedule'
})
}
this.refreshSchedule()
}).catch(error => {
this.$notification.error({
message: 'Request Failed',
description: (error.response && error.response.headers && error.response.headers['x-description']) || error.message
})
}).finally(() => {
this.actionLoading = false
})
},
getTimeZone (timeZone) {
return timeZoneName(timeZone)
}
}
}
</script>
<style scoped lang="less">
.interval-icon {
span {
position: relative;
font-size: 18px;
}
.custom-icon:before {
font-size: 8px;
position: absolute;
top: 8px;
left: 3.5px;
color: #000;
font-weight: 700;
line-height: 1.7;
}
.icon-daily:before {
content: "01";
left: 5px;
top: 7px;
line-height: 1.9;
}
.icon-weekly:before {
content: "1-7";
left: 3px;
line-height: 1.7;
}
.icon-monthly:before {
content: "***";
}
}
/deep/.ant-btn > .anticon {
line-height: 1.8;
}
</style>

View File

@ -0,0 +1,330 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
<template>
<a-spin :spinning="loading">
<div class="form-layout">
<label>
{{ $t('label.header.backup.schedule') }}
</label>
<div class="form">
<a-form
:form="form"
layout="vertical"
@submit="handleSubmit">
<a-row :gutter="12">
<a-col :md="24" :lg="24">
<a-form-item :label="$t('intervaltype')">
<a-radio-group
v-decorator="['intervaltype', {
initialValue: intervalType
}]"
buttonStyle="solid"
@change="handleChangeIntervalType">
<a-radio-button value="hourly">
{{ $t('HOURLY') }}
</a-radio-button>
<a-radio-button value="daily">
{{ $t('DAILY') }}
</a-radio-button>
<a-radio-button value="weekly">
{{ $t('WEEKLY') }}
</a-radio-button>
<a-radio-button value="monthly">
{{ $t('MONTHLY') }}
</a-radio-button>
</a-radio-group>
</a-form-item>
</a-col>
<a-col :md="24" :lg="12" v-if="intervalType==='hourly'">
<a-form-item :label="$t('time')">
<a-tooltip
placement="right"
:title="$t('label.minute.past.hour')">
<a-input-number
style="width: 100%"
v-decorator="['time', {
rules: [{required: true, message: 'Please enter input'}]
}]"
:min="1"
:max="59"/>
</a-tooltip>
</a-form-item>
</a-col>
<a-col :md="24" :lg="12" v-if="['daily', 'weekly', 'monthly'].includes(intervalType)">
<a-form-item
class="custom-time-select"
:label="$t('time')">
<a-time-picker
use12Hours
format="h:mm A"
v-decorator="['timeSelect', {
rules: [{
type: 'object',
required: true,
message: 'Please select time'
}]
}]" />
</a-form-item>
</a-col>
<a-col :md="24" :lg="12" v-if="intervalType==='weekly'">
<a-form-item :label="$t('label.day.of.week')">
<a-select
v-decorator="['day-of-week', {
rules: [{
required: true,
message: 'Please select option'
}]
}]" >
<a-select-option v-for="(opt, optIndex) in dayOfWeek" :key="optIndex">
{{ opt.name || opt.description }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :md="24" :lg="12" v-if="intervalType==='monthly'">
<a-form-item :label="$t('label.day.of.month')">
<a-select
v-decorator="['day-of-month', {
rules: [{
required: true,
message: 'Please select option'
}]
}]">
<a-select-option v-for="opt in dayOfMonth" :key="opt.name">
{{ opt.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :md="24" :lg="24">
<a-form-item :label="$t('timezone')">
<a-select
showSearch
v-decorator="['timezone', {
rules: [{
required: true,
message: 'Please select option'
}]
}]"
:loading="fetching">
<a-select-option v-for="opt in timeZoneMap" :key="opt.id">
{{ opt.name || opt.description }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
</a-row>
<div :span="24" class="action-button">
<a-button
:loading="actionLoading"
@click="closeAction">
{{ this.$t('Cancel') }}
</a-button>
<a-button
:loading="actionLoading"
type="primary"
@click="handleSubmit">
{{ this.$t('OK') }}
</a-button>
</div>
</a-form>
</div>
</div>
</a-spin>
</template>
<script>
import { api } from '@/api'
import { timeZone } from '@/utils/timezone'
import debounce from 'lodash/debounce'
export default {
name: 'FormSchedule',
props: {
loading: {
type: Boolean,
default: false
},
dataSource: {
type: Object,
required: true
},
resource: {
type: Object,
required: true
}
},
data () {
this.fetchTimeZone = debounce(this.fetchTimeZone, 800)
return {
dayOfWeek: [],
dayOfMonth: [],
timeZoneMap: [],
fetching: false,
actionLoading: false,
intervalValue: 0,
intervalType: 'hourly',
listDayOfWeek: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
}
},
beforeCreate () {
this.form = this.$form.createForm(this)
},
mounted () {
this.fetchTimeZone()
},
inject: ['refreshSchedule', 'closeSchedule'],
methods: {
fetchTimeZone (value) {
this.timeZoneMap = []
this.fetching = true
timeZone(value).then(json => {
this.timeZoneMap = json
this.fetching = false
})
},
fetchDayOfWeek () {
this.dayOfWeek = []
for (const index in this.listDayOfWeek) {
const dayName = this.listDayOfWeek[index]
this.dayOfWeek.push({
id: dayName,
name: this.$t(dayName)
})
}
},
fetchDayOfMonth () {
this.dayOfMonth = []
const maxDayOfMonth = 28
for (let num = 1; num <= maxDayOfMonth; num++) {
this.dayOfMonth.push({
id: num,
name: num
})
}
},
handleChangeIntervalType (e) {
this.intervalType = e.target.value
this.resetForm()
switch (this.intervalType) {
case 'hourly':
this.intervalValue = 'HOURLY'
break
case 'daily':
this.intervalValue = 'DAILY'
break
case 'weekly':
this.intervalValue = 'WEEKLY'
this.fetchDayOfWeek()
break
case 'monthly':
this.intervalValue = 'MONTHLY'
this.fetchDayOfMonth()
break
}
},
handleSubmit (e) {
this.form.validateFields((error, values) => {
if (error) {
return
}
const params = {}
params.virtualmachineid = this.resource.id
params.intervaltype = values.intervaltype
params.timezone = values.timezone
switch (values.intervaltype) {
case 'hourly':
params.schedule = values.time
break
case 'daily':
params.schedule = values.timeSelect.format('mm:HH')
break
case 'weekly':
params.schedule = [values.timeSelect.format('mm:HH'), (values['day-of-week'] + 1)].join(':')
break
case 'monthly':
params.schedule = [values.timeSelect.format('mm:HH'), values['day-of-month']].join(':')
break
}
this.actionLoading = true
api('createBackupSchedule', params).then(json => {
this.$notification.success({
message: this.$t('label.scheduled.backups'),
description: 'Successfully Configure VM backup schedule'
})
this.refreshSchedule()
this.resetForm()
}).catch(error => {
this.$notification.error({
message: 'Request Failed',
description: (error.response && error.response.headers && error.response.headers['x-description']) || error.message
})
}).finally(() => {
this.actionLoading = false
})
})
},
resetForm () {
this.form.setFieldsValue({
time: undefined,
timezone: undefined,
timeSelect: undefined,
'day-of-week': undefined,
'day-of-month': undefined
})
this.tags = []
},
closeAction () {
this.closeSchedule()
}
}
}
</script>
<style scoped lang="less">
.form-layout {
.ant-tag {
margin-bottom: 10px;
}
/deep/.custom-time-select .ant-time-picker {
width: 100%;
}
/deep/.ant-divider-horizontal {
margin-top: 0;
}
}
.form {
margin: 10px 0;
}
.action-button {
margin-top: 20px;
text-align: right;
button {
margin-right: 5px;
}
}
</style>

View File

@ -748,7 +748,7 @@ export default {
if (['KVM', 'VMware', 'Hyperv'].includes(hypervisor)) {
scope.push({
id: 'zone',
description: this.$t('label.zone')
description: this.$t('zone')
})
scope.push({
id: 'cluster',

View File

@ -0,0 +1,214 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
<template>
<div class="form-layout">
<a-form
layout="vertical"
:form="form"
@submit="handleSubmit">
<a-form-item :label="$t('name')">
<a-input
v-decorator="['name', {
rules: [{ required: true, message: 'Please enter input' }]
}]"/>
</a-form-item>
<a-form-item :label="$t('description')">
<a-input
v-decorator="['description', {
rules: [{ required: true, message: 'Please enter input' }]
}]"/>
</a-form-item>
<a-form-item :label="$t('zoneid')">
<a-select
showSearch
allowClear
v-decorator="['zoneid', {
rules: [{ required: true, message: 'Please select option' }]
}]"
:loading="zones.loading"
@change="onChangeZone">
<a-select-option v-for="zone in zones.opts" :key="zone.name">
{{ zone.name }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item :label="$t('externalid')">
<a-select
allowClear
v-decorator="['externalid'] "
:loading="externals.loading">
<a-select-option v-for="opt in externals.opts" :key="opt.id">
{{ opt.name }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item :label="$t('allowuserdrivenbackups')">
<a-switch
v-decorator="['allowuserdrivenbackups']"
:default-checked="true"/>
</a-form-item>
<div :span="24" class="action-button">
<a-button :loading="loading" @click="closeAction">{{ this.$t('Cancel') }}</a-button>
<a-button :loading="loading" type="primary" @click="handleSubmit">{{ this.$t('OK') }}</a-button>
</div>
</a-form>
</div>
</template>
<script>
import { api } from '@/api'
export default {
name: 'ImportBackupOffering',
data () {
return {
loading: false,
zones: {
loading: false,
opts: []
},
externals: {
loading: false,
opts: []
}
}
},
beforeCreate () {
this.form = this.$form.createForm(this)
},
mounted () {
this.fetchData()
},
inject: ['parentFetchData'],
methods: {
fetchData () {
this.fetchZone()
},
fetchZone () {
this.zones.loading = true
api('listZones', { available: true }).then(json => {
this.zones.opts = json.listzonesresponse.zone || []
this.$forceUpdate()
}).catch(error => {
this.$notification.error({
message: 'Request Failed',
description: (error.response && error.response.headers && error.response.headers['x-description']) || error.message
})
}).finally(f => {
this.zones.loading = false
})
},
fetchExternal (zoneId) {
if (!zoneId) {
this.externals.opts = []
return
}
this.externals.loading = true
api('listBackupProviderOfferings', { zoneid: zoneId }).then(json => {
this.externals.opts = json.listbackupproviderofferingsresponse.backupoffering || []
this.$forceUpdate()
}).catch(error => {
this.$notification.error({
message: 'Request Failed',
description: (error.response && error.response.headers && error.response.headers['x-description']) || error.message
})
}).finally(f => {
this.externals.loading = false
})
},
handleSubmit (e) {
e.preventDefault()
this.form.validateFields((err, values) => {
if (err) {
return
}
const params = {}
for (const key in values) {
const input = values[key]
if (key === 'zoneid') {
params[key] = this.zones.opts.filter(zone => zone.name === input)[0].id || null
} else {
params[key] = input
}
}
params.allowuserdrivenbackups = values.allowuserdrivenbackups ? values.allowuserdrivenbackups : false
this.loading = true
const title = 'Import Offering'
api('importBackupOffering', params).then(json => {
const jobId = json.importbackupofferingresponse.jobid
if (jobId) {
this.$pollJob({
jobId,
successMethod: result => {
const successDescription = result.jobresult.backupoffering.name
this.$store.dispatch('AddAsyncJob', {
title: title,
jobid: jobId,
description: successDescription,
status: 'progress'
})
this.parentFetchData()
this.closeAction()
},
loadingMessage: `${title} in progress for ${params.name}`,
catchMessage: 'Error encountered while fetching async job result'
})
}
}).catch(error => {
this.$notification.error({
message: 'Request Failed',
description: (error.response && error.response.headers && error.response.headers['x-description']) || error.message
})
}).finally(f => {
this.loading = false
})
})
},
onChangeZone (value) {
if (!value) {
this.externals.opts = []
return
}
const zoneId = this.zones.opts.filter(zone => zone.name === value)[0].id || null
this.fetchExternal(zoneId)
},
closeAction () {
this.$emit('close-action')
}
}
}
</script>
<style scoped lang="less">
.form-layout {
width: 30vw;
@media (min-width: 500px) {
width: 450px;
}
.action-button {
text-align: right;
margin-top: 20px;
button {
margin-right: 5px;
}
}
}
</style>

View File

@ -17,7 +17,7 @@
<template>
<div class="snapshot-layout">
<a-tabs defaultActiveKey="1">
<a-tabs defaultActiveKey="1" :animated="false">
<a-tab-pane :tab="$t('schedule')" key="1">
<FormSchedule
:loading="loading"

View File

@ -0,0 +1,198 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
<template>
<div class="form-layout">
<a-form layout="vertical" :form="form">
<a-form-item :label="$t('volume')">
<a-select
allowClear
v-decorator="['volumeid', {
rules: [{ required: true, message: 'Please select option' }]
}]"
:loading="volumeOptions.loading">
<a-select-option
v-for="(opt) in volumeOptions.opts"
:key="opt.id">
{{ opt.name }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item :label="$t('vm')">
<a-select
showSearch
allowClear
v-decorator="['virtualmachineid', {
rules: [{ required: true, message: 'Please select option' }]
}]"
:loading="virtualMachineOptions.loading">
<a-select-option
v-for="(opt) in virtualMachineOptions.opts"
:key="opt.name">
{{ opt.name }}
</a-select-option>
</a-select>
</a-form-item>
<div :span="24" class="action-button">
<a-button :loading="loading || actionLoading" @click="closeAction">{{ this.$t('Cancel') }}</a-button>
<a-button :loading="loading || actionLoading" type="primary" @click="handleSubmit">{{ this.$t('OK') }}</a-button>
</div>
</a-form>
</div>
</template>
<script>
import { api } from '@/api'
export default {
name: 'RestoreAttachBackupVolume',
props: {
loading: {
type: Boolean,
default: false
},
resource: {
type: Object,
default: () => {}
}
},
data () {
return {
virtualMachineOptions: {
loading: false,
opts: []
},
volumeOptions: {
loading: false,
opts: []
},
actionLoading: false
}
},
beforeCreate () {
this.form = this.$form.createForm(this)
},
mounted () {
this.fetchData()
},
inject: ['parentFetchData'],
methods: {
fetchData () {
this.fetchVirtualMachine()
this.fetchVolumes()
},
fetchVirtualMachine () {
this.virtualMachineOptions.loading = true
api('listVirtualMachines', { zoneid: this.resource.zoneid }).then(json => {
this.virtualMachineOptions.opts = json.listvirtualmachinesresponse.virtualmachine || []
this.$forceUpdate()
}).catch(error => {
this.$notification.error({
message: 'Request Failed',
description: (error.response && error.response.headers && error.response.headers['x-description']) || error.message
})
}).finally(() => {
this.virtualMachineOptions.loading = false
})
},
async fetchVolumes () {
if (!this.resource || Object.keys(this.resource).length === 0) {
return
}
if (!this.resource.volumes || typeof this.resource.volumes !== 'string') {
return
}
const volumes = JSON.parse(this.resource.volumes)
this.volumeOptions.loading = true
this.volumeOptions.opts = await volumes.map(volume => {
return {
id: volume.uuid,
name: ['(', volume.type, ') ', volume.uuid].join('')
}
})
this.volumeOptions.loading = false
this.$forceUpdate()
},
handleSubmit (e) {
e.preventDefault()
this.form.validateFields((err, values) => {
if (err) {
return
}
const params = {}
params.backupid = this.resource.id
params.volumeid = values.volumeid
params.virtualmachineid = this.virtualMachineOptions.opts.filter(opt => opt.name === values.virtualmachineid)[0].id || null
this.actionLoading = true
const title = 'Restore Volume and Attach'
api('restoreVolumeFromBackupAndAttachToVM', params).then(json => {
const jobId = json.restorevolumefrombackupandattachtovmresponse.jobid || null
if (jobId) {
this.$pollJob({
jobId,
successMethod: result => {
const successDescription = result.jobresult.storagebackup.name
this.$store.dispatch('AddAsyncJob', {
title: title,
jobid: jobId,
description: successDescription,
status: 'progress'
})
this.parentFetchData()
this.closeAction()
},
loadingMessage: `${title} in progress for ${this.resource.id}`,
catchMessage: 'Error encountered while fetching async job result'
})
}
}).catch(error => {
this.$notification.error({
message: 'Request Failed',
description: (error.response && error.response.headers && error.response.headers['x-description']) || error.message
})
}).finally(() => {
this.actionLoading = false
})
})
},
closeAction () {
this.$emit('close-action')
}
}
}
</script>
<style scoped lang="less">
.form-layout {
width: 30vw;
@media (min-width: 500px) {
width: 400px;
}
.action-button {
text-align: right;
margin-top: 20px;
button {
margin-right: 5px;
}
}
}
</style>