-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenstack_parallel_migrate.py
More file actions
1921 lines (1600 loc) · 68.2 KB
/
openstack_parallel_migrate.py
File metadata and controls
1921 lines (1600 loc) · 68.2 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
#!/usr/bin/env python3
#
# License: MIT
# Copyright (c) 2026 EUMETSAT
# See the LICENSE file for more details
# Need to install pv on instance #
import argparse
import concurrent.futures
import contextlib
import hashlib
import json
import math
import os
import sys
import tempfile
import threading
import time
import subprocess
import shutil
import shlex
from pathlib import Path
from typing import Optional
import openstack
import yaml
from tqdm import tqdm
STATE_DIR = Path("state")
STATE_DIR.mkdir(exist_ok=True)
IMAGE_STALE_STATUSES = {
"queued",
"saving",
"uploading",
"importing",
"deactivated",
"killed",
"deleted",
"pending_delete",
}
IMAGE_READY_STATUSES = {"active"}
SOURCE_IMAGE_WAITABLE = {"queued", "saving", "uploading", "importing"}
SNAPSHOT_WAITABLE = {"creating"}
VOLUME_WAITABLE = {"creating", "downloading", "uploading"}
VOLUME_FAIL_STATUSES = {"error", "error_restoring", "error_extending", "error_managing"}
SERVER_FAIL_STATUSES = {"ERROR"}
STREAM_CHUNK_SIZE = 4 * 1024 * 1024 # 4 MiB
PRINT_LOCK = threading.Lock()
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
def log(msg: str) -> None:
with PRINT_LOCK:
tqdm.write(f"[INFO] {msg}")
def warn(msg: str) -> None:
with PRINT_LOCK:
tqdm.write(f"[WARN] {msg}", file=sys.stderr)
def err(msg: str) -> None:
with PRINT_LOCK:
tqdm.write(f"[ERROR] {msg}", file=sys.stderr)
# ---------------------------------------------------------------------------
# State handling
# ---------------------------------------------------------------------------
def state_path(server_name: str) -> Path:
safe = "".join(c if c.isalnum() or c in ("-", "_", ".") else "_" for c in server_name)
return STATE_DIR / f"{safe}.json"
def load_state(server_name: str) -> dict:
path = state_path(server_name)
if not path.exists():
return {
"server_name": server_name,
"artifact_order": [],
"artifacts": {},
"ports": [],
"source_server_id": None,
"source_server_was_volume_backed": None,
"target_server_id": None,
"target_server_name": None,
"target_root_created": False,
"target_data_attached": [],
"target_started": False,
"current_stage": None,
"started_at": None,
"updated_at": None,
}
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def atomic_write_json(path: Path, payload: dict) -> None:
fd, tmp_name = tempfile.mkstemp(prefix=path.name, suffix=".tmp", dir=str(path.parent))
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2, sort_keys=True)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_name, path)
finally:
with contextlib.suppress(FileNotFoundError):
os.unlink(tmp_name)
def save_state(server_name: str, state: dict) -> None:
state["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
if not state.get("started_at"):
state["started_at"] = state["updated_at"]
atomic_write_json(state_path(server_name), state)
def set_stage(server_name: str, state: dict, stage: str) -> None:
state["current_stage"] = stage
save_state(server_name, state)
log(f"{server_name}: {stage}")
# ---------------------------------------------------------------------------
# Config loading
# ---------------------------------------------------------------------------
def load_yaml_file(path: str) -> dict:
with open(path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
if not isinstance(data, dict):
raise RuntimeError(f"{path} must contain a YAML mapping/object")
return data
def load_flavor_map(path: str | None) -> dict:
if not path:
return {}
data = load_yaml_file(path)
return {str(k): str(v) for k, v in data.items()}
# ---------------------------------------------------------------------------
# OpenStack connection
# ---------------------------------------------------------------------------
def connect(cloud_name: str):
try:
conn = openstack.connect(cloud=cloud_name)
conn.authorize()
return conn
except Exception as e:
raise RuntimeError(
f"Failed to connect/authenticate to cloud '{cloud_name}'. "
f"Check clouds.yaml (including OIDC auth plugin settings if used). "
f"Original error: {e}"
) from e
# ---------------------------------------------------------------------------
# Generic wait helpers
# ---------------------------------------------------------------------------
def wait_for_status(
getter,
resource_id: str,
wanted: str,
fail_states: set[str] | None = None,
timeout: int = 3600,
interval: int = 5,
desc: str | None = None,
heartbeat_every: int = 60,
):
start = time.time()
last_heartbeat = 0
while True:
obj = getter(resource_id)
status = getattr(obj, "status", None) or getattr(obj, "state", None)
if status == wanted:
return obj
if fail_states and status in fail_states:
raise RuntimeError(f"-- {desc or resource_id} entered failure state {status}")
now = time.time()
if now - last_heartbeat >= heartbeat_every:
log(f"-- Waiting for {desc or resource_id}: current status={status}, target={wanted}")
last_heartbeat = now
if now - start > timeout:
raise TimeoutError(f"-- Timeout waiting for {desc or resource_id} -> {wanted}, current={status}")
time.sleep(interval)
def wait_until_deleted(getter, resource_id: str, timeout: int = 900, interval: int = 5, desc: str | None = None):
start = time.time()
while True:
try:
obj = getter(resource_id)
except Exception:
return
if obj is None:
return
if time.time() - start > timeout:
raise TimeoutError(f"-- Timeout waiting for deletion of {desc or resource_id}")
time.sleep(interval)
def wait_for_image_ready(conn, image_id: str, timeout: int = 7200, interval: int = 10, desc: str | None = None):
start = time.time()
last_heartbeat = 0
desc = desc or f"image {image_id}"
while True:
img = conn.image.find_image(image_id, ignore_missing=True)
status = getattr(img, "status", None) if img else None
if status == "active":
return img
if status in {"killed", "deleted", "deactivated"}:
raise RuntimeError(f"-- {desc} entered failure state {status}")
now = time.time()
if now - last_heartbeat >= 60:
log(f"-- Waiting for {desc}: current status={status}, target=active")
last_heartbeat = now
try:
stream = conn.image.download_image(image_id, stream=True)
iterator = iter(stream)
first_chunk = next(iterator, None)
if first_chunk is not None:
log(f"-- {desc} is downloadable; treating it as ready")
return img or conn.image.get_image(image_id)
except Exception:
pass
if now - start > timeout:
raise TimeoutError(f"-- Timeout waiting for {desc} -> active, current={status}")
time.sleep(interval)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def stable_name(*parts: str) -> str:
raw = "::".join(parts)
digest = hashlib.sha1(raw.encode("utf-8")).hexdigest()[:12]
base = "-".join(p for p in parts if p)
base = "".join(c if c.isalnum() or c in ("-", "_", ".") else "-" for c in base)
return f"{base}-{digest}"
def iter_server_names(source, configured_servers):
if configured_servers == "all":
return [s.name for s in source.compute.servers(all_projects=False)]
if not isinstance(configured_servers, list):
raise RuntimeError("servers in migrate.yaml must be a list or the string 'all'")
return [str(x) for x in configured_servers]
def get_server(source, server_name: str):
srv = source.compute.find_server(server_name, ignore_missing=True)
if not srv:
raise RuntimeError(f"Source server '{server_name}' not found")
return source.compute.get_server(srv.id)
def flavor_name_from_server(source, server) -> str:
flavor_info = getattr(server, "flavor", {}) or {}
original_name = flavor_info.get("original_name")
if original_name:
return original_name
flavor_id = flavor_info.get("id")
if not flavor_id:
raise RuntimeError(f"{server.name}: could not determine source flavor")
flv = source.compute.get_flavor(flavor_id)
return flv.name
def flavor_root_disk_gb_from_server(source, server) -> int:
flavor_info = getattr(server, "flavor", {}) or {}
disk = flavor_info.get("disk")
if disk is not None:
try:
return int(disk)
except Exception:
pass
flavor_id = flavor_info.get("id")
if not flavor_id:
return 0
flv = source.compute.get_flavor(flavor_id)
try:
return int(getattr(flv, "disk", 0) or 0)
except Exception:
return 0
def bytes_to_gib_ceil(value) -> int:
if value is None:
return 1
try:
value = int(value)
except Exception:
return 1
gib = 1024 ** 3
return max(1, math.ceil(value / gib))
def volume_attachment_device(vol, server_id: str):
for att in getattr(vol, "attachments", []) or []:
if att.get("server_id") == server_id:
return att.get("device") or att.get("mountpoint")
return None
def artifact_key(kind: str, source_id: str) -> str:
return f"{kind}:{source_id}"
def record_artifacts_in_state(server_name: str, state: dict, artifacts: list[dict]) -> None:
state["artifact_order"] = []
for art in artifacts:
entry = {
"kind": art["kind"],
"role": art["role"],
"source_id": art["source_id"],
"device_name": art.get("device_name"),
"boot_index": art.get("boot_index"),
"source_flavor_root_disk_gb": art.get("source_flavor_root_disk_gb"),
}
state["artifact_order"].append(entry)
save_state(server_name, state)
def load_artifacts_from_state(state: dict) -> list[dict]:
return list(state.get("artifact_order", []) or [])
def _normalize_glance_base(endpoint: str) -> str:
"""
Convert a Glance endpoint into a base URL without a trailing /v2.
Examples:
https://glance.example.com:9292 -> https://glance.example.com:9292
https://glance.example.com:9292/ -> https://glance.example.com:9292
https://glance.example.com:9292/v2 -> https://glance.example.com:9292
https://glance.example.com:9292/v2/ -> https://glance.example.com:9292
"""
endpoint = endpoint.rstrip("/")
if endpoint.endswith("/v2"):
endpoint = endpoint[:-3]
return endpoint.rstrip("/")
def _get_token_and_glance_base(conn):
token = conn.session.get_token()
endpoint = conn.image.get_endpoint()
base = _normalize_glance_base(endpoint)
return token, base
def _target_supports_import(target) -> bool:
"""
If your target cloud supports glance-direct import, return True.
Otherwise return False and the code will use direct file upload.
"""
return False
def reserve_progress_lines(n: int) -> None:
for _ in range(max(0, n)):
print()
def _build_positioned_pv_cmd(
image_size: Optional[int] = None,
label: Optional[str] = None,
line_up: int = 1,
) -> list[str]:
pv = "exec pv --cursor -f -i 1 -p -t -e -r -b"
if image_size and image_size > 0:
pv += f" -s {int(image_size)}"
if label:
pv += f" -N {shlex.quote(label)}"
script = f'printf "\\033[{int(line_up)}A" >&2; {pv}'
return ["bash", "-lc", script]
def stream_image_via_curl(
source,
target,
source_image_id: str,
target_image_id: str,
image_size: int | None = None,
label: str | None = None,
progress_line_up: int | None = None,
):
src_token, src_base = _get_token_and_glance_base(source)
tgt_token, tgt_base = _get_token_and_glance_base(target)
src_url = f"{src_base}/v2/images/{source_image_id}/file"
if _target_supports_import(target):
tgt_url = f"{tgt_base}/v2/images/{target_image_id}/stage"
else:
tgt_url = f"{tgt_base}/v2/images/{target_image_id}/file"
src_cmd = [
"curl",
"--fail",
"--silent",
"--show-error",
"--no-buffer",
"--http1.1",
"-H", f"X-Auth-Token: {src_token}",
src_url,
]
have_pv = shutil.which("pv") is not None
pv_cmd = None
if have_pv:
if progress_line_up and progress_line_up > 0:
pv_cmd = _build_positioned_pv_cmd(
image_size=image_size,
label=label,
line_up=progress_line_up,
)
else:
pv_cmd = [
"pv",
"--cursor",
"-f",
"-i", "1",
"-p",
"-t",
"-e",
"-r",
"-b",
]
if image_size and image_size > 0:
pv_cmd += ["-s", str(image_size)]
if label:
pv_cmd += ["-N", label]
tgt_cmd = [
"curl",
"--fail",
"--silent",
"--show-error",
"--http1.1",
"-X", "PUT",
"-H", f"X-Auth-Token: {tgt_token}",
"-H", "Content-Type: application/octet-stream",
"-H", "Expect:",
"--upload-file", "-",
tgt_url,
]
log(f"Source curl URL: {src_url}")
log(f"Target curl URL: {tgt_url}")
p1 = subprocess.Popen(
src_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=False,
)
p_pv = None
if have_pv:
p_pv = subprocess.Popen(
pv_cmd,
stdin=p1.stdout,
stdout=subprocess.PIPE,
stderr=None,
text=False,
)
if p1.stdout is not None:
p1.stdout.close()
p2 = subprocess.Popen(
tgt_cmd,
stdin=p_pv.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=False,
)
if p_pv.stdout is not None:
p_pv.stdout.close()
else:
p2 = subprocess.Popen(
tgt_cmd,
stdin=p1.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=False,
)
if p1.stdout is not None:
p1.stdout.close()
out2, err2 = p2.communicate()
if p_pv is not None:
pv_rc = p_pv.wait()
if progress_line_up and progress_line_up > 0:
print(f"\033[{int(progress_line_up)}B", end="", flush=True)
else:
pv_rc = 0
out1, err1 = p1.communicate()
err1_txt = err1.decode(errors="replace") if err1 else ""
err2_txt = err2.decode(errors="replace") if err2 else ""
if p2.returncode != 0:
raise RuntimeError(f"Target curl upload failed rc={p2.returncode}: {err2_txt}")
if p_pv is not None and pv_rc != 0:
raise RuntimeError(f"pv failed rc={pv_rc}")
if p1.returncode != 0:
raise RuntimeError(f"Source curl download failed rc={p1.returncode}: {err1_txt}")
# ---------------------------------------------------------------------------
# Source storage detection
# ---------------------------------------------------------------------------
def list_cinder_volumes_attached_to_server(source, server) -> list:
attached = []
for vol in source.block_storage.volumes(details=True):
for att in getattr(vol, "attachments", []) or []:
if att.get("server_id") == server.id:
attached.append(vol)
break
return attached
def detect_source_workload_storage(source, server) -> list[dict]:
srv = source.compute.get_server(server.id)
bdm = getattr(srv, "block_device_mapping", None) or []
attached_vols = list_cinder_volumes_attached_to_server(source, srv)
attached_by_id = {v.id: v for v in attached_vols}
volume_entries = []
root_volume_id = None
if isinstance(bdm, list):
for entry in bdm:
if not isinstance(entry, dict):
continue
vol_id = entry.get("uuid") or entry.get("volume_id") or entry.get("source_id")
if not vol_id:
continue
boot_index = entry.get("boot_index")
try:
bi = int(boot_index)
except Exception:
bi = None
device_name = entry.get("device_name")
volume_entries.append({
"source_id": vol_id,
"boot_index": bi,
"device_name": device_name,
})
if bi == 0:
root_volume_id = vol_id
if root_volume_id:
artifacts = []
root_vol = attached_by_id.get(root_volume_id)
root_device = volume_attachment_device(root_vol, srv.id) if root_vol else None
root_bdm = next((x for x in volume_entries if x["source_id"] == root_volume_id), {})
artifacts.append({
"kind": "volume",
"role": "root",
"source_id": root_volume_id,
"device_name": root_bdm.get("device_name") or root_device,
"boot_index": 0,
"source_flavor_root_disk_gb": None,
})
data_candidates = []
for vol in attached_vols:
if vol.id == root_volume_id:
continue
bdm_info = next((x for x in volume_entries if x["source_id"] == vol.id), {})
device_name = bdm_info.get("device_name") or volume_attachment_device(vol, srv.id)
boot_index = bdm_info.get("boot_index")
data_candidates.append({
"kind": "volume",
"role": "data",
"source_id": vol.id,
"device_name": device_name,
"boot_index": boot_index if boot_index is not None else 9999,
"source_flavor_root_disk_gb": None,
})
data_candidates.sort(key=lambda x: (x.get("boot_index", 9999), x.get("device_name") or "", x["source_id"]))
artifacts.extend(data_candidates)
return artifacts
warn(f"{server.name}: Nova block_device_mapping did not reveal root volume cleanly, checking image-backed boot")
server_image = getattr(srv, "image", None) or {}
image_id = server_image.get("id") if isinstance(server_image, dict) else None
if image_id:
flavor_root_disk_gb = flavor_root_disk_gb_from_server(source, srv)
artifacts = [{
"kind": "image",
"role": "root",
"source_id": image_id,
"device_name": None,
"boot_index": 0,
"source_flavor_root_disk_gb": flavor_root_disk_gb,
}]
data_candidates = []
for vol in attached_vols:
device_name = volume_attachment_device(vol, srv.id)
data_candidates.append({
"kind": "volume",
"role": "data",
"source_id": vol.id,
"device_name": device_name,
"boot_index": 9999,
"source_flavor_root_disk_gb": None,
})
data_candidates.sort(key=lambda x: (x.get("device_name") or "", x["source_id"]))
artifacts.extend(data_candidates)
return artifacts
if attached_vols:
bootable = [v for v in attached_vols if str(getattr(v, "is_bootable", "")).lower() == "true"]
if len(bootable) == 1:
root_vol = bootable[0]
artifacts = [{
"kind": "volume",
"role": "root",
"source_id": root_vol.id,
"device_name": volume_attachment_device(root_vol, srv.id),
"boot_index": 0,
"source_flavor_root_disk_gb": None,
}]
data_candidates = []
for vol in attached_vols:
if vol.id == root_vol.id:
continue
data_candidates.append({
"kind": "volume",
"role": "data",
"source_id": vol.id,
"device_name": volume_attachment_device(vol, srv.id),
"boot_index": 9999,
"source_flavor_root_disk_gb": None,
})
data_candidates.sort(key=lambda x: (x.get("device_name") or "", x["source_id"]))
artifacts.extend(data_candidates)
return artifacts
raise RuntimeError(f"{server.name}: could not determine whether the workload is booted from volume or from image")
def is_volume_backed(artifacts: list[dict]) -> bool:
return bool(artifacts) and artifacts[0]["kind"] == "volume"
# ---------------------------------------------------------------------------
# Security groups
# ---------------------------------------------------------------------------
def sg_rule_ethertype(rule):
return getattr(rule, "ether_type", getattr(rule, "ethertype", None))
def normalize_sg_rule_dict(rule_dict: dict) -> dict:
return {
"direction": rule_dict.get("direction"),
"ether_type": rule_dict.get("ether_type"),
"protocol": rule_dict.get("protocol"),
"port_range_min": rule_dict.get("port_range_min"),
"port_range_max": rule_dict.get("port_range_max"),
"remote_ip_prefix": rule_dict.get("remote_ip_prefix"),
"remote_group_id": rule_dict.get("remote_group_id"),
}
def normalize_sg_rule_obj(rule) -> dict:
return {
"direction": getattr(rule, "direction", None),
"ether_type": sg_rule_ethertype(rule),
"protocol": getattr(rule, "protocol", None),
"port_range_min": getattr(rule, "port_range_min", None),
"port_range_max": getattr(rule, "port_range_max", None),
"remote_ip_prefix": getattr(rule, "remote_ip_prefix", None),
"remote_group_id": getattr(rule, "remote_group_id", None),
}
def build_sg_rule_payload(rule, target_sg_id: str, remote_group_id: str | None = None) -> dict:
payload = {
"security_group_id": target_sg_id,
"direction": getattr(rule, "direction", None),
"ether_type": sg_rule_ethertype(rule),
}
if getattr(rule, "protocol", None) is not None:
payload["protocol"] = rule.protocol
if getattr(rule, "port_range_min", None) is not None:
payload["port_range_min"] = rule.port_range_min
if getattr(rule, "port_range_max", None) is not None:
payload["port_range_max"] = rule.port_range_max
if getattr(rule, "remote_ip_prefix", None):
payload["remote_ip_prefix"] = rule.remote_ip_prefix
if remote_group_id:
payload["remote_group_id"] = remote_group_id
return payload
def ensure_security_groups(source, target, server) -> list[str]:
src_srv = source.compute.get_server(server.id)
attached_sg_names = [sg["name"] for sg in getattr(src_srv, "security_groups", [])]
if not attached_sg_names:
return []
chosen_names = []
src_sg_cache_by_id = {sg.id: sg for sg in source.network.security_groups()}
tgt_sg_cache_by_name = {sg.name: sg for sg in target.network.security_groups()}
for name in attached_sg_names:
src_sg = source.network.find_security_group(name, ignore_missing=True)
if not src_sg:
raise RuntimeError(f"{server.name}: source security group '{name}' not found")
tgt_sg = tgt_sg_cache_by_name.get(name)
if not tgt_sg:
log(f"{server.name}: creating target security group '{name}'")
tgt_sg = target.network.create_security_group(name=name)
tgt_sg_cache_by_name[tgt_sg.name] = tgt_sg
def map_remote_group(src_remote_group_id: str | None):
if not src_remote_group_id:
return None
src_remote = src_sg_cache_by_id.get(src_remote_group_id)
if not src_remote:
warn(f"{server.name}: remote_group_id={src_remote_group_id} not visible on source; omitting remote_group_id")
return None
tgt_remote = tgt_sg_cache_by_name.get(src_remote.name)
if not tgt_remote:
log(f"{server.name}: creating referenced remote security group '{src_remote.name}'")
tgt_remote = target.network.create_security_group(name=src_remote.name)
tgt_sg_cache_by_name[tgt_remote.name] = tgt_remote
return tgt_remote.id
src_rules = list(source.network.security_group_rules(security_group_id=src_sg.id))
tgt_rules = list(target.network.security_group_rules(security_group_id=tgt_sg.id))
existing = {json.dumps(normalize_sg_rule_obj(r), sort_keys=True) for r in tgt_rules}
for rule in src_rules:
mapped_remote_group_id = map_remote_group(getattr(rule, "remote_group_id", None))
payload = build_sg_rule_payload(rule, tgt_sg.id, mapped_remote_group_id)
key = json.dumps(
normalize_sg_rule_dict({
"direction": payload.get("direction"),
"ether_type": payload.get("ether_type"),
"protocol": payload.get("protocol"),
"port_range_min": payload.get("port_range_min"),
"port_range_max": payload.get("port_range_max"),
"remote_ip_prefix": payload.get("remote_ip_prefix"),
"remote_group_id": payload.get("remote_group_id"),
}),
sort_keys=True,
)
if key in existing:
continue
try:
target.network.create_security_group_rule(**payload)
existing.add(key)
except Exception as e:
msg = str(e).lower()
if "already exists" in msg or "conflict" in msg or "409" in msg:
existing.add(key)
continue
raise RuntimeError(f"{server.name}: failed creating SG rule in '{tgt_sg.name}': {e}") from e
chosen_names.append(tgt_sg.name)
return chosen_names
# ---------------------------------------------------------------------------
# Networking / ports
# ---------------------------------------------------------------------------
def source_fixed_ip_plan(server) -> list[dict]:
plan = []
for network_name, addr_list in (getattr(server, "addresses", {}) or {}).items():
for addr in addr_list:
if addr.get("OS-EXT-IPS:type") == "fixed":
plan.append({"network_name": network_name, "fixed_ip": addr["addr"]})
return plan
def ensure_target_ports(target, server, sg_names: list[str], state: dict) -> list[str]:
existing_port_ids = []
for port_id in list(state.get("ports", []) or []):
try:
port = target.network.get_port(port_id)
except Exception:
port = None
if port:
existing_port_ids.append(port.id)
if state.get("ports") and len(existing_port_ids) == len(state.get("ports")):
state["ports"] = existing_port_ids
return existing_port_ids
state["ports"] = []
plan = source_fixed_ip_plan(server)
if not plan:
raise RuntimeError(f"{server.name}: no fixed IPs discovered on source server")
sg_ids = []
for name in sg_names:
sg = target.network.find_security_group(name, ignore_missing=True)
if not sg:
raise RuntimeError(f"{server.name}: target security group '{name}' missing before port creation")
sg_ids.append(sg.id)
created = []
try:
for item in plan:
network_name = item["network_name"]
fixed_ip = item["fixed_ip"]
tgt_net = target.network.find_network(network_name, ignore_missing=True)
if not tgt_net:
raise RuntimeError(f"{server.name}: target network '{network_name}' not found")
desired_name = stable_name("migrated-port", server.name, network_name, fixed_ip)
reused = False
for port in target.network.ports(network_id=tgt_net.id):
fixed_ips = getattr(port, "fixed_ips", []) or []
if port.name == desired_name and any(x.get("ip_address") == fixed_ip for x in fixed_ips):
created.append(port.id)
reused = True
break
if reused:
continue
port = target.network.create_port(
name=desired_name,
network_id=tgt_net.id,
fixed_ips=[{"ip_address": fixed_ip}],
security_group_ids=sg_ids,
)
created.append(port.id)
state["ports"] = created
return created
except Exception:
for port_id in created:
with contextlib.suppress(Exception):
target.network.delete_port(port_id, ignore_missing=True)
raise
# ---------------------------------------------------------------------------
# Cleanup helpers
# ---------------------------------------------------------------------------
def cleanup_target_image(target, image_id: str | None):
if not image_id:
return
with contextlib.suppress(Exception):
target.image.delete_image(image_id, ignore_missing=True)
with contextlib.suppress(Exception):
wait_until_deleted(lambda rid: target.image.find_image(rid, ignore_missing=True), image_id, desc=f"image {image_id}")
def cleanup_target_volume(target, volume_id: str | None):
if not volume_id:
return
with contextlib.suppress(Exception):
target.block_storage.delete_volume(volume_id, force=True, ignore_missing=True)
with contextlib.suppress(Exception):
wait_until_deleted(lambda rid: target.block_storage.find_volume(rid, ignore_missing=True), volume_id, desc=f"volume {volume_id}")
def cleanup_source_snapshot(source, snapshot_id: str | None):
if not snapshot_id:
return
with contextlib.suppress(Exception):
source.block_storage.delete_snapshot(snapshot_id, ignore_missing=True)
with contextlib.suppress(Exception):
wait_until_deleted(lambda rid: source.block_storage.find_snapshot(rid, ignore_missing=True), snapshot_id, desc=f"snapshot {snapshot_id}")
def cleanup_source_volume(source, volume_id: str | None):
if not volume_id:
return
with contextlib.suppress(Exception):
source.block_storage.delete_volume(volume_id, force=True, ignore_missing=True)
with contextlib.suppress(Exception):
wait_until_deleted(lambda rid: source.block_storage.find_volume(rid, ignore_missing=True), volume_id, desc=f"source temp volume {volume_id}")
# ---------------------------------------------------------------------------
# Source temp artifact resume helpers
# ---------------------------------------------------------------------------
def get_or_init_artifact_state(state: dict, source_kind: str, source_id: str, role: str, device_name=None) -> dict:
key = artifact_key(source_kind, source_id)
artifacts = state.setdefault("artifacts", {})
entry = artifacts.get(key)
if not entry:
entry = {
"role": role,
"source_kind": source_kind,
"source_id": source_id,
"device_name": device_name,
"source_temp_image_id": None,
"source_temp_snapshot_id": None,
"source_temp_clone_volume_id": None,
"target_image_id": None,
"target_image_name": None,
"target_volume_id": None,
"target_volume_name": None,
}
artifacts[key] = entry
else:
if device_name and not entry.get("device_name"):
entry["device_name"] = device_name
return entry
def persist(server_name: str, state: dict):
save_state(server_name, state)
def get_source_image_if_reusable(source, image_id: str | None):
if not image_id:
return None
img = source.image.find_image(image_id, ignore_missing=True)
if not img:
return None
status = getattr(img, "status", None)
if status == "active":
return img
if status in SOURCE_IMAGE_WAITABLE:
return wait_for_image_ready(source, image_id, desc=f"source temp image {image_id}")
cleanup_target_image(source, image_id) if False else None # no-op marker
with contextlib.suppress(Exception):
source.image.delete_image(image_id, ignore_missing=True)
return None
def get_source_snapshot_if_reusable(source, snapshot_id: str | None):
if not snapshot_id:
return None
snap = source.block_storage.find_snapshot(snapshot_id, ignore_missing=True)
if not snap:
return None
status = getattr(snap, "status", None)
if status == "available":
return snap
if status in SNAPSHOT_WAITABLE:
return wait_for_status(
lambda rid: source.block_storage.get_snapshot(rid),
snapshot_id,
wanted="available",
fail_states={"error"},
timeout=7200,
interval=10,
desc=f"source snapshot {snapshot_id}",
)
cleanup_source_snapshot(source, snapshot_id)
return None