-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathMigrationForm.tsx
More file actions
1772 lines (1599 loc) · 62.6 KB
/
MigrationForm.tsx
File metadata and controls
1772 lines (1599 loc) · 62.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Box, Alert, Divider, Typography, useMediaQuery } from '@mui/material'
import MigrationIcon from '@mui/icons-material/SwapHoriz'
import { useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { useEffect, useMemo, useRef, useState, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { postMigrationPlan } from 'src/features/migration/api/migration-plans/migrationPlans'
import { MigrationPlan } from 'src/features/migration/api/migration-plans/model'
import SecurityGroupAndServerGroupStep from './SecurityGroupAndServerGroup'
import {
getMigrationTemplate,
patchMigrationTemplate,
postMigrationTemplate,
deleteMigrationTemplate
} from 'src/features/migration/api/migration-templates/migrationTemplates'
import { MigrationTemplate, VmData } from 'src/features/migration/api/migration-templates/model'
import { createNetworkMappingJson } from 'src/api/network-mapping/helpers'
import { postNetworkMapping } from 'src/api/network-mapping/networkMappings'
import { OpenstackCreds } from 'src/api/openstack-creds/model'
import {
getOpenstackCredentials,
deleteOpenstackCredentials
} from 'src/api/openstack-creds/openstackCreds'
import { createStorageMappingJson } from 'src/api/storage-mappings/helpers'
import { postStorageMapping } from 'src/api/storage-mappings/storageMappings'
import { createArrayCredsMappingJson } from 'src/api/arraycreds-mapping/helpers'
import { postArrayCredsMapping } from 'src/api/arraycreds-mapping/arrayCredsMapping'
import { VMwareCreds } from 'src/api/vmware-creds/model'
import { getVmwareCredentials, deleteVmwareCredentials } from 'src/api/vmware-creds/vmwareCreds'
import { THREE_SECONDS } from 'src/constants'
import { MIGRATIONS_QUERY_KEY } from 'src/hooks/api/useMigrationsQuery'
import { VMWARE_MACHINES_BASE_KEY } from 'src/hooks/api/useVMwareMachinesQuery'
import { useInterval } from 'src/hooks/useInterval'
import useParams from 'src/hooks/useParams'
import { isNilOrEmpty } from 'src/utils'
import MigrationOptions from './MigrationOptionsAlt'
import NetworkAndStorageMappingStep from './NetworkAndStorageMappingStep'
import SourceDestinationClusterSelection from './SourceDestinationClusterSelection'
import VmsSelectionStep from './VmsSelectionStep'
import { CUTOVER_TYPES } from './constants'
import { uniq } from 'ramda'
import { flatten } from 'ramda'
import { useClusterData } from './useClusterData'
import { useErrorHandler } from 'src/hooks/useErrorHandler'
import { useRdmConfigValidation } from 'src/hooks/useRdmConfigValidation'
import { useRdmDisksQuery } from 'src/hooks/api/useRdmDisksQuery'
import { useAmplitude } from 'src/hooks/useAmplitude'
import { AMPLITUDE_EVENTS } from 'src/types/amplitude'
import { createMigrationTemplateJson } from 'src/features/migration/api/migration-templates/helpers'
import { createMigrationPlanJson } from 'src/features/migration/api/migration-plans/helpers'
import {
ActionButton,
DrawerFooter,
DrawerHeader,
DrawerShell,
NavTab,
NavTabs,
SectionNav,
SurfaceCard
} from 'src/components'
import type { SectionNavItem } from 'src/components'
import { useTheme } from '@mui/material/styles'
import { useForm, useWatch } from 'react-hook-form'
import { DesignSystemForm } from 'src/shared/components/forms'
const stringsCompareFn = (a: string, b: string) => a.toLowerCase().localeCompare(b.toLowerCase())
const drawerWidth = 1400
type MigrationDrawerRHFValues = {
securityGroups: string[]
serverGroup: string
dataCopyStartTime: string
cutoverStartTime: string
cutoverEndTime: string
postMigrationActionSuffix: string
postMigrationActionFolderName: string
}
const stringArrayEqual = (a: string[] | undefined, b: string[] | undefined) => {
if (a === b) return true
if (!a || !b) return false
if (a.length !== b.length) return false
return a.every((v, i) => v === b[i])
}
export interface FormValues extends Record<string, unknown> {
vmwareCreds?: {
vcenterHost: string
datacenter: string
username: string
password: string
existingCredName?: string
credentialName?: string
}
openstackCreds?: {
OS_AUTH_URL: string
OS_DOMAIN_NAME: string
OS_USERNAME: string
OS_PASSWORD: string
OS_REGION_NAME: string
OS_TENANT_NAME: string
existingCredName?: string
credentialName?: string
OS_INSECURE?: boolean
}
vms?: VmData[]
rdmConfigurations?: Array<{
uuid: string
diskName: string
cinderBackendPool: string
volumeType: string
source: Record<string, string>
}>
networkMappings?: { source: string; target: string }[]
storageMappings?: { source: string; target: string }[]
arrayCredsMappings?: { source: string; target: string }[]
storageCopyMethod?: 'normal' | 'StorageAcceleratedCopy' | 'HotAddCopy'
// Cluster selection fields
vmwareCluster?: string // Format: "credName:datacenter:clusterName"
pcdCluster?: string // PCD cluster ID
// Optional Params
dataCopyMethod?: string
dataCopyStartTime?: string
cutoverOption?: string
cutoverStartTime?: string
cutoverEndTime?: string
postMigrationScript?: string
osFamily?: string
// Add postMigrationAction with optional properties
postMigrationAction?: {
suffix?: string
folderName?: string
renameVm?: boolean
moveToFolder?: boolean
}
disconnectSourceNetwork?: boolean
securityGroups?: string[]
serverGroup?: string
fallbackToDHCP?: boolean
useGPU?: boolean
networkPersistence?: boolean
removeVMwareTools?: boolean
}
export interface SelectedMigrationOptionsType {
dataCopyMethod: boolean
dataCopyStartTime: boolean
cutoverOption: boolean
cutoverStartTime: boolean
cutoverEndTime: boolean
postMigrationScript: boolean
useGPU?: boolean
useFlavorless?: boolean
periodicSyncEnabled?: boolean
postMigrationAction?: {
suffix?: boolean
folderName?: boolean
renameVm?: boolean
moveToFolder?: boolean
}
acknowledgeNetworkConflictRisk?: boolean
[key: string]: unknown
}
// Default state for checkboxes
const defaultMigrationOptions = {
dataCopyMethod: false,
dataCopyStartTime: false,
cutoverOption: false,
cutoverStartTime: false,
cutoverEndTime: false,
postMigrationScript: false,
useGPU: false,
useFlavorless: false,
postMigrationAction: {
suffix: false,
folderName: false,
renameVm: false,
moveToFolder: false
}
}
const defaultValues: Partial<FormValues> = {}
export type FieldErrors = { [formId: string]: string }
interface MigrationFormDrawerProps {
open: boolean
onClose: () => void
reloadMigrations?: () => void
onSuccess?: (message: string) => void
}
export default function MigrationFormDrawer({
open,
onClose,
onSuccess
}: MigrationFormDrawerProps) {
const navigate = useNavigate()
const { params, getParamsUpdater } = useParams<FormValues>(defaultValues)
const { pcdData } = useClusterData()
const { reportError } = useErrorHandler({ component: 'MigrationForm' })
const { track } = useAmplitude({ component: 'MigrationForm' })
const [, setError] = useState<{ title: string; message: string } | null>(null)
// Theses are the errors that will be displayed on the form
const { params: fieldErrors, getParamsUpdater: getFieldErrorsUpdater } = useParams<FieldErrors>(
{}
)
const queryClient = useQueryClient()
// Migration Options - Checked or Unchecked state
const { params: selectedMigrationOptions, getParamsUpdater: updateSelectedMigrationOptions } =
useParams<SelectedMigrationOptionsType>(defaultMigrationOptions)
// Form Statuses
const [submitting, setSubmitting] = useState(false)
// Migration Resources
const [vmwareCredentials, setVmwareCredentials] = useState<VMwareCreds | undefined>(undefined)
const [openstackCredentials, setOpenstackCredentials] = useState<OpenstackCreds | undefined>(
undefined
)
const [migrationTemplate, setMigrationTemplate] = useState<MigrationTemplate | undefined>(
undefined
)
// Generate a unique session ID for this form instance
const [sessionId] = useState(() => `form-session-${Date.now()}`)
const form = useForm<MigrationDrawerRHFValues, any, MigrationDrawerRHFValues>({
defaultValues: {
securityGroups: params.securityGroups ?? [],
serverGroup: params.serverGroup ?? '',
dataCopyStartTime: params.dataCopyStartTime ?? '',
cutoverStartTime: params.cutoverStartTime ?? '',
cutoverEndTime: params.cutoverEndTime ?? '',
postMigrationActionSuffix: params.postMigrationAction?.suffix ?? '',
postMigrationActionFolderName: params.postMigrationAction?.folderName ?? ''
}
})
const rhfSecurityGroups = useWatch({ control: form.control, name: 'securityGroups' })
const rhfServerGroup = useWatch({ control: form.control, name: 'serverGroup' })
const rhfDataCopyStartTime = useWatch({ control: form.control, name: 'dataCopyStartTime' })
const rhfCutoverStartTime = useWatch({ control: form.control, name: 'cutoverStartTime' })
const rhfCutoverEndTime = useWatch({ control: form.control, name: 'cutoverEndTime' })
const rhfPostMigrationActionSuffix = useWatch({
control: form.control,
name: 'postMigrationActionSuffix'
})
const rhfPostMigrationActionFolderName = useWatch({
control: form.control,
name: 'postMigrationActionFolderName'
})
useEffect(() => {
const nextSecurityGroups = params.securityGroups ?? []
const nextServerGroup = params.serverGroup ?? ''
const nextDataCopyStartTime = params.dataCopyStartTime ?? ''
const nextCutoverStartTime = params.cutoverStartTime ?? ''
const nextCutoverEndTime = params.cutoverEndTime ?? ''
const nextPostMigrationActionSuffix = params.postMigrationAction?.suffix ?? ''
const nextPostMigrationActionFolderName = params.postMigrationAction?.folderName ?? ''
const currentSecurityGroups = form.getValues('securityGroups') ?? []
const currentServerGroup = form.getValues('serverGroup') ?? ''
const currentDataCopyStartTime = form.getValues('dataCopyStartTime') ?? ''
const currentCutoverStartTime = form.getValues('cutoverStartTime') ?? ''
const currentCutoverEndTime = form.getValues('cutoverEndTime') ?? ''
const currentPostMigrationActionSuffix = form.getValues('postMigrationActionSuffix') ?? ''
const currentPostMigrationActionFolderName =
form.getValues('postMigrationActionFolderName') ?? ''
if (!stringArrayEqual(currentSecurityGroups, nextSecurityGroups)) {
form.setValue('securityGroups', nextSecurityGroups)
}
if (currentServerGroup !== nextServerGroup) {
form.setValue('serverGroup', nextServerGroup)
}
if (currentDataCopyStartTime !== nextDataCopyStartTime) {
form.setValue('dataCopyStartTime', nextDataCopyStartTime)
}
if (currentCutoverStartTime !== nextCutoverStartTime) {
form.setValue('cutoverStartTime', nextCutoverStartTime)
}
if (currentCutoverEndTime !== nextCutoverEndTime) {
form.setValue('cutoverEndTime', nextCutoverEndTime)
}
if (currentPostMigrationActionSuffix !== nextPostMigrationActionSuffix) {
form.setValue('postMigrationActionSuffix', nextPostMigrationActionSuffix)
}
if (currentPostMigrationActionFolderName !== nextPostMigrationActionFolderName) {
form.setValue('postMigrationActionFolderName', nextPostMigrationActionFolderName)
}
}, [
form,
params.securityGroups,
params.serverGroup,
params.dataCopyStartTime,
params.cutoverStartTime,
params.cutoverEndTime,
params.postMigrationAction
])
useEffect(() => {
const nextDataCopyStartTime = (rhfDataCopyStartTime ?? '') as string
if ((params.dataCopyStartTime ?? '') !== nextDataCopyStartTime) {
getParamsUpdater('dataCopyStartTime')(nextDataCopyStartTime)
}
}, [getParamsUpdater, params.dataCopyStartTime, rhfDataCopyStartTime])
useEffect(() => {
const nextCutoverStartTime = (rhfCutoverStartTime ?? '') as string
if ((params.cutoverStartTime ?? '') !== nextCutoverStartTime) {
getParamsUpdater('cutoverStartTime')(nextCutoverStartTime)
}
}, [getParamsUpdater, params.cutoverStartTime, rhfCutoverStartTime])
useEffect(() => {
const nextCutoverEndTime = (rhfCutoverEndTime ?? '') as string
if ((params.cutoverEndTime ?? '') !== nextCutoverEndTime) {
getParamsUpdater('cutoverEndTime')(nextCutoverEndTime)
}
}, [getParamsUpdater, params.cutoverEndTime, rhfCutoverEndTime])
useEffect(() => {
const nextSuffix = String(rhfPostMigrationActionSuffix ?? '')
const normalized = nextSuffix.trim() ? nextSuffix.trim() : ''
const current = params.postMigrationAction?.suffix ?? ''
const renameEnabled = !!selectedMigrationOptions.postMigrationAction?.renameVm
if (!renameEnabled) return
if (current !== normalized) {
getParamsUpdater('postMigrationAction')({
...params.postMigrationAction,
suffix: normalized ? normalized : undefined
})
}
}, [
getParamsUpdater,
params.postMigrationAction,
rhfPostMigrationActionSuffix,
selectedMigrationOptions.postMigrationAction?.renameVm
])
useEffect(() => {
const nextFolderName = String(rhfPostMigrationActionFolderName ?? '')
const normalized = nextFolderName.trim() ? nextFolderName.trim() : ''
const current = params.postMigrationAction?.folderName ?? ''
const moveToFolderEnabled = !!selectedMigrationOptions.postMigrationAction?.moveToFolder
if (!moveToFolderEnabled) return
if (current !== normalized) {
getParamsUpdater('postMigrationAction')({
...params.postMigrationAction,
folderName: normalized ? normalized : undefined
})
}
}, [
getParamsUpdater,
params.postMigrationAction,
rhfPostMigrationActionFolderName,
selectedMigrationOptions.postMigrationAction?.moveToFolder
])
useEffect(() => {
const next = (rhfSecurityGroups ?? []) as string[]
if (!stringArrayEqual(params.securityGroups ?? [], next)) {
getParamsUpdater('securityGroups')(next)
}
}, [params.securityGroups, rhfSecurityGroups, getParamsUpdater])
useEffect(() => {
const next = (rhfServerGroup ?? '') as string
if ((params.serverGroup ?? '') !== next) {
getParamsUpdater('serverGroup')(next)
}
}, [params.serverGroup, rhfServerGroup, getParamsUpdater])
const vmwareCredsValidated = vmwareCredentials?.status?.vmwareValidationStatus === 'Succeeded'
const openstackCredsValidated =
openstackCredentials?.status?.openstackValidationStatus === 'Succeeded'
// Query RDM disks
const { data: rdmDisks = [] } = useRdmDisksQuery({
enabled: vmwareCredsValidated && openstackCredsValidated
})
// Polling Conditions - Poll when we have a migration template but it's not fully populated with networks/volumes
const shouldPollMigrationTemplate =
migrationTemplate?.metadata?.name &&
(!migrationTemplate?.status?.openstack?.networks ||
!migrationTemplate?.status?.openstack?.volumeTypes)
// Update this effect to only handle existing credential selection
useEffect(() => {
const fetchCredentials = async () => {
if (!params.vmwareCreds || !params.vmwareCreds.existingCredName) return
try {
const existingCredName = params.vmwareCreds.existingCredName
const response = await getVmwareCredentials(existingCredName)
setVmwareCredentials(response)
} catch (error) {
console.error('Error fetching existing VMware credentials:', error)
getFieldErrorsUpdater('vmwareCreds')(
'Error fetching VMware credentials: ' +
(axios.isAxiosError(error) ? error?.response?.data?.message : error)
)
}
}
if (isNilOrEmpty(params.vmwareCreds)) return
setVmwareCredentials(undefined)
getFieldErrorsUpdater('vmwareCreds')('')
fetchCredentials()
}, [params.vmwareCreds, getFieldErrorsUpdater])
// Update this effect to only handle existing credential selection
useEffect(() => {
const fetchCredentials = async () => {
if (!params.openstackCreds || !params.openstackCreds.existingCredName) return
try {
const existingCredName = params.openstackCreds.existingCredName
const response = await getOpenstackCredentials(existingCredName)
setOpenstackCredentials(response)
} catch (error) {
console.error('Error fetching existing OpenStack credentials:', error)
getFieldErrorsUpdater('openstackCreds')(
'Error fetching PCD credentials: ' +
(axios.isAxiosError(error) ? error?.response?.data?.message : error)
)
}
}
if (isNilOrEmpty(params.openstackCreds)) return
// Reset the OpenstackCreds object if the user changes the credentials
setOpenstackCredentials(undefined)
getFieldErrorsUpdater('openstackCreds')('')
fetchCredentials()
}, [params.openstackCreds, getFieldErrorsUpdater])
const targetPCDClusterName = useMemo(() => {
if (!params.pcdCluster) return undefined
const selectedPCD = pcdData.find((p) => p.id === params.pcdCluster)
return selectedPCD?.name
}, [params.pcdCluster, pcdData])
useEffect(() => {
if (!vmwareCredsValidated || !openstackCredsValidated) return
const syncMigrationTemplate = async () => {
try {
// If a template already exists, update it instead of creating a new one
if (migrationTemplate?.metadata?.name) {
const patchBody = {
spec: {
source: {
...(params.vmwareCreds?.datacenter && {
datacenter: params.vmwareCreds.datacenter
}),
vmwareRef: vmwareCredentials?.metadata.name
},
destination: {
openstackRef: openstackCredentials?.metadata.name
},
...(targetPCDClusterName && {
targetPCDClusterName
}),
useFlavorless: params.useFlavorless || false,
useGPUFlavor: params.useGPU || false
}
}
const updated = await patchMigrationTemplate(migrationTemplate.metadata.name, patchBody)
setMigrationTemplate(updated)
return
}
// Otherwise create a new template once
const body = createMigrationTemplateJson({
...(params.vmwareCreds?.datacenter && { datacenter: params.vmwareCreds.datacenter }),
vmwareRef: vmwareCredentials?.metadata.name,
openstackRef: openstackCredentials?.metadata.name,
targetPCDClusterName,
useFlavorless: params.useFlavorless || false,
useGPUFlavor: params.useGPU || false
})
const created = await postMigrationTemplate(body)
setMigrationTemplate(created)
} catch (err) {
console.error('Error syncing migration template', err)
getFieldErrorsUpdater('migrationTemplate')(
'Error syncing migration template: ' +
(axios.isAxiosError(err)
? err?.response?.data?.message
: err instanceof Error
? err.message
: String(err))
)
}
}
syncMigrationTemplate()
}, [
vmwareCredsValidated,
openstackCredsValidated,
params.vmwareCreds?.datacenter,
vmwareCredentials?.metadata.name,
openstackCredentials?.metadata.name,
targetPCDClusterName,
params.useFlavorless,
params.useGPU,
migrationTemplate?.metadata?.name,
getFieldErrorsUpdater
])
// Keep original fetchMigrationTemplate for fetching OpenStack networks and volume types
const fetchMigrationTemplate = async () => {
try {
const updatedMigrationTemplate = await getMigrationTemplate(migrationTemplate!.metadata!.name)
setMigrationTemplate(updatedMigrationTemplate)
} catch (err) {
console.error('Error retrieving migration templates', err)
getFieldErrorsUpdater('migrationTemplate')('Error retrieving migration templates')
}
}
useInterval(
async () => {
if (shouldPollMigrationTemplate) {
try {
fetchMigrationTemplate()
} catch (err) {
console.error('Error retrieving migration templates', err)
getFieldErrorsUpdater('migrationTemplate')('Error retrieving migration templates')
}
}
},
THREE_SECONDS,
shouldPollMigrationTemplate
)
useEffect(() => {
if (vmwareCredsValidated && openstackCredsValidated) return
// Reset all the migration resources if the user changes the credentials
setMigrationTemplate(undefined)
}, [vmwareCredsValidated, openstackCredsValidated])
const availableVmwareNetworks = useMemo(() => {
if (params.vms === undefined) return []
return uniq(flatten(params.vms.map((vm) => vm.networks || []))).sort(stringsCompareFn) // Back to unique networks only
}, [params.vms])
const availableVmwareDatastores = useMemo(() => {
if (params.vms === undefined) return []
return uniq(flatten(params.vms.map((vm) => vm.datastores || []))).sort(stringsCompareFn)
}, [params.vms])
const createNetworkMapping = async (networkMappingParams) => {
const body = createNetworkMappingJson({
networkMappings: networkMappingParams
})
try {
const data = postNetworkMapping(body)
return data
} catch (err) {
setError({
title: 'Error creating network mapping',
message: axios.isAxiosError(err) ? err?.response?.data?.message : ''
})
getFieldErrorsUpdater('networksMapping')(
'Error creating network mapping : ' +
(axios.isAxiosError(err) ? err?.response?.data?.message : err)
)
}
}
const createStorageMapping = async (storageMappingsParams) => {
const body = createStorageMappingJson({
storageMappings: storageMappingsParams
})
try {
const data = postStorageMapping(body)
return data
} catch (err) {
console.error('Error creating storage mapping', err)
reportError(err as Error, {
context: 'storage-mapping-creation',
metadata: {
storageMappingsParams: storageMappingsParams,
action: 'create-storage-mapping'
}
})
setError({
title: 'Error creating storage mapping',
message: axios.isAxiosError(err) ? err?.response?.data?.message : ''
})
getFieldErrorsUpdater('storageMapping')(
'Error creating storage mapping : ' +
(axios.isAxiosError(err) ? err?.response?.data?.message : err)
)
}
}
const createArrayCredsMapping = async (
arrayCredsMappingsParams: { source: string; target: string }[]
) => {
const body = createArrayCredsMappingJson({
mappings: arrayCredsMappingsParams
})
try {
const data = await postArrayCredsMapping(body)
return data
} catch (err) {
console.error('Error creating ArrayCreds mapping', err)
reportError(err as Error, {
context: 'arraycreds-mapping-creation',
metadata: {
arrayCredsMappingsParams: arrayCredsMappingsParams,
action: 'create-arraycreds-mapping'
}
})
setError({
title: 'Error creating ArrayCreds mapping',
message: axios.isAxiosError(err) ? err?.response?.data?.message : ''
})
getFieldErrorsUpdater('storageMapping')(
'Error creating ArrayCreds mapping : ' +
(axios.isAxiosError(err) ? err?.response?.data?.message : err)
)
}
}
const updateMigrationTemplate = async (
migrationTemplate,
networkMappings,
storageMappings,
arrayCredsMapping: any = null
) => {
const migrationTemplateName = migrationTemplate?.metadata?.name
const storageCopyMethod = params.storageCopyMethod || 'normal'
const updatedMigrationTemplateFields: any = {
spec: {
networkMapping: networkMappings.metadata.name,
storageCopyMethod
}
}
// Add either arrayCredsMapping or storageMapping based on method
if (storageCopyMethod === 'StorageAcceleratedCopy' && arrayCredsMapping) {
updatedMigrationTemplateFields.spec.arrayCredsMapping = arrayCredsMapping.metadata.name
} else if (storageMappings) {
updatedMigrationTemplateFields.spec.storageMapping = storageMappings.metadata.name
}
try {
const data = await patchMigrationTemplate(
migrationTemplateName,
updatedMigrationTemplateFields
)
return data
} catch (err) {
setError({
title: 'Error updating migration template',
message: axios.isAxiosError(err) ? err?.response?.data?.message : ''
})
}
}
const createMigrationPlan = async (
updatedMigrationTemplate?: MigrationTemplate | null
): Promise<MigrationPlan> => {
if (!updatedMigrationTemplate?.metadata?.name) {
throw new Error('Migration template is not available')
}
const postMigrationAction = selectedMigrationOptions.postMigrationAction
? params.postMigrationAction
: undefined
const vmsToMigrate = (params.vms || []).map((vm) => vm.name)
// Build AssignedIPsPerVM map for cold migration
const assignedIPsPerVM: Record<string, string> = {}
if (params.vms) {
params.vms.forEach((vm) => {
if (vm.assignedIPs && vm.assignedIPs.trim() !== '') {
assignedIPsPerVM[vm.name] = vm.assignedIPs
}
})
}
const networkOverridesPerVM: Record<
string,
Array<{ interfaceIndex: number; preserveIP: boolean; preserveMAC: boolean }>
> = {}
if (params.vms) {
params.vms.forEach((vm) => {
const preserveIp = vm.preserveIp || {}
const preserveMac = vm.preserveMac || {}
const indices = new Set<string>([...Object.keys(preserveIp), ...Object.keys(preserveMac)])
if (indices.size === 0) return
networkOverridesPerVM[vm.name] = Array.from(indices)
.map((indexStr) => {
const interfaceIndex = Number(indexStr)
const ipFlag = preserveIp[interfaceIndex]
const macFlag = preserveMac[interfaceIndex]
return {
interfaceIndex,
preserveIP: ipFlag !== false,
preserveMAC: macFlag !== false
}
})
.sort((a, b) => a.interfaceIndex - b.interfaceIndex)
})
}
const migrationFields = {
migrationTemplateName: updatedMigrationTemplate?.metadata?.name,
virtualMachines: vmsToMigrate,
type: params.dataCopyMethod,
...(Object.keys(assignedIPsPerVM).length > 0 && { assignedIPsPerVM }),
...(Object.keys(networkOverridesPerVM).length > 0 && { networkOverridesPerVM }),
...(selectedMigrationOptions.dataCopyStartTime &&
params?.dataCopyStartTime && {
dataCopyStart: params.dataCopyStartTime
}),
...(selectedMigrationOptions.cutoverOption &&
params.cutoverOption === CUTOVER_TYPES.ADMIN_INITIATED && {
adminInitiatedCutOver: true
}),
...(selectedMigrationOptions.cutoverOption &&
params.cutoverOption === CUTOVER_TYPES.TIME_WINDOW &&
params.cutoverStartTime && {
vmCutoverStart: params.cutoverStartTime
}),
...(selectedMigrationOptions.cutoverOption &&
params.cutoverOption === CUTOVER_TYPES.TIME_WINDOW &&
params.cutoverEndTime && {
vmCutoverEnd: params.cutoverEndTime
}),
...(postMigrationAction && { postMigrationAction }),
...(params.securityGroups &&
params.securityGroups.length > 0 && {
securityGroups: params.securityGroups
}),
...(params.serverGroup && {
serverGroup: params.serverGroup
}),
disconnectSourceNetwork: params.disconnectSourceNetwork || false,
fallbackToDHCP: params.fallbackToDHCP || false,
...(selectedMigrationOptions.postMigrationScript &&
params.postMigrationScript && {
postMigrationScript: params.postMigrationScript
}),
...(typeof params.networkPersistence === 'boolean' && {
networkPersistence: params.networkPersistence
}),
...(typeof params.removeVMwareTools === 'boolean' && {
removeVMwareTools: params.removeVMwareTools
}),
periodicSyncInterval: params.periodicSyncInterval,
periodicSyncEnabled: selectedMigrationOptions.periodicSyncEnabled,
acknowledgeNetworkConflictRisk: params.acknowledgeNetworkConflictRisk
}
const body = createMigrationPlanJson(migrationFields)
try {
const data = await postMigrationPlan(body)
// Track successful migration creation
track(AMPLITUDE_EVENTS.MIGRATION_CREATED, {
migrationName: data.metadata?.name,
migrationTemplateName: updatedMigrationTemplate?.metadata?.name,
virtualMachineCount: vmsToMigrate?.length || 0,
migrationType: migrationFields.type,
hasDataCopyStartTime: !!migrationFields.dataCopyStart,
hasAdminInitiatedCutover: !!migrationFields.adminInitiatedCutOver,
hasTimedCutover: !!(migrationFields.vmCutoverStart && migrationFields.vmCutoverEnd),
postMigrationAction,
namespace: data.metadata?.namespace
})
return data
} catch (error: unknown) {
console.error('Error creating migration plan', error)
// Track migration creation failure
track(AMPLITUDE_EVENTS.MIGRATION_CREATION_FAILED, {
migrationTemplateName: updatedMigrationTemplate?.metadata?.name,
virtualMachineCount: vmsToMigrate?.length || 0,
migrationType: migrationFields.type,
errorMessage: error instanceof Error ? error.message : String(error),
stage: 'creation'
})
reportError(error as Error, {
context: 'migration-plan-creation',
metadata: {
migrationFields: migrationFields,
action: 'create-migration-plan'
}
})
let errorMessage = 'An unknown error occurred'
let errorResponse: {
status?: number
statusText?: string
data?: unknown
config?: {
url?: string
method?: string
data?: unknown
}
} = {}
if (axios.isAxiosError(error)) {
errorMessage = error.response?.data?.message || error.message || String(error)
errorResponse = {
status: error.response?.status,
statusText: error.response?.statusText,
data: error.response?.data,
config: {
url: error.config?.url,
method: error.config?.method,
data: error.config?.data
}
}
} else if (error instanceof Error) {
errorMessage = error.message
} else {
errorMessage = String(error)
}
console.error('Error details:', errorResponse)
setError({
title: 'Error creating migration plan',
message: errorMessage
})
getFieldErrorsUpdater('migrationPlan')(`Error creating migration plan: ${errorMessage}`)
throw error
}
}
const handleSubmit = useCallback(async () => {
setSubmitting(true)
setError(null)
const storageCopyMethod = params.storageCopyMethod || 'normal'
// Create NetworkMapping
const networkMappings = await createNetworkMapping(params.networkMappings)
if (!networkMappings) {
setSubmitting(false)
return
}
let storageMappings: any = null
let arrayCredsMapping: any = null
if (storageCopyMethod === 'StorageAcceleratedCopy') {
// Create ArrayCredsMapping for StorageAcceleratedCopy
arrayCredsMapping = await createArrayCredsMapping(params.arrayCredsMappings || [])
if (!arrayCredsMapping) {
setSubmitting(false)
return
}
} else {
// Create StorageMapping for normal copy
storageMappings = await createStorageMapping(params.storageMappings)
if (!storageMappings) {
setSubmitting(false)
return
}
}
// Update MigrationTemplate with NetworkMapping and StorageMapping/ArrayCredsMapping resource names
const updatedMigrationTemplate = await updateMigrationTemplate(
migrationTemplate,
networkMappings,
storageMappings,
arrayCredsMapping
)
// Create MigrationPlan
await createMigrationPlan(updatedMigrationTemplate)
// Stop submitting state
setSubmitting(false)
queryClient.invalidateQueries({ queryKey: MIGRATIONS_QUERY_KEY })
// Show success notification via callback
onSuccess?.('Migration submitted successfully')
// Close form and navigate
onClose()
navigate('/dashboard/migrations')
}, [
params.networkMappings,
params.storageMappings,
params.arrayCredsMappings,
params.storageCopyMethod,
migrationTemplate,
createNetworkMapping,
createStorageMapping,
createArrayCredsMapping,
updateMigrationTemplate,
createMigrationPlan,
queryClient,
onClose,
onSuccess,
navigate
])
const migrationOptionValidated = useMemo(() => {
return Object.keys(selectedMigrationOptions).every((key) => {
if (key === 'postMigrationAction') {
// Post-migration actions are optional, so we don't validate them here
return true
}
// TODO - Need to figure out a better way to add validation for periodic sync interval
if (key === 'periodicSyncEnabled' && selectedMigrationOptions.periodicSyncEnabled) {
return params?.periodicSyncInterval !== '' && fieldErrors['periodicSyncInterval'] === ''
}
if (key === 'dataCopyStartTime' && selectedMigrationOptions.dataCopyStartTime) {
const value = String(params?.dataCopyStartTime ?? '').trim()
return value !== '' && !fieldErrors['dataCopyStartTime']
}
if (key === 'postMigrationScript' && selectedMigrationOptions.postMigrationScript) {
const value = String(params?.postMigrationScript ?? '').trim()
return value !== '' && !fieldErrors['postMigrationScript']
}
if (selectedMigrationOptions[key as keyof typeof selectedMigrationOptions]) {
return params?.[key as keyof typeof params] !== undefined && !fieldErrors[key]
}
return true
})
}, [selectedMigrationOptions, params, fieldErrors])
// VM validation - ensure OS is assigned/detected for selected VMs
const vmValidation = useMemo(() => {
if (!params.vms || params.vms.length === 0) {
return { hasError: false, errorMessage: '' }
}
const poweredOffVMs = params.vms.filter((vm) => {
// Determine power state - check different possible property names
const powerState = vm.vmState === 'running' ? 'powered-on' : 'powered-off'
return powerState === 'powered-off'
})
const poweredOnVMs = params.vms.filter((vm) => {
// Determine power state - check different possible property names
const powerState = vm.vmState === 'running' ? 'powered-on' : 'powered-off'
return powerState === 'powered-on'
})
// Check for VMs without OS assignment or with Unknown OS (any power state)
const vmsWithoutOSAssigned = poweredOffVMs
.filter((vm) => !vm.osFamily || vm.osFamily === 'Unknown' || vm.osFamily.trim() === '')
.concat(
poweredOnVMs.filter(
(vm) => !vm.osFamily || vm.osFamily === 'Unknown' || vm.osFamily.trim() === ''
)
)
if (vmsWithoutOSAssigned.length > 0) {
let errorMessage = 'Cannot proceed with migration: '
const issues: string[] = []
if (vmsWithoutOSAssigned.length > 0) {
issues.push(
`We could not detect the operating system for ${vmsWithoutOSAssigned.length} VM${
vmsWithoutOSAssigned.length === 1 ? '' : 's'
}`
)
}
errorMessage +=
issues.join(' and ') + '. Please assign the required information before continuing.'
return { hasError: true, errorMessage }
}