-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudstack_migrate.py
More file actions
1685 lines (1261 loc) · 54.6 KB
/
cloudstack_migrate.py
File metadata and controls
1685 lines (1261 loc) · 54.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 os
import sys
import ssl
import time
import json
import hashlib
import argparse
import traceback
import subprocess
import nbd
import yaml
import random
import requests
import base64
import hmac
import urllib.parse
import string
import threading
import select
import fcntl
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
'''VCENTER = '10.0.35.3'
VCUSER = 'administrator@vsphere.local'
VCPASS = 'P@ssword123'
DATA = '/mnt/68f38850-a051-3ff1-9865-6a24a2ba2864'
VDDK = "/opt/vmware-vddk/vmware-vix-disklib-distrib/"
STATE_FILE = f"{DATA}/migration_state.json"'''
CONFIG_FILE = "config.yaml"
CONTROL_DIR = "/var/lib/vm-migrator"
def load_config():
with open(CONFIG_FILE) as f:
return yaml.safe_load(f)
config = load_config()
VCENTER = config["vcenter"]["host"]
VCUSER = config["vcenter"]["user"]
VCPASS = config["vcenter"]["password"]
#DATA = config["migration"]["data_dir"]
VDDK = config["migration"]["vddk_path"]
def migrate_vm(vmname):
log(f"Starting migration for {vmname}")
mig = Migrator(vmname)
log(f"Stage: {mig.state['stage']}")
log(f"VMware Tools status: {mig.vm.guest.toolsStatus}")
while True:
stage = mig.state["stage"]
log(f"Stage: {stage}")
if stage == MigrationStage.INIT:
mig.ensure_cbt_enabled()
mig.state["stage"] = MigrationStage.BASE_COPY
mig.save_state()
mig.base_copy()
mig.state["stage"] = MigrationStage.DELTA
mig.save_state()
elif stage in [MigrationStage.BASE_COPY, MigrationStage.DELTA]:
mig.run_delta_loop()
elif stage == MigrationStage.CONVERTING:
mig.run_virt_v2v()
elif stage == MigrationStage.IMPORT_ROOT_DISK:
boot_unit = mig.get_boot_disk_unit()
boot_disk = mig.get_v2v_boot_disk(boot_unit)
vm_id = mig.import_vm_to_cloudstack(boot_disk)
mig.state["vm_id"] = vm_id
mig.state["stage"] = MigrationStage.IMPORT_DATA_DISK
mig.save_state()
elif stage == MigrationStage.IMPORT_DATA_DISK:
mig.stage_import_data_disk()
mig.state["stage"] = MigrationStage.DONE
mig.save_state()
elif stage == MigrationStage.DONE:
log(f"{vmname} migration already completed")
break
def log(msg):
ts = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{ts}] {msg}", flush=True)
def wait_task(task):
while task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]:
time.sleep(1)
if task.info.state == vim.TaskInfo.State.error:
raise Exception(task.info.error)
def get_thumbprint(host):
cert = ssl.get_server_certificate((host, 443))
der = ssl.PEM_cert_to_DER_cert(cert)
sha = hashlib.sha1(der).hexdigest()
return ":".join(sha[i:i+2] for i in range(0, len(sha), 2)).upper()
def cloudstack_request(command, params):
cs = config["cloudstack"]
params["command"] = command
params["apikey"] = cs["api_key"]
params["response"] = "json"
query = "&".join(
f"{k}={urllib.parse.quote_plus(str(params[k]))}"
for k in sorted(params)
)
signature = base64.b64encode(
hmac.new(
cs["secret_key"].encode(),
query.lower().encode(),
hashlib.sha1
).digest()
).decode()
url = f"{cs['endpoint']}?{query}&signature={urllib.parse.quote_plus(signature)}"
r = requests.get(url)
return r.json()
def vcenter_keepalive(migrator):
while True:
try:
migrator.si.CurrentTime()
except Exception:
log("vCenter keepalive detected expired session")
time.sleep(60)
def format_bytes(b):
for unit in ['B','KB','MB','GB','TB']:
if b < 1024:
return f"{b:.1f}{unit}"
b/=1024
class MigrationStage:
INIT = "init"
BASE_COPY = "base_copy"
DELTA = "delta"
WAITING_FINALIZE = "waiting_finalize"
FINAL_SYNC = "final_sync"
CONVERTING = "converting"
IMPORT_ROOT_DISK = "import_root_disk"
IMPORT_DATA_DISK = "import_data_disk"
DONE = "done"
class Migrator:
def connect_vcenter(self):
ctx = ssl._create_unverified_context()
self.si = SmartConnect(
host=VCENTER,
user=VCUSER,
pwd=VCPASS,
sslContext=ctx
)
self.content = self.si.RetrieveContent()
# start keepalive only once
if not hasattr(self, "keepalive_started"):
threading.Thread(
target=vcenter_keepalive,
args=(self,),
daemon=True
).start()
self.keepalive_started = True
def ensure_vcenter_session(self):
try:
_ = self.vm.runtime.powerState
return
except vim.fault.NotAuthenticated:
log("vCenter session expired, reconnecting")
# reconnect
self.connect_vcenter()
# rebuild VM object using same moid
self.vm = vim.VirtualMachine(
self.vm_moid,
self.si._stub
)
def import_vm_to_cloudstack(self, disk_path):
cs = self.spec["target"]["cloudstack"]
hostname = self.vm.name.replace("_", "-") #sanitizing hostname to repalce _ with - as cloudstack doesn't allow _ in hostname. We can sanitize further as needed
params = {
"name": hostname,
"displayname": self.vm.name,
"clusterid": cs["clusterid"],
"zoneid": cs["zoneid"],
"importsource": "shared",
"hypervisor": "kvm",
"storageid": cs["storageid"],
"diskpath": os.path.basename(disk_path),
"networkid": cs["networkid"],
"serviceofferingid": cs["serviceofferingid"]
}
log(f"[+] Importing VM {self.vm.name} into CloudStack")
result = cloudstack_request("importVm", params)
job_id = result["importvmresponse"]["jobid"]
log(f"[+] Waiting for CloudStack import job {job_id}")
while True:
job = cloudstack_request("queryAsyncJobResult", {"jobid": job_id})
status = job["queryasyncjobresultresponse"]["jobstatus"]
log(f"[CloudStack] VM import job {job_id} status={status}")
if status == 1:
vm = job["queryasyncjobresultresponse"]["jobresult"]["virtualmachine"]
vm_id = vm["id"]
log(f"[+] VM import complete: {vm_id}")
return vm_id
if job["queryasyncjobresultresponse"]["jobstatus"] == 2:
raise Exception(f"CloudStack VM import failed: {job}")
time.sleep(5)
def import_data_disks(self, disk_path, storageid, diskofferingid):
cs = self.spec["target"]["cloudstack"]
params = {
"name": os.path.basename(disk_path),
"zoneid": cs["zoneid"],
"diskofferingid": diskofferingid,
"storageid": storageid,
"path": os.path.basename(disk_path)
}
log(f"[+] Importing data disk {disk_path}")
log(f" disk: {disk_path}")
log(f" storage: {storageid}")
log(f" offering: {diskofferingid}")
result = cloudstack_request("importVolume", params)
log(f"[+] CloudStack response: {result}")
resp = result.get("importvolumeresponse", {})
if "jobid" not in resp:
raise Exception(f"importVolume failed: {resp}")
job_id = resp["jobid"]
log(f"[+] Waiting for volume import job {job_id}")
while True:
job = cloudstack_request("queryAsyncJobResult", {"jobid": job_id})
status = job["queryasyncjobresultresponse"]["jobstatus"]
log(f"[CloudStack] Volume import job {job_id} status={status}")
if status == 1:
vol = job["queryasyncjobresultresponse"]["jobresult"]["volume"]
return vol["id"]
if status == 2:
raise Exception(f"Volume import failed: {job}")
time.sleep(5)
def get_data_disk_config(self, unit):
unit = str(unit)
disk_cfg = self.disk_map.get(unit)
if not disk_cfg:
raise Exception(f"Disk unit {unit} missing in spec.disks")
storageid = disk_cfg.get("storageid")
diskofferingid = disk_cfg.get("diskofferingid")
if not storageid:
raise Exception(f"Disk unit {unit} missing storageid")
if not diskofferingid:
raise Exception(f"Disk unit {unit} missing diskofferingid")
return storageid, diskofferingid
def resolve_data_import_path(self, unit):
unit = str(unit)
d = self.state["disks"].get(unit, {})
raw = d.get("path")
if not raw:
raise Exception(f"Missing state path for disk unit {unit}")
qcow = raw[:-4] + ".qcow2" if raw.endswith(".raw") else f"{raw}.qcow2"
if os.path.exists(qcow):
return qcow
if os.path.exists(raw):
return raw
raise Exception(f"No importable file for disk unit {unit}: {raw} / {qcow}")
def stage_import_data_disk(self):
log("Stage: import_data_disk")
boot_unit = str(self.get_boot_disk_unit())
vm_id = self.state.get("vm_id")
if not vm_id:
raise Exception("Cannot import data disks: missing vm_id in state")
data_units = [u for u in sorted(self.state["disks"].keys(), key=int) if str(u) != boot_unit]
if not data_units:
log("[+] No data disks found, skipping stage")
return
for unit in data_units:
storageid, diskofferingid = self.get_data_disk_config(unit)
disk_path = self.resolve_data_import_path(unit)
log(f"[+] Importing data disk {disk_path}")
volume_id = self.import_data_disks(disk_path, storageid, diskofferingid)
self.attach_volume(volume_id, vm_id)
with self.state_lock:
self.state["disks"][str(unit)]["volume_id"] = volume_id
self.state["disks"][str(unit)]["attached_to_vm_id"] = vm_id
self.save_state()
def attach_volume(self, volume_id, vm_id):
params = {
"id": volume_id,
"virtualmachineid": vm_id
}
log(f"[+] Attaching volume {volume_id} to VM {vm_id}")
result = cloudstack_request("attachVolume", params)
log(result)
def get_v2v_boot_disk(self, boot_unit):
self.ensure_vcenter_session()
letters = string.ascii_lowercase
disk_letter = letters[int(boot_unit)]
disk_path = os.path.join(self.DATA, f"{self.migration_id}-sd{disk_letter}")
if not os.path.exists(disk_path):
raise Exception(f"virt-v2v disk not found: {disk_path}")
return disk_path
def get_v2v_data_disks(self, boot_unit):
self.ensure_vcenter_session()
disks = []
for unit, disk in self.state["disks"].items():
if unit == str(boot_unit):
continue
raw = disk["path"]
qcow = raw.replace(".raw", ".qcow2")
if os.path.exists(qcow):
disks.append(qcow)
elif os.path.exists(raw):
disks.append(raw)
return disks
def get_disk_storage(self, unit):
unit = str(unit)
boot_unit = str(self.get_boot_disk_unit())
# Boot disk uses target.cloudstack.storageid.
if unit == boot_unit:
return self.spec["target"]["cloudstack"]["storageid"]
# Data disks use per-unit storage mapping from spec.disks.
disk_cfg = self.disk_map.get(unit)
if not disk_cfg:
raise Exception(f"Disk unit {unit} missing in spec")
return disk_cfg["storageid"]
def run_qemu_convert(self, cmd, raw_file, disk_size, disk_unit):
import pty
start = time.time()
master, slave = pty.openpty()
flags = fcntl.fcntl(master, fcntl.F_GETFL)
fcntl.fcntl(master, fcntl.F_SETFL, flags | os.O_NONBLOCK)
proc = subprocess.Popen(
cmd,
stdout=slave,
stderr=slave,
close_fds=True,
)
os.close(slave)
qemu_pct = 0.0
while proc.poll() is None:
ready, _, _ = select.select([master], [], [], 1.0)
if ready:
try:
data = os.read(master, 4096).decode(errors="ignore")
for part in data.split("\r"):
if "(" in part and "/100%" in part:
try:
qemu_pct = float(part.split("(")[1].split("/")[0])
except (IndexError, ValueError):
pass
except OSError:
pass
if os.path.exists(raw_file):
st = os.stat(raw_file)
written = st.st_blocks * 512
alloc_pct = min((written / disk_size) * 100, 100) if disk_size else 0
effective_pct = max(alloc_pct, qemu_pct)
elapsed = time.time() - start
speed = written / elapsed / (1024**2) if elapsed > 0 else 0
dynamic_estimated_used = None
if qemu_pct > 0:
ratio = max(min(qemu_pct, 100.0), 0.01) / 100.0
dynamic_estimated_used = int(written / ratio)
if disk_size:
dynamic_estimated_used = min(max(dynamic_estimated_used, written), disk_size)
elif dynamic_estimated_used < written:
dynamic_estimated_used = written
with self.state_lock:
disk_state = self.state["disks"].setdefault(str(disk_unit), {})
disk_state["qemu_progress"] = qemu_pct
disk_state["progress"] = effective_pct
disk_state["bytes_written"] = written
disk_state["copied_bytes"] = min(written, disk_size) if disk_size else written
locked_estimate = bool(disk_state.get("used_estimate_locked"))
if not locked_estimate and dynamic_estimated_used is not None:
previous_est = self._to_int(disk_state.get("estimated_used_bytes"))
if previous_est > 0:
diff_ratio = abs(dynamic_estimated_used - previous_est) / float(max(previous_est, 1))
stable_count = self._to_int(disk_state.get("used_estimate_stable_count"))
stable_count = stable_count + 1 if diff_ratio <= 0.02 else 0
smoothed = int((previous_est * 3 + dynamic_estimated_used) / 4)
new_estimate = max(smoothed, written)
else:
stable_count = 0
new_estimate = max(dynamic_estimated_used, written)
if disk_size:
new_estimate = min(new_estimate, disk_size)
disk_state["estimated_used_bytes"] = new_estimate
disk_state["read_total_bytes"] = new_estimate
disk_state["used_estimate_stable_count"] = stable_count
disk_state["used_size_source"] = "estimated_qemu"
if stable_count >= 5 and qemu_pct >= 20:
disk_state["used_estimate_locked"] = True
disk_state["used_size_source"] = "estimated_stable"
log(f"[disk{disk_unit}] locked used-size estimate at {format_bytes(new_estimate)}")
eta_total = self._to_int(disk_state.get("read_total_bytes")) or self._to_int(
disk_state.get("estimated_used_bytes")
)
if eta_total <= 0 and disk_size:
eta_total = disk_size
if eta_total > 0 and eta_total < written:
eta_total = written
disk_state["estimated_used_bytes"] = eta_total
disk_state["read_total_bytes"] = eta_total
disk_state["speed_mb"] = round(speed, 2)
disk_state["speed_mbps"] = round(speed, 2)
disk_state["transfer_speed_mbps"] = round(speed, 2)
if speed > 0 and eta_total > 0:
remaining = max(eta_total - written, 0)
disk_state["eta_seconds"] = int(remaining / (speed * 1024 * 1024))
self.state["transfer_speed_mbps"] = round(speed, 2)
self.state["stage"] = MigrationStage.BASE_COPY
self._recalculate_overall_progress_locked()
log(f"[disk{disk_unit}] copy {alloc_pct:.2f}% scan {qemu_pct:.2f}% {speed:.1f} MB/s")
self.save_state()
os.close(master)
if proc.returncode != 0:
raise Exception(f"qemu-img convert failed with code {proc.returncode}")
final_written = disk_size
if os.path.exists(raw_file):
try:
final_written = os.stat(raw_file).st_blocks * 512
except OSError:
final_written = disk_size
with self.state_lock:
disk_state = self.state["disks"].setdefault(str(disk_unit), {})
disk_state["qemu_progress"] = 100.0
disk_state["progress"] = 100.0
disk_state["bytes_written"] = final_written
disk_state["copied_bytes"] = final_written
disk_state["estimated_used_bytes"] = final_written
disk_state["read_total_bytes"] = final_written
disk_state["used_estimate_stable_count"] = 999
disk_state["used_estimate_locked"] = True
disk_state["used_size_source"] = "final_sparse_written"
disk_state["speed_mb"] = 0
disk_state["speed_mbps"] = 0
disk_state["transfer_speed_mbps"] = 0
disk_state["eta_seconds"] = 0
self.state["transfer_speed_mbps"] = 0
self._recalculate_overall_progress_locked()
self.save_state()
def _recalculate_overall_progress_locked(self):
progress_values = [
d.get("progress")
for d in self.state.get("disks", {}).values()
if isinstance(d.get("progress"), (int, float))
]
if progress_values:
self.state["progress"] = round(sum(progress_values) / len(progress_values), 2)
def __init__(self, vmname):
self.connect_vcenter()
view = self.content.viewManager.CreateContainerView(
self.content.rootFolder, [vim.VirtualMachine], True)
self.vm = next((vm for vm in view.view if vm.name == vmname), None)
if not self.vm:
raise Exception(f"VM {vmname} not found")
self.state_lock = threading.RLock()
self.migration_id = f"{self.vm.name}_{self.vm._moId}"
self.vm_moid = self.vm._moId
# ---- create VM control directory ----
self.control_dir = os.path.join(CONTROL_DIR, self.migration_id)
os.makedirs(self.control_dir, exist_ok=True)
# ---- load spec file ----
self.spec_file = os.path.join(self.control_dir, "spec.yaml")
if not os.path.exists(self.spec_file):
raise Exception(f"Missing spec file: {self.spec_file}")
with open(self.spec_file) as f:
self.spec = yaml.safe_load(f)
# ---- determine storage mount ----
self.disk_map = self.spec.get("disks", {})
boot_storageid = self.spec["target"]["cloudstack"]["storageid"]
self.DATA = ensure_storage_mounted(boot_storageid)
# ---- state file ----
self.state_file = os.path.join(self.control_dir, "state.json")
self.state = self.load_state()
# ---- other init values ----
self.thumb = get_thumbprint(VCENTER)
self.nbd_procs = []
view.Destroy()
def load_state(self):
if os.path.exists(self.state_file):
return json.load(open(self.state_file))
return {
"vm": self.vm.name,
"stage": MigrationStage.INIT,
"disks": {}
}
def save_state(self):
with self.state_lock:
os.makedirs(os.path.dirname(self.state_file), exist_ok=True)
tmp_file = f"{self.state_file}.tmp"
with open(tmp_file, "w") as f:
json.dump(self.state, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_file, self.state_file)
@staticmethod
def _to_int(value, default=0):
try:
return int(value)
except (TypeError, ValueError):
return default
def _vm_guest_used_total_bytes(self):
self.ensure_vcenter_session()
guest = getattr(self.vm, "guest", None)
if guest is None:
return None
tools_status = getattr(guest, "toolsStatus", None)
if tools_status not in ["toolsOk", "toolsOld"]:
return None
guest_disks = getattr(guest, "disk", None)
if not guest_disks:
return None
total_used = 0
for d in guest_disks:
capacity = getattr(d, "capacity", None)
free_space = getattr(d, "freeSpace", None)
if capacity is None or free_space is None:
continue
used = max(self._to_int(capacity) - self._to_int(free_space), 0)
total_used += used
if total_used <= 0:
return None
return total_used
def _seed_guest_used_estimates(self):
total_used = self._vm_guest_used_total_bytes()
if not total_used:
return
vm_disks = self.disks()
if not vm_disks:
return
total_capacity = sum(max(self._to_int(d.get("capacity")), 0) for d in vm_disks)
if total_capacity <= 0:
return
ordered_disks = sorted(vm_disks, key=lambda d: self._to_int(d.get("unit"), 10_000))
remaining = total_used
with self.state_lock:
self.state["guest_used_total_bytes"] = total_used
for idx, disk in enumerate(ordered_disks):
unit = str(disk["unit"])
capacity = max(self._to_int(disk.get("capacity")), 0)
disk_state = self.state["disks"].setdefault(unit, {})
if idx == len(ordered_disks) - 1:
allocated_used = max(remaining, 0)
else:
allocated_used = int((total_used * capacity) / total_capacity)
remaining -= allocated_used
if capacity > 0:
allocated_used = min(allocated_used, capacity)
copied = self._to_int(disk_state.get("copied_bytes"))
allocated_used = max(allocated_used, copied)
if capacity > 0:
allocated_used = min(allocated_used, capacity)
disk_state["estimated_used_bytes"] = allocated_used
disk_state["read_total_bytes"] = allocated_used
disk_state["used_estimate_stable_count"] = 999
disk_state["used_estimate_locked"] = True
disk_state["used_size_source"] = "vmware_tools_guest_disk"
log(f"[+] Seeded used-size from VMware Tools guest disks: {format_bytes(total_used)} total")
self.save_state()
def get_boot_disk_unit(self):
self.ensure_vcenter_session()
boot = self.vm.config.bootOptions
if boot and boot.bootOrder:
for device in boot.bootOrder:
if isinstance(device, vim.vm.BootOptions.BootableDiskDevice):
boot_key = device.deviceKey
for dev in self.vm.config.hardware.device:
if isinstance(dev, vim.vm.device.VirtualDisk) and dev.key == boot_key:
unit = dev.unitNumber
log(f"[+] Boot disk detected via VMware boot order: unit {unit}")
return str(unit)
# fallback if boot order not available
for dev in self.vm.config.hardware.device:
if isinstance(dev, vim.vm.device.VirtualDisk):
unit = dev.unitNumber
log(f"[+] Boot disk fallback detected: unit {unit}")
return str(unit)
raise Exception("Unable to determine boot disk unit")
def get_finalize_time(self):
mig = self.spec.get("migration", {})
finalize_at = mig.get("finalize_at")
if not finalize_at:
return None
return datetime.fromisoformat(finalize_at).timestamp()
def get_delta_sleep(self):
mig = self.spec.get("migration", {})
normal_interval = mig.get("delta_interval", 300)
finalize_interval = mig.get("finalize_delta_interval", 30)
finalize_window = mig.get("finalize_window", 600)
finalize_time = self.get_finalize_time()
if not finalize_time:
return normal_interval
remaining = finalize_time - time.time()
if remaining <= 0:
return 0
if remaining <= finalize_window:
return finalize_interval
return normal_interval
def check_snapshot_limit(self):
if not self.vm.snapshot:
return
def count(node):
total = 1
for c in node.childSnapshotList:
total += count(c)
return total
#total = count(self.vm.snapshot.rootSnapshotList[0])
total = 0
for root in self.vm.snapshot.rootSnapshotList:
total += count(root)
if total > 25:
raise Exception(
f"Snapshot count dangerously high ({total}). "
"User must finalize migration."
)
def create_snapshot(self, name):
self.ensure_vcenter_session()
mode = config["migration"].get("snapshot_quiesce", "auto")
log(f"Creating snapshot {name} (quiesce mode: {mode})")
def run_snapshot(quiesce):
task = self.vm.CreateSnapshot(
name=name,
memory=False,
quiesce=quiesce
)
while task.info.state in [vim.TaskInfo.State.running, vim.TaskInfo.State.queued]:
time.sleep(1)
if task.info.state == vim.TaskInfo.State.success:
return task.info.result
raise Exception(task.info.error)
tools_status = self.vm.guest.toolsStatus
# Always non-quiesced
if mode == "false":
log("Using non-quiesced snapshot")
return run_snapshot(False)
# Force quiesced
if mode == "true":
log("Using quiesced snapshot")
return run_snapshot(True)
# AUTO mode
if tools_status in ["toolsOk", "toolsOld"]:
try:
log("Trying quiesced snapshot")
return run_snapshot(True)
except Exception as e:
log(f"Quiesced snapshot failed: {e}")
log("Falling back to non-quiesced snapshot")
else:
log("VMware Tools not running, skipping quiesced snapshot")
return run_snapshot(False)
def run_delta_loop(self):
log(f"[{self.vm.name}] Entering delta sync loop")
finalize_file = os.path.join(self.control_dir, "FINALIZE")
while True:
if self.state["stage"] == MigrationStage.DONE:
Disconnect(self.si)
return
now = time.time()
finalize_time = self.get_finalize_time()
# Scheduled finalize
if finalize_time and now >= finalize_time:
log(f"[{self.vm.name}] Scheduled finalize triggered")
open(finalize_file, "a").close()
# Manual finalize
if os.path.exists(finalize_file):
log(f"[{self.vm.name}] Finalize triggered")
self.finalize()
Disconnect(self.si)
return
# Run delta sync
log(f"[{self.vm.name}] Running delta sync")
self.delta()
self.state["stage"] = MigrationStage.DELTA
self.save_state()
sleep_time = self.get_delta_sleep()
# Ensure we don't oversleep past finalize
if finalize_time:
remaining = finalize_time - time.time()
if remaining > 0:
sleep_time = min(sleep_time, remaining)
if sleep_time <= 0:
continue
log(f"[{self.vm.name}] Sleeping {sleep_time}s")
time.sleep(sleep_time)
def disks(self):
disks = []
self.ensure_vcenter_session()
for d in self.vm.config.hardware.device:
if isinstance(d, vim.vm.device.VirtualDisk):
curr = d.backing
while hasattr(curr, 'parent') and curr.parent:
curr = curr.parent
disks.append({
"key": d.key,
"unit": d.unitNumber,
"path": curr.fileName,
"capacity": d.capacityInBytes
})
return disks
def ensure_cbt_enabled(self):
self.ensure_vcenter_session()
if not self.vm.config.changeTrackingEnabled:
log(f"[!] CBT is NOT enabled on {self.vm.name}. Enabling now...")
spec = vim.vm.ConfigSpec(changeTrackingEnabled=True)
task = self.vm.ReconfigVM_Task(spec)
wait_task(task)
log("[+] CBT enabled successfully.")
else:
log("[+] CBT is already enabled. Proceeding...")
def get_snapshot_disk_path(self, snapshot, disk_key):
# This searches the snapshot configuration for the backing file of the specific disk
for device in snapshot.config.hardware.device:
if isinstance(device, vim.vm.device.VirtualDisk) and device.key == disk_key:
return device.backing.fileName
return None
def start_nbd(self, disk, snapshot, export_name=None):
self.ensure_vcenter_session()
# FORCE RELOAD: This updates the local snapshot object with real data from vCenter
# Without this, the object is just a shell and lacks the .name attribute
# We retrieve the 'config' or 'name' property explicitly
content = self.si.RetrieveContent()
# Or simply re-fetch it if you have the MOREF
# But usually, just accessing an attribute that forces a fetch works:
try:
snap_name = snapshot.name
except AttributeError:
# If it fails, the object is likely stale. Refresh it by calling UpdateView
# or just use the _moId which you already have.
snap_name = "Snapshot_Refreshed"
print(f"DEBUG: Opening disk at path: {disk['path']}")
sock = f"/tmp/nbd_{self.migration_id}_{disk['unit']}.sock"
if os.path.exists(sock):
os.remove(sock)
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = f"{VDDK}/lib64"
# Then in start_nbd:
snapshot_disk_path = self.get_snapshot_disk_path(snapshot, disk['key'])
cmd = [
"nbdkit",
"-r",
"-t", "16", #enable 16 worker threads
"--filter=cache", #cache reads locally
"--filter=retry", #retry VDDK read failures
"vddk",
f"libdir={VDDK}",
f"server={VCENTER}",
f"user={VCUSER}",
f"password={VCPASS}",
f"thumbprint={self.thumb}",
"transports=nbd",
f"vm=moref={self.vm._moId}",
f"file={snapshot_disk_path}",
f"snapshot=moref={snapshot._moId}",
"--exit-with-parent",
"--unix", sock