summaryrefslogtreecommitdiff
path: root/nova/virt/libvirt/driver.py
blob: 03c62b12a57de492388f2840df2c8bd7d7d16368 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
A connection to a hypervisor through libvirt.

Supports KVM, LXC, QEMU, UML, XEN and Parallels.

"""

import collections
from collections import deque
import contextlib
import errno
import functools
import glob
import itertools
import mmap
import operator
import os
import shutil
import tempfile
import time
import uuid

import eventlet
from eventlet import greenthread
from eventlet import tpool
from lxml import etree
from os_brick import encryptors
from os_brick import exception as brick_exception
from os_brick.initiator import connector
from oslo_concurrency import processutils
from oslo_log import log as logging
from oslo_serialization import base64
from oslo_serialization import jsonutils
from oslo_service import loopingcall
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import fileutils
from oslo_utils import importutils
from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import units
import six
from six.moves import range

from nova.api.metadata import base as instance_metadata
from nova.api.metadata import password
from nova import block_device
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import utils as compute_utils
import nova.conf
from nova.console import serial as serial_console
from nova.console import type as ctype
from nova import context as nova_context
from nova import crypto
from nova import exception
from nova.i18n import _
from nova import image
from nova import keymgr
from nova.network import model as network_model
from nova import objects
from nova.objects import diagnostics as diagnostics_obj
from nova.objects import fields
from nova.objects import migrate_data as migrate_data_obj
from nova.pci import manager as pci_manager
from nova.pci import utils as pci_utils
from nova import utils
from nova import version
from nova.virt import block_device as driver_block_device
from nova.virt import configdrive
from nova.virt.disk import api as disk_api
from nova.virt.disk.vfs import guestfs
from nova.virt import driver
from nova.virt import firewall
from nova.virt import hardware
from nova.virt.image import model as imgmodel
from nova.virt import images
from nova.virt.libvirt import blockinfo
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import firewall as libvirt_firewall
from nova.virt.libvirt import guest as libvirt_guest
from nova.virt.libvirt import host
from nova.virt.libvirt import imagebackend
from nova.virt.libvirt import imagecache
from nova.virt.libvirt import instancejobtracker
from nova.virt.libvirt import migration as libvirt_migrate
from nova.virt.libvirt.storage import dmcrypt
from nova.virt.libvirt.storage import lvm
from nova.virt.libvirt.storage import rbd_utils
from nova.virt.libvirt import utils as libvirt_utils
from nova.virt.libvirt import vif as libvirt_vif
from nova.virt.libvirt.volume import mount
from nova.virt.libvirt.volume import remotefs
from nova.virt import netutils
from nova.volume import cinder

libvirt = None

uefi_logged = False

LOG = logging.getLogger(__name__)

CONF = nova.conf.CONF

DEFAULT_FIREWALL_DRIVER = "%s.%s" % (
    libvirt_firewall.__name__,
    libvirt_firewall.IptablesFirewallDriver.__name__)

DEFAULT_UEFI_LOADER_PATH = {
    "x86_64": "/usr/share/OVMF/OVMF_CODE.fd",
    "aarch64": "/usr/share/AAVMF/AAVMF_CODE.fd"
}

MAX_CONSOLE_BYTES = 100 * units.Ki

# The libvirt driver will prefix any disable reason codes with this string.
DISABLE_PREFIX = 'AUTO: '
# Disable reason for the service which was enabled or disabled without reason
DISABLE_REASON_UNDEFINED = None

# Guest config console string
CONSOLE = "console=tty0 console=ttyS0 console=hvc0"

GuestNumaConfig = collections.namedtuple(
    'GuestNumaConfig', ['cpuset', 'cputune', 'numaconfig', 'numatune'])


class InjectionInfo(collections.namedtuple(
        'InjectionInfo', ['network_info', 'files', 'admin_pass'])):
    __slots__ = ()

    def __repr__(self):
        return ('InjectionInfo(network_info=%r, files=%r, '
                'admin_pass=<SANITIZED>)') % (self.network_info, self.files)

libvirt_volume_drivers = [
    'iscsi=nova.virt.libvirt.volume.iscsi.LibvirtISCSIVolumeDriver',
    'iser=nova.virt.libvirt.volume.iser.LibvirtISERVolumeDriver',
    'local=nova.virt.libvirt.volume.volume.LibvirtVolumeDriver',
    'drbd=nova.virt.libvirt.volume.drbd.LibvirtDRBDVolumeDriver',
    'fake=nova.virt.libvirt.volume.volume.LibvirtFakeVolumeDriver',
    'rbd=nova.virt.libvirt.volume.net.LibvirtNetVolumeDriver',
    'sheepdog=nova.virt.libvirt.volume.net.LibvirtNetVolumeDriver',
    'nfs=nova.virt.libvirt.volume.nfs.LibvirtNFSVolumeDriver',
    'smbfs=nova.virt.libvirt.volume.smbfs.LibvirtSMBFSVolumeDriver',
    'aoe=nova.virt.libvirt.volume.aoe.LibvirtAOEVolumeDriver',
    'fibre_channel='
        'nova.virt.libvirt.volume.fibrechannel.'
        'LibvirtFibreChannelVolumeDriver',
    'gpfs=nova.virt.libvirt.volume.gpfs.LibvirtGPFSVolumeDriver',
    'quobyte=nova.virt.libvirt.volume.quobyte.LibvirtQuobyteVolumeDriver',
    'hgst=nova.virt.libvirt.volume.hgst.LibvirtHGSTVolumeDriver',
    'scaleio=nova.virt.libvirt.volume.scaleio.LibvirtScaleIOVolumeDriver',
    'disco=nova.virt.libvirt.volume.disco.LibvirtDISCOVolumeDriver',
    'vzstorage='
        'nova.virt.libvirt.volume.vzstorage.LibvirtVZStorageVolumeDriver',
    'veritas_hyperscale='
        'nova.virt.libvirt.volume.vrtshyperscale.'
        'LibvirtHyperScaleVolumeDriver',
]


def patch_tpool_proxy():
    """eventlet.tpool.Proxy doesn't work with old-style class in __str__()
    or __repr__() calls. See bug #962840 for details.
    We perform a monkey patch to replace those two instance methods.
    """
    def str_method(self):
        return str(self._obj)

    def repr_method(self):
        return repr(self._obj)

    tpool.Proxy.__str__ = str_method
    tpool.Proxy.__repr__ = repr_method


patch_tpool_proxy()

# For information about when MIN_LIBVIRT_VERSION and
# NEXT_MIN_LIBVIRT_VERSION can be changed, consult
#
#   https://wiki.openstack.org/wiki/LibvirtDistroSupportMatrix
#
# Currently this is effectively the min version for i686/x86_64
# + KVM/QEMU, as other architectures/hypervisors require newer
# versions. Over time, this will become a common min version
# for all architectures/hypervisors, as this value rises to
# meet them.
MIN_LIBVIRT_VERSION = (1, 2, 9)
MIN_QEMU_VERSION = (2, 1, 0)
# TODO(berrange): Re-evaluate this at start of each release cycle
# to decide if we want to plan a future min version bump.
# MIN_LIBVIRT_VERSION can be updated to match this after
# NEXT_MIN_LIBVIRT_VERSION  has been at a higher value for
# one cycle
NEXT_MIN_LIBVIRT_VERSION = (1, 3, 1)
NEXT_MIN_QEMU_VERSION = (2, 5, 0)

# When the above version matches/exceeds this version
# delete it & corresponding code using it
# Libvirt version 1.2.17 is required for successful block live migration
# of vm booted from image with attached devices
MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION = (1, 2, 17)
# PowerPC based hosts that support NUMA using libvirt
MIN_LIBVIRT_NUMA_VERSION_PPC = (1, 2, 19)
# Versions of libvirt with known NUMA topology issues
# See bug #1449028
BAD_LIBVIRT_NUMA_VERSIONS = [(1, 2, 9, 2)]
# Versions of libvirt with broken cpu pinning support. This excludes
# versions of libvirt with broken NUMA support since pinning needs
# NUMA
# See bug #1438226
BAD_LIBVIRT_CPU_POLICY_VERSIONS = [(1, 2, 10)]

# Virtuozzo driver support
MIN_VIRTUOZZO_VERSION = (7, 0, 0)
MIN_LIBVIRT_VIRTUOZZO_VERSION = (1, 2, 12)

# Ability to set the user guest password with Qemu
MIN_LIBVIRT_SET_ADMIN_PASSWD = (1, 2, 16)

# Ability to set the user guest password with parallels
MIN_LIBVIRT_PARALLELS_SET_ADMIN_PASSWD = (2, 0, 0)

# s/390 & s/390x architectures with KVM
MIN_LIBVIRT_KVM_S390_VERSION = (1, 2, 13)
MIN_QEMU_S390_VERSION = (2, 3, 0)

# libvirt < 1.3 reported virt_functions capability
# only when VFs are enabled.
# libvirt 1.3 fix f391889f4e942e22b9ef8ecca492de05106ce41e
MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION = (1, 3, 0)

# Use the "logd" backend for handling stdout/stderr from QEMU processes.
MIN_LIBVIRT_VIRTLOGD = (1, 3, 3)
MIN_QEMU_VIRTLOGD = (2, 7, 0)

# ppc64/ppc64le architectures with KVM
# NOTE(rfolco): Same levels for Libvirt/Qemu on Big Endian and Little
# Endian giving the nuance around guest vs host architectures
MIN_LIBVIRT_KVM_PPC64_VERSION = (1, 2, 12)

# Names of the types that do not get compressed during migration
NO_COMPRESSION_TYPES = ('qcow2',)


# number of serial console limit
QEMU_MAX_SERIAL_PORTS = 4
# Qemu supports 4 serial consoles, we remove 1 because of the PTY one defined
ALLOWED_QEMU_SERIAL_PORTS = QEMU_MAX_SERIAL_PORTS - 1

# realtime support
MIN_LIBVIRT_REALTIME_VERSION = (1, 2, 13)

# libvirt postcopy support
MIN_LIBVIRT_POSTCOPY_VERSION = (1, 3, 3)

# qemu postcopy support
MIN_QEMU_POSTCOPY_VERSION = (2, 5, 0)

MIN_LIBVIRT_OTHER_ARCH = {
    fields.Architecture.S390: MIN_LIBVIRT_KVM_S390_VERSION,
    fields.Architecture.S390X: MIN_LIBVIRT_KVM_S390_VERSION,
    fields.Architecture.PPC: MIN_LIBVIRT_KVM_PPC64_VERSION,
    fields.Architecture.PPC64: MIN_LIBVIRT_KVM_PPC64_VERSION,
    fields.Architecture.PPC64LE: MIN_LIBVIRT_KVM_PPC64_VERSION,
}

MIN_QEMU_OTHER_ARCH = {
    fields.Architecture.S390: MIN_QEMU_S390_VERSION,
    fields.Architecture.S390X: MIN_QEMU_S390_VERSION,
}

# perf events support
MIN_LIBVIRT_PERF_VERSION = (2, 0, 0)
LIBVIRT_PERF_EVENT_PREFIX = 'VIR_PERF_PARAM_'

PERF_EVENTS_CPU_FLAG_MAPPING = {'cmt': 'cmt',
                                'mbml': 'mbm_local',
                                'mbmt': 'mbm_total',
                               }

MIN_MIGRATION_SPEED_BW = 1  # 1 MiB/s


class LibvirtDriver(driver.ComputeDriver):
    capabilities = {
        "has_imagecache": True,
        "supports_recreate": True,
        "supports_migrate_to_same_host": False,
        "supports_attach_interface": True,
        "supports_device_tagging": True,
        "supports_tagged_attach_interface": True,
        "supports_tagged_attach_volume": True,
        "supports_extend_volume": True,
    }

    def __init__(self, virtapi, read_only=False):
        super(LibvirtDriver, self).__init__(virtapi)

        global libvirt
        if libvirt is None:
            libvirt = importutils.import_module('libvirt')
            libvirt_migrate.libvirt = libvirt

        self._host = host.Host(self._uri(), read_only,
                               lifecycle_event_handler=self.emit_event,
                               conn_event_handler=self._handle_conn_event)
        self._initiator = None
        self._fc_wwnns = None
        self._fc_wwpns = None
        self._caps = None
        self._supported_perf_events = []
        self.firewall_driver = firewall.load_driver(
            DEFAULT_FIREWALL_DRIVER,
            host=self._host)

        self.vif_driver = libvirt_vif.LibvirtGenericVIFDriver()

        # TODO(mriedem): Long-term we should load up the volume drivers on
        # demand as needed rather than doing this on startup, as there might
        # be unsupported volume drivers in this list based on the underlying
        # platform.
        self.volume_drivers = self._get_volume_drivers()

        self._disk_cachemode = None
        self.image_cache_manager = imagecache.ImageCacheManager()
        self.image_backend = imagebackend.Backend(CONF.use_cow_images)

        self.disk_cachemodes = {}

        self.valid_cachemodes = ["default",
                                 "none",
                                 "writethrough",
                                 "writeback",
                                 "directsync",
                                 "unsafe",
                                ]
        self._conn_supports_start_paused = CONF.libvirt.virt_type in ('kvm',
                                                                      'qemu')

        for mode_str in CONF.libvirt.disk_cachemodes:
            disk_type, sep, cache_mode = mode_str.partition('=')
            if cache_mode not in self.valid_cachemodes:
                LOG.warning('Invalid cachemode %(cache_mode)s specified '
                            'for disk type %(disk_type)s.',
                            {'cache_mode': cache_mode, 'disk_type': disk_type})
                continue
            self.disk_cachemodes[disk_type] = cache_mode

        self._volume_api = cinder.API()
        self._image_api = image.API()

        sysinfo_serial_funcs = {
            'none': lambda: None,
            'hardware': self._get_host_sysinfo_serial_hardware,
            'os': self._get_host_sysinfo_serial_os,
            'auto': self._get_host_sysinfo_serial_auto,
        }

        self._sysinfo_serial_func = sysinfo_serial_funcs.get(
            CONF.libvirt.sysinfo_serial)

        self.job_tracker = instancejobtracker.InstanceJobTracker()
        self._remotefs = remotefs.RemoteFilesystem()

        self._live_migration_flags = self._block_migration_flags = 0
        self.active_migrations = {}

        # Compute reserved hugepages from conf file at the very
        # beginning to ensure any syntax error will be reported and
        # avoid any re-calculation when computing resources.
        self._reserved_hugepages = hardware.numa_get_reserved_huge_pages()

    def _get_volume_drivers(self):
        driver_registry = dict()

        for driver_str in libvirt_volume_drivers:
            driver_type, _sep, driver = driver_str.partition('=')
            driver_class = importutils.import_class(driver)
            try:
                driver_registry[driver_type] = driver_class(self._host)
            except brick_exception.InvalidConnectorProtocol:
                LOG.debug('Unable to load volume driver %s. It is not '
                          'supported on this host.', driver)

        return driver_registry

    @property
    def disk_cachemode(self):
        if self._disk_cachemode is None:
            # We prefer 'none' for consistent performance, host crash
            # safety & migration correctness by avoiding host page cache.
            # Some filesystems don't support O_DIRECT though. For those we
            # fallback to 'writethrough' which gives host crash safety, and
            # is safe for migration provided the filesystem is cache coherent
            # (cluster filesystems typically are, but things like NFS are not).
            self._disk_cachemode = "none"
            if not self._supports_direct_io(CONF.instances_path):
                self._disk_cachemode = "writethrough"
        return self._disk_cachemode

    def _set_cache_mode(self, conf):
        """Set cache mode on LibvirtConfigGuestDisk object."""
        try:
            source_type = conf.source_type
            driver_cache = conf.driver_cache
        except AttributeError:
            return

        cache_mode = self.disk_cachemodes.get(source_type,
                                              driver_cache)
        conf.driver_cache = cache_mode

    def _do_quality_warnings(self):
        """Warn about untested driver configurations.

        This will log a warning message about untested driver or host arch
        configurations to indicate to administrators that the quality is
        unknown. Currently, only qemu or kvm on intel 32- or 64-bit systems
        is tested upstream.
        """
        caps = self._host.get_capabilities()
        hostarch = caps.host.cpu.arch
        if (CONF.libvirt.virt_type not in ('qemu', 'kvm') or
            hostarch not in (fields.Architecture.I686,
                             fields.Architecture.X86_64)):
            LOG.warning('The libvirt driver is not tested on '
                        '%(type)s/%(arch)s by the OpenStack project and '
                        'thus its quality can not be ensured. For more '
                        'information, see: http://docs.openstack.org/'
                        'developer/nova/support-matrix.html',
                        {'type': CONF.libvirt.virt_type, 'arch': hostarch})

    def _handle_conn_event(self, enabled, reason):
        LOG.info("Connection event '%(enabled)d' reason '%(reason)s'",
                 {'enabled': enabled, 'reason': reason})
        self._set_host_enabled(enabled, reason)

    def _version_to_string(self, version):
        return '.'.join([str(x) for x in version])

    def init_host(self, host):
        self._host.initialize()

        self._do_quality_warnings()

        self._parse_migration_flags()

        self._supported_perf_events = self._get_supported_perf_events()

        if (CONF.libvirt.virt_type == 'lxc' and
                not (CONF.libvirt.uid_maps and CONF.libvirt.gid_maps)):
            LOG.warning("Running libvirt-lxc without user namespaces is "
                        "dangerous. Containers spawned by Nova will be run "
                        "as the host's root user. It is highly suggested "
                        "that user namespaces be used in a public or "
                        "multi-tenant environment.")

        # Stop libguestfs using KVM unless we're also configured
        # to use this. This solves problem where people need to
        # stop Nova use of KVM because nested-virt is broken
        if CONF.libvirt.virt_type != "kvm":
            guestfs.force_tcg()

        if not self._host.has_min_version(MIN_LIBVIRT_VERSION):
            raise exception.InternalError(
                _('Nova requires libvirt version %s or greater.') %
                self._version_to_string(MIN_LIBVIRT_VERSION))

        if CONF.libvirt.virt_type in ("qemu", "kvm"):
            if self._host.has_min_version(hv_ver=MIN_QEMU_VERSION):
                # "qemu-img info" calls are version dependent, so we need to
                # store the version in the images module.
                images.QEMU_VERSION = self._host.get_connection().getVersion()
            else:
                raise exception.InternalError(
                    _('Nova requires QEMU version %s or greater.') %
                    self._version_to_string(MIN_QEMU_VERSION))

        if CONF.libvirt.virt_type == 'parallels':
            if not self._host.has_min_version(hv_ver=MIN_VIRTUOZZO_VERSION):
                raise exception.InternalError(
                    _('Nova requires Virtuozzo version %s or greater.') %
                    self._version_to_string(MIN_VIRTUOZZO_VERSION))
            if not self._host.has_min_version(MIN_LIBVIRT_VIRTUOZZO_VERSION):
                raise exception.InternalError(
                    _('Running Nova with parallels virt_type requires '
                      'libvirt version %s') %
                    self._version_to_string(MIN_LIBVIRT_VIRTUOZZO_VERSION))

        # Give the cloud admin a heads up if we are intending to
        # change the MIN_LIBVIRT_VERSION in the next release.
        if not self._host.has_min_version(NEXT_MIN_LIBVIRT_VERSION):
            LOG.warning('Running Nova with a libvirt version less than '
                        '%(version)s is deprecated. The required minimum '
                        'version of libvirt will be raised to %(version)s '
                        'in the next release.',
                        {'version': self._version_to_string(
                            NEXT_MIN_LIBVIRT_VERSION)})
        if (CONF.libvirt.virt_type in ("qemu", "kvm") and
            not self._host.has_min_version(hv_ver=NEXT_MIN_QEMU_VERSION)):
            LOG.warning('Running Nova with a QEMU version less than '
                        '%(version)s is deprecated. The required minimum '
                        'version of QEMU will be raised to %(version)s '
                        'in the next release.',
                        {'version': self._version_to_string(
                            NEXT_MIN_QEMU_VERSION)})

        kvm_arch = fields.Architecture.from_host()
        if (CONF.libvirt.virt_type in ('kvm', 'qemu') and
            kvm_arch in MIN_LIBVIRT_OTHER_ARCH and
                not self._host.has_min_version(
                                        MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch),
                                        MIN_QEMU_OTHER_ARCH.get(kvm_arch))):
            if MIN_QEMU_OTHER_ARCH.get(kvm_arch):
                raise exception.InternalError(
                    _('Running Nova with qemu/kvm virt_type on %(arch)s '
                      'requires libvirt version %(libvirt_ver)s and '
                      'qemu version %(qemu_ver)s, or greater') %
                    {'arch': kvm_arch,
                     'libvirt_ver': self._version_to_string(
                         MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch)),
                     'qemu_ver': self._version_to_string(
                         MIN_QEMU_OTHER_ARCH.get(kvm_arch))})
            # no qemu version in the error message
            raise exception.InternalError(
                _('Running Nova with qemu/kvm virt_type on %(arch)s '
                  'requires libvirt version %(libvirt_ver)s or greater') %
                {'arch': kvm_arch,
                 'libvirt_ver': self._version_to_string(
                     MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch))})

    def _prepare_migration_flags(self):
        migration_flags = 0

        migration_flags |= libvirt.VIR_MIGRATE_LIVE

        # Adding p2p flag only if xen is not in use, because xen does not
        # support p2p migrations
        if CONF.libvirt.virt_type != 'xen':
            migration_flags |= libvirt.VIR_MIGRATE_PEER2PEER

        # Adding VIR_MIGRATE_UNDEFINE_SOURCE because, without it, migrated
        # instance will remain defined on the source host
        migration_flags |= libvirt.VIR_MIGRATE_UNDEFINE_SOURCE

        # Adding VIR_MIGRATE_PERSIST_DEST to persist the VM on the
        # destination host
        migration_flags |= libvirt.VIR_MIGRATE_PERSIST_DEST

        live_migration_flags = block_migration_flags = migration_flags

        # Adding VIR_MIGRATE_NON_SHARED_INC, otherwise all block-migrations
        # will be live-migrations instead
        block_migration_flags |= libvirt.VIR_MIGRATE_NON_SHARED_INC

        return (live_migration_flags, block_migration_flags)

    def _handle_live_migration_tunnelled(self, migration_flags):
        if (CONF.libvirt.live_migration_tunnelled is None or
                CONF.libvirt.live_migration_tunnelled):
            migration_flags |= libvirt.VIR_MIGRATE_TUNNELLED
        return migration_flags

    def _is_post_copy_available(self):
        if self._host.has_min_version(lv_ver=MIN_LIBVIRT_POSTCOPY_VERSION,
                                      hv_ver=MIN_QEMU_POSTCOPY_VERSION):
            return True
        return False

    def _is_virtlogd_available(self):
        return self._host.has_min_version(MIN_LIBVIRT_VIRTLOGD,
                                          MIN_QEMU_VIRTLOGD)

    def _handle_live_migration_post_copy(self, migration_flags):
        if CONF.libvirt.live_migration_permit_post_copy:
            if self._is_post_copy_available():
                migration_flags |= libvirt.VIR_MIGRATE_POSTCOPY
            else:
                LOG.info('The live_migration_permit_post_copy is set '
                         'to True, but it is not supported.')
        return migration_flags

    def _handle_live_migration_auto_converge(self, migration_flags):
        if (self._is_post_copy_available() and
                (migration_flags & libvirt.VIR_MIGRATE_POSTCOPY) != 0):
            LOG.info('The live_migration_permit_post_copy is set to '
                     'True and post copy live migration is available '
                     'so auto-converge will not be in use.')
        elif CONF.libvirt.live_migration_permit_auto_converge:
            migration_flags |= libvirt.VIR_MIGRATE_AUTO_CONVERGE
        return migration_flags

    def _parse_migration_flags(self):
        (live_migration_flags,
            block_migration_flags) = self._prepare_migration_flags()

        live_migration_flags = self._handle_live_migration_tunnelled(
            live_migration_flags)
        block_migration_flags = self._handle_live_migration_tunnelled(
            block_migration_flags)

        live_migration_flags = self._handle_live_migration_post_copy(
            live_migration_flags)
        block_migration_flags = self._handle_live_migration_post_copy(
            block_migration_flags)

        live_migration_flags = self._handle_live_migration_auto_converge(
            live_migration_flags)
        block_migration_flags = self._handle_live_migration_auto_converge(
            block_migration_flags)

        self._live_migration_flags = live_migration_flags
        self._block_migration_flags = block_migration_flags

    # TODO(sahid): This method is targeted for removal when the tests
    # have been updated to avoid its use
    #
    # All libvirt API calls on the libvirt.Connect object should be
    # encapsulated by methods on the nova.virt.libvirt.host.Host
    # object, rather than directly invoking the libvirt APIs. The goal
    # is to avoid a direct dependency on the libvirt API from the
    # driver.py file.
    def _get_connection(self):
        return self._host.get_connection()

    _conn = property(_get_connection)

    @staticmethod
    def _uri():
        if CONF.libvirt.virt_type == 'uml':
            uri = CONF.libvirt.connection_uri or 'uml:///system'
        elif CONF.libvirt.virt_type == 'xen':
            uri = CONF.libvirt.connection_uri or 'xen:///'
        elif CONF.libvirt.virt_type == 'lxc':
            uri = CONF.libvirt.connection_uri or 'lxc:///'
        elif CONF.libvirt.virt_type == 'parallels':
            uri = CONF.libvirt.connection_uri or 'parallels:///system'
        else:
            uri = CONF.libvirt.connection_uri or 'qemu:///system'
        return uri

    @staticmethod
    def _live_migration_uri(dest):
        uris = {
            'kvm': 'qemu+%s://%s/system',
            'qemu': 'qemu+%s://%s/system',
            'xen': 'xenmigr://%s/system',
            'parallels': 'parallels+tcp://%s/system',
        }
        virt_type = CONF.libvirt.virt_type
        # TODO(pkoniszewski): Remove fetching live_migration_uri in Pike
        uri = CONF.libvirt.live_migration_uri
        if uri:
            return uri % dest

        uri = uris.get(virt_type)
        if uri is None:
            raise exception.LiveMigrationURINotAvailable(virt_type=virt_type)

        str_format = (dest,)
        if virt_type in ('kvm', 'qemu'):
            scheme = CONF.libvirt.live_migration_scheme or 'tcp'
            str_format = (scheme, dest)
        return uris.get(virt_type) % str_format

    @staticmethod
    def _migrate_uri(dest):
        uri = None
        # Only QEMU live migrations supports migrate-uri parameter
        virt_type = CONF.libvirt.virt_type
        if virt_type in ('qemu', 'kvm'):
            # QEMU accept two schemes: tcp and rdma.  By default
            # libvirt build the URI using the remote hostname and the
            # tcp schema.
            uri = 'tcp://%s' % dest
        # Because dest might be of type unicode, here we might return value of
        # type unicode as well which is not acceptable by libvirt python
        # binding when Python 2.7 is in use, so let's convert it explicitly
        # back to string. When Python 3.x is in use, libvirt python binding
        # accepts unicode type so it is completely fine to do a no-op str(uri)
        # conversion which will return value of type unicode.
        return uri and str(uri)

    def instance_exists(self, instance):
        """Efficient override of base instance_exists method."""
        try:
            self._host.get_guest(instance)
            return True
        except (exception.InternalError, exception.InstanceNotFound):
            return False

    def estimate_instance_overhead(self, instance_info):
        overhead = super(LibvirtDriver, self).estimate_instance_overhead(
            instance_info)
        if isinstance(instance_info, objects.Flavor):
            # A flavor object is passed during case of migrate
            # TODO(sahid): We do not have any way to retrieve the
            # image meta related to the instance so if the cpu_policy
            # has been set in image_meta we will get an
            # exception. Until we fix it we specifically set the
            # cpu_policy in dedicated in an ImageMeta object so if the
            # emulator threads has been requested nothing is going to
            # fail.
            image_meta = objects.ImageMeta.from_dict({"properties": {
                "hw_cpu_policy": fields.CPUAllocationPolicy.DEDICATED,
            }})
            if (hardware.get_emulator_threads_constraint(
                    instance_info, image_meta)
                == fields.CPUEmulatorThreadsPolicy.ISOLATE):
                overhead['vcpus'] += 1
        else:
            # An instance object is passed during case of spawing or a
            # dict is passed when computing resource for an instance
            numa_topology = hardware.instance_topology_from_instance(
                instance_info)
            if numa_topology and numa_topology.emulator_threads_isolated:
                overhead['vcpus'] += 1
        return overhead

    def list_instances(self):
        names = []
        for guest in self._host.list_guests(only_running=False):
            names.append(guest.name)

        return names

    def list_instance_uuids(self):
        uuids = []
        for guest in self._host.list_guests(only_running=False):
            uuids.append(guest.uuid)

        return uuids

    def plug_vifs(self, instance, network_info):
        """Plug VIFs into networks."""
        for vif in network_info:
            self.vif_driver.plug(instance, vif)

    def _unplug_vifs(self, instance, network_info, ignore_errors):
        """Unplug VIFs from networks."""
        for vif in network_info:
            try:
                self.vif_driver.unplug(instance, vif)
            except exception.NovaException:
                if not ignore_errors:
                    raise

    def unplug_vifs(self, instance, network_info):
        self._unplug_vifs(instance, network_info, False)

    def _teardown_container(self, instance):
        inst_path = libvirt_utils.get_instance_path(instance)
        container_dir = os.path.join(inst_path, 'rootfs')
        rootfs_dev = instance.system_metadata.get('rootfs_device_name')
        LOG.debug('Attempting to teardown container at path %(dir)s with '
                  'root device: %(rootfs_dev)s',
                  {'dir': container_dir, 'rootfs_dev': rootfs_dev},
                  instance=instance)
        disk_api.teardown_container(container_dir, rootfs_dev)

    def _destroy(self, instance, attempt=1):
        try:
            guest = self._host.get_guest(instance)
            if CONF.serial_console.enabled:
                # This method is called for several events: destroy,
                # rebuild, hard-reboot, power-off - For all of these
                # events we want to release the serial ports acquired
                # for the guest before destroying it.
                serials = self._get_serial_ports_from_guest(guest)
                for hostname, port in serials:
                    serial_console.release_port(host=hostname, port=port)
        except exception.InstanceNotFound:
            guest = None

        # If the instance is already terminated, we're still happy
        # Otherwise, destroy it
        old_domid = -1
        if guest is not None:
            try:
                old_domid = guest.id
                guest.poweroff()

            except libvirt.libvirtError as e:
                is_okay = False
                errcode = e.get_error_code()
                if errcode == libvirt.VIR_ERR_NO_DOMAIN:
                    # Domain already gone. This can safely be ignored.
                    is_okay = True
                elif errcode == libvirt.VIR_ERR_OPERATION_INVALID:
                    # If the instance is already shut off, we get this:
                    # Code=55 Error=Requested operation is not valid:
                    # domain is not running

                    state = guest.get_power_state(self._host)
                    if state == power_state.SHUTDOWN:
                        is_okay = True
                elif errcode == libvirt.VIR_ERR_INTERNAL_ERROR:
                    errmsg = e.get_error_message()
                    if (CONF.libvirt.virt_type == 'lxc' and
                        errmsg == 'internal error: '
                                  'Some processes refused to die'):
                        # Some processes in the container didn't die
                        # fast enough for libvirt. The container will
                        # eventually die. For now, move on and let
                        # the wait_for_destroy logic take over.
                        is_okay = True
                elif errcode == libvirt.VIR_ERR_OPERATION_TIMEOUT:
                    LOG.warning("Cannot destroy instance, operation time out",
                                instance=instance)
                    reason = _("operation time out")
                    raise exception.InstancePowerOffFailure(reason=reason)
                elif errcode == libvirt.VIR_ERR_SYSTEM_ERROR:
                    if e.get_int1() == errno.EBUSY:
                        # NOTE(danpb): When libvirt kills a process it sends it
                        # SIGTERM first and waits 10 seconds. If it hasn't gone
                        # it sends SIGKILL and waits another 5 seconds. If it
                        # still hasn't gone then you get this EBUSY error.
                        # Usually when a QEMU process fails to go away upon
                        # SIGKILL it is because it is stuck in an
                        # uninterruptible kernel sleep waiting on I/O from
                        # some non-responsive server.
                        # Given the CPU load of the gate tests though, it is
                        # conceivable that the 15 second timeout is too short,
                        # particularly if the VM running tempest has a high
                        # steal time from the cloud host. ie 15 wallclock
                        # seconds may have passed, but the VM might have only
                        # have a few seconds of scheduled run time.
                        LOG.warning('Error from libvirt during destroy. '
                                    'Code=%(errcode)s Error=%(e)s; '
                                    'attempt %(attempt)d of 3',
                                    {'errcode': errcode, 'e': e,
                                     'attempt': attempt},
                                    instance=instance)
                        with excutils.save_and_reraise_exception() as ctxt:
                            # Try up to 3 times before giving up.
                            if attempt < 3:
                                ctxt.reraise = False
                                self._destroy(instance, attempt + 1)
                                return

                if not is_okay:
                    with excutils.save_and_reraise_exception():
                        LOG.error('Error from libvirt during destroy. '
                                  'Code=%(errcode)s Error=%(e)s',
                                  {'errcode': errcode, 'e': e},
                                  instance=instance)

        def _wait_for_destroy(expected_domid):
            """Called at an interval until the VM is gone."""
            # NOTE(vish): If the instance disappears during the destroy
            #             we ignore it so the cleanup can still be
            #             attempted because we would prefer destroy to
            #             never fail.
            try:
                dom_info = self.get_info(instance)
                state = dom_info.state
                new_domid = dom_info.id
            except exception.InstanceNotFound:
                LOG.debug("During wait destroy, instance disappeared.",
                          instance=instance)
                state = power_state.SHUTDOWN

            if state == power_state.SHUTDOWN:
                LOG.info("Instance destroyed successfully.", instance=instance)
                raise loopingcall.LoopingCallDone()

            # NOTE(wangpan): If the instance was booted again after destroy,
            #                this may be an endless loop, so check the id of
            #                domain here, if it changed and the instance is
            #                still running, we should destroy it again.
            # see https://bugs.launchpad.net/nova/+bug/1111213 for more details
            if new_domid != expected_domid:
                LOG.info("Instance may be started again.", instance=instance)
                kwargs['is_running'] = True
                raise loopingcall.LoopingCallDone()

        kwargs = {'is_running': False}
        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_destroy,
                                                     old_domid)
        timer.start(interval=0.5).wait()
        if kwargs['is_running']:
            LOG.info("Going to destroy instance again.", instance=instance)
            self._destroy(instance)
        else:
            # NOTE(GuanQiang): teardown container to avoid resource leak
            if CONF.libvirt.virt_type == 'lxc':
                self._teardown_container(instance)

    def destroy(self, context, instance, network_info, block_device_info=None,
                destroy_disks=True):
        self._destroy(instance)
        self.cleanup(context, instance, network_info, block_device_info,
                     destroy_disks)

    def _undefine_domain(self, instance):
        try:
            guest = self._host.get_guest(instance)
            try:
                support_uefi = self._has_uefi_support()
                guest.delete_configuration(support_uefi)
            except libvirt.libvirtError as e:
                with excutils.save_and_reraise_exception() as ctxt:
                    errcode = e.get_error_code()
                    if errcode == libvirt.VIR_ERR_NO_DOMAIN:
                        LOG.debug("Called undefine, but domain already gone.",
                                  instance=instance)
                        ctxt.reraise = False
                    else:
                        LOG.error('Error from libvirt during undefine. '
                                  'Code=%(errcode)s Error=%(e)s',
                                  {'errcode': errcode, 'e': e},
                                  instance=instance)
        except exception.InstanceNotFound:
            pass

    def cleanup(self, context, instance, network_info, block_device_info=None,
                destroy_disks=True, migrate_data=None, destroy_vifs=True):
        if destroy_vifs:
            self._unplug_vifs(instance, network_info, True)

        retry = True
        while retry:
            try:
                self.unfilter_instance(instance, network_info)
            except libvirt.libvirtError as e:
                try:
                    state = self.get_info(instance).state
                except exception.InstanceNotFound:
                    state = power_state.SHUTDOWN

                if state != power_state.SHUTDOWN:
                    LOG.warning("Instance may be still running, destroy "
                                "it again.", instance=instance)
                    self._destroy(instance)
                else:
                    retry = False
                    errcode = e.get_error_code()
                    LOG.exception(_('Error from libvirt during unfilter. '
                                    'Code=%(errcode)s Error=%(e)s'),
                                  {'errcode': errcode, 'e': e},
                                  instance=instance)
                    reason = _("Error unfiltering instance.")
                    raise exception.InstanceTerminationFailure(reason=reason)
            except Exception:
                retry = False
                raise
            else:
                retry = False

        # FIXME(wangpan): if the instance is booted again here, such as the
        #                 soft reboot operation boot it here, it will become
        #                 "running deleted", should we check and destroy it
        #                 at the end of this method?

        # NOTE(vish): we disconnect from volumes regardless
        block_device_mapping = driver.block_device_info_get_mapping(
            block_device_info)
        for vol in block_device_mapping:
            connection_info = vol['connection_info']
            disk_dev = vol['mount_device']
            if disk_dev is not None:
                disk_dev = disk_dev.rpartition("/")[2]

            if ('data' in connection_info and
                    'volume_id' in connection_info['data']):
                volume_id = connection_info['data']['volume_id']
                encryption = encryptors.get_encryption_metadata(
                    context, self._volume_api, volume_id, connection_info)

                if encryption:
                    # The volume must be detached from the VM before
                    # disconnecting it from its encryptor. Otherwise, the
                    # encryptor may report that the volume is still in use.
                    encryptor = self._get_volume_encryptor(connection_info,
                                                           encryption)
                    try:
                        encryptor.detach_volume(**encryption)
                    except processutils.ProcessExecutionError as e:
                        if e.exit_code == 4:
                            LOG.debug('Ignoring exit code 4, volume already '
                                      'destroyed')
                        else:
                            with excutils.save_and_reraise_exception():
                                LOG.warning(
                                    'Could not disconnect encrypted volume '
                                    '%(volume)s. If the device is still '
                                    'active, it will have to destroyed '
                                    'manually for cleanup to succeed.',
                                    {'volume': disk_dev})

            try:
                self._disconnect_volume(connection_info, disk_dev, instance)
            except Exception as exc:
                with excutils.save_and_reraise_exception() as ctxt:
                    if destroy_disks:
                        # Don't block on Volume errors if we're trying to
                        # delete the instance as we may be partially created
                        # or deleted
                        ctxt.reraise = False
                        LOG.warning(
                            "Ignoring Volume Error on vol %(vol_id)s "
                            "during delete %(exc)s",
                            {'vol_id': vol.get('volume_id'), 'exc': exc},
                            instance=instance)

        if destroy_disks:
            # NOTE(haomai): destroy volumes if needed
            if CONF.libvirt.images_type == 'lvm':
                self._cleanup_lvm(instance, block_device_info)
            if CONF.libvirt.images_type == 'rbd':
                self._cleanup_rbd(instance)

        is_shared_block_storage = False
        if migrate_data and 'is_shared_block_storage' in migrate_data:
            is_shared_block_storage = migrate_data.is_shared_block_storage
        if destroy_disks or is_shared_block_storage:
            attempts = int(instance.system_metadata.get('clean_attempts',
                                                        '0'))
            success = self.delete_instance_files(instance)
            # NOTE(mriedem): This is used in the _run_pending_deletes periodic
            # task in the compute manager. The tight coupling is not great...
            instance.system_metadata['clean_attempts'] = str(attempts + 1)
            if success:
                instance.cleaned = True
            instance.save()

        self._undefine_domain(instance)

    def _detach_encrypted_volumes(self, instance, block_device_info):
        """Detaches encrypted volumes attached to instance."""
        disks = self._get_instance_disk_info(instance, block_device_info)
        encrypted_volumes = filter(dmcrypt.is_encrypted,
                                   [disk['path'] for disk in disks])
        for path in encrypted_volumes:
            dmcrypt.delete_volume(path)

    def _get_serial_ports_from_guest(self, guest, mode=None):
        """Returns an iterator over serial port(s) configured on guest.

        :param mode: Should be a value in (None, bind, connect)
        """
        xml = guest.get_xml_desc()
        tree = etree.fromstring(xml)

        # The 'serial' device is the base for x86 platforms. Other platforms
        # (e.g. kvm on system z = S390X) can only use 'console' devices.
        xpath_mode = "[@mode='%s']" % mode if mode else ""
        serial_tcp = "./devices/serial[@type='tcp']/source" + xpath_mode
        console_tcp = "./devices/console[@type='tcp']/source" + xpath_mode

        tcp_devices = tree.findall(serial_tcp)
        if len(tcp_devices) == 0:
            tcp_devices = tree.findall(console_tcp)
        for source in tcp_devices:
            yield (source.get("host"), int(source.get("service")))

    def _get_scsi_controller_max_unit(self, guest):
        """Returns the max disk unit used by scsi controller"""
        xml = guest.get_xml_desc()
        tree = etree.fromstring(xml)
        addrs = "./devices/disk[@device='disk']/address[@type='drive']"

        ret = []
        for obj in tree.findall(addrs):
            ret.append(int(obj.get('unit', 0)))
        return max(ret)

    @staticmethod
    def _get_rbd_driver():
        return rbd_utils.RBDDriver(
                pool=CONF.libvirt.images_rbd_pool,
                ceph_conf=CONF.libvirt.images_rbd_ceph_conf,
                rbd_user=CONF.libvirt.rbd_user)

    def _cleanup_rbd(self, instance):
        # NOTE(nic): On revert_resize, the cleanup steps for the root
        # volume are handled with an "rbd snap rollback" command,
        # and none of this is needed (and is, in fact, harmful) so
        # filter out non-ephemerals from the list
        if instance.task_state == task_states.RESIZE_REVERTING:
            filter_fn = lambda disk: (disk.startswith(instance.uuid) and
                                      disk.endswith('disk.local'))
        else:
            filter_fn = lambda disk: disk.startswith(instance.uuid)
        LibvirtDriver._get_rbd_driver().cleanup_volumes(filter_fn)

    def _cleanup_lvm(self, instance, block_device_info):
        """Delete all LVM disks for given instance object."""
        if instance.get('ephemeral_key_uuid') is not None:
            self._detach_encrypted_volumes(instance, block_device_info)

        disks = self._lvm_disks(instance)
        if disks:
            lvm.remove_volumes(disks)

    def _lvm_disks(self, instance):
        """Returns all LVM disks for given instance object."""
        if CONF.libvirt.images_volume_group:
            vg = os.path.join('/dev', CONF.libvirt.images_volume_group)
            if not os.path.exists(vg):
                return []
            pattern = '%s_' % instance.uuid

            def belongs_to_instance(disk):
                return disk.startswith(pattern)

            def fullpath(name):
                return os.path.join(vg, name)

            logical_volumes = lvm.list_volumes(vg)

            disks = [fullpath(disk) for disk in logical_volumes
                     if belongs_to_instance(disk)]
            return disks
        return []

    def get_volume_connector(self, instance):
        root_helper = utils.get_root_helper()
        return connector.get_connector_properties(
            root_helper, CONF.my_block_storage_ip,
            CONF.libvirt.volume_use_multipath,
            enforce_multipath=True,
            host=CONF.host)

    def _cleanup_resize(self, context, instance, network_info):
        inst_base = libvirt_utils.get_instance_path(instance)
        target = inst_base + '_resize'

        if os.path.exists(target):
            # Deletion can fail over NFS, so retry the deletion as required.
            # Set maximum attempt as 5, most test can remove the directory
            # for the second time.
            utils.execute('rm', '-rf', target, delay_on_retry=True,
                          attempts=5)

        # NOTE(mriedem): Some image backends will recreate the instance path
        # and disk.info during init, and all we need the root disk for
        # here is removing cloned snapshots which is backend-specific, so
        # check that first before initializing the image backend object. If
        # there is ever an image type that supports clone *and* re-creates
        # the instance directory and disk.info on init, this condition will
        # need to be re-visited to make sure that backend doesn't re-create
        # the disk. Refer to bugs: 1666831 1728603 1769131
        if self.image_backend.backend(CONF.libvirt.images_type).SUPPORTS_CLONE:
            root_disk = self.image_backend.by_name(instance, 'disk')
            # TODO(nic): Set ignore_errors=False in a future release.
            # It is set to True here to avoid any upgrade issues surrounding
            # instances being in pending resize state when the software is
            # updated; in that case there will be no snapshot to remove.
            # Once it can be reasonably assumed that no such instances exist
            # in the wild anymore, it should be set back to False
            # (the default) so it will throw errors, like it should.
            if root_disk.exists():
                root_disk.remove_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME,
                                      ignore_errors=True)

        if instance.host != CONF.host:
            self._undefine_domain(instance)
            self.unplug_vifs(instance, network_info)
            self.unfilter_instance(instance, network_info)

    def _get_volume_driver(self, connection_info):
        driver_type = connection_info.get('driver_volume_type')
        if driver_type not in self.volume_drivers:
            raise exception.VolumeDriverNotFound(driver_type=driver_type)
        return self.volume_drivers[driver_type]

    def _connect_volume(self, connection_info, disk_info, instance):
        vol_driver = self._get_volume_driver(connection_info)
        vol_driver.connect_volume(connection_info, disk_info, instance)

    def _disconnect_volume(self, connection_info, disk_dev, instance):
        vol_driver = self._get_volume_driver(connection_info)
        vol_driver.disconnect_volume(connection_info, disk_dev, instance)

    def _extend_volume(self, connection_info, instance):
        vol_driver = self._get_volume_driver(connection_info)
        return vol_driver.extend_volume(connection_info, instance)

    def _get_volume_config(self, connection_info, disk_info):
        vol_driver = self._get_volume_driver(connection_info)
        conf = vol_driver.get_config(connection_info, disk_info)
        self._set_cache_mode(conf)
        return conf

    def _get_volume_encryptor(self, connection_info, encryption):
        root_helper = utils.get_root_helper()
        key_manager = keymgr.API(CONF)
        return encryptors.get_volume_encryptor(root_helper=root_helper,
                                               keymgr=key_manager,
                                               connection_info=connection_info,
                                               **encryption)

    def _get_volume_encryption(self, context, connection_info):
        """Get the encryption metadata dict if it is not provided
        """
        encryption = {}
        volume_id = driver_block_device.get_volume_id(connection_info)
        if volume_id:
            encryption = encryptors.get_encryption_metadata(context,
                            self._volume_api, volume_id, connection_info)
        return encryption

    def _check_discard_for_attach_volume(self, conf, instance):
        """Perform some checks for volumes configured for discard support.

        If discard is configured for the volume, and the guest is using a
        configuration known to not work, we will log a message explaining
        the reason why.
        """
        if conf.driver_discard == 'unmap' and conf.target_bus == 'virtio':
            LOG.debug('Attempting to attach volume %(id)s with discard '
                      'support enabled to an instance using an '
                      'unsupported configuration. target_bus = '
                      '%(bus)s. Trim commands will not be issued to '
                      'the storage device.',
                      {'bus': conf.target_bus,
                       'id': conf.serial},
                      instance=instance)

    def attach_volume(self, context, connection_info, instance, mountpoint,
                      disk_bus=None, device_type=None, encryption=None):
        guest = self._host.get_guest(instance)

        disk_dev = mountpoint.rpartition("/")[2]
        bdm = {
            'device_name': disk_dev,
            'disk_bus': disk_bus,
            'device_type': device_type}

        # Note(cfb): If the volume has a custom block size, check that
        #            that we are using QEMU/KVM and libvirt >= 0.10.2. The
        #            presence of a block size is considered mandatory by
        #            cinder so we fail if we can't honor the request.
        data = {}
        if ('data' in connection_info):
            data = connection_info['data']
        if ('logical_block_size' in data or 'physical_block_size' in data):
            if ((CONF.libvirt.virt_type != "kvm" and
                 CONF.libvirt.virt_type != "qemu")):
                msg = _("Volume sets block size, but the current "
                        "libvirt hypervisor '%s' does not support custom "
                        "block size") % CONF.libvirt.virt_type
                raise exception.InvalidHypervisorType(msg)

        disk_info = blockinfo.get_info_from_bdm(
            instance, CONF.libvirt.virt_type, instance.image_meta, bdm)
        self._connect_volume(connection_info, disk_info, instance)
        if disk_info['bus'] == 'scsi':
            disk_info['unit'] = self._get_scsi_controller_max_unit(guest) + 1

        conf = self._get_volume_config(connection_info, disk_info)

        self._check_discard_for_attach_volume(conf, instance)

        try:
            state = guest.get_power_state(self._host)
            live = state in (power_state.RUNNING, power_state.PAUSED)

            if encryption:
                encryptor = self._get_volume_encryptor(connection_info,
                                                       encryption)
                encryptor.attach_volume(context, **encryption)

            guest.attach_device(conf, persistent=True, live=live)
            # NOTE(artom) If we're attaching with a device role tag, we need to
            # rebuild device_metadata. If we're attaching without a role
            # tag, we're rebuilding it here needlessly anyways. This isn't a
            # massive deal, and it helps reduce code complexity by not having
            # to indicate to the virt driver that the attach is tagged. The
            # really important optimization of not calling the database unless
            # device_metadata has actually changed is done for us by
            # instance.save().
            instance.device_metadata = self._build_device_metadata(
                context, instance)
            instance.save()
        except Exception:
            LOG.exception(_('Failed to attach volume at mountpoint: %s'),
                          mountpoint, instance=instance)
            with excutils.save_and_reraise_exception():
                self._disconnect_volume(connection_info, disk_dev, instance)

    def _swap_volume(self, guest, disk_path, conf, resize_to):
        """Swap existing disk with a new block device."""
        dev = guest.get_block_device(disk_path)

        # Save a copy of the domain's persistent XML file. We'll use this
        # to redefine the domain if anything fails during the volume swap.
        xml = guest.get_xml_desc(dump_inactive=True, dump_sensitive=True)

        # Abort is an idempotent operation, so make sure any block
        # jobs which may have failed are ended.
        try:
            dev.abort_job()
        except Exception:
            pass

        try:
            # NOTE (rmk): blockRebase cannot be executed on persistent
            #             domains, so we need to temporarily undefine it.
            #             If any part of this block fails, the domain is
            #             re-defined regardless.
            if guest.has_persistent_configuration():
                support_uefi = self._has_uefi_support()
                guest.delete_configuration(support_uefi)

            try:
                # Start copy with VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT flag to
                # allow writing to existing external volume file. Use
                # VIR_DOMAIN_BLOCK_REBASE_COPY_DEV if it's a block device to
                # make sure XML is generated correctly (bug 1691195)
                copy_dev = conf.source_type == 'block'
                dev.rebase(conf.source_path, copy=True, reuse_ext=True,
                           copy_dev=copy_dev)
                while not dev.is_job_complete():
                    time.sleep(0.5)

                dev.abort_job(pivot=True)

            except Exception as exc:
                LOG.exception("Failure rebasing volume %(new_path)s on "
                    "%(old_path)s.", {'new_path': conf.source_path,
                                      'old_path': disk_path})
                raise exception.VolumeRebaseFailed(reason=six.text_type(exc))

            if resize_to:
                dev.resize(resize_to * units.Gi / units.Ki)

            # Make sure we will redefine the domain using the updated
            # configuration after the volume was swapped. The dump_inactive
            # keyword arg controls whether we pull the inactive (persistent)
            # or active (live) config from the domain. We want to pull the
            # live config after the volume was updated to use when we redefine
            # the domain.
            xml = guest.get_xml_desc(dump_inactive=False, dump_sensitive=True)
        finally:
            self._host.write_instance_config(xml)

    def swap_volume(self, context, old_connection_info,
                    new_connection_info, instance, mountpoint, resize_to):

        # NOTE(lyarwood): Bug #1739593 uncovered a nasty data corruption
        # issue that was fixed in Queens by Ica323b87fa85a454fca9d46ada3677f18.
        # Given the size of the bugfix it was agreed not to backport the change
        # to earlier stable branches and to instead block swap volume attempts.
        if (self._get_volume_encryption(context, old_connection_info) or
            self._get_volume_encryption(context, new_connection_info)):
            raise NotImplementedError(_("Swap volume is not supported when "
                "using encrypted volumes. For more details see "
                "https://bugs.launchpad.net/nova/+bug/1739593."))

        guest = self._host.get_guest(instance)

        disk_dev = mountpoint.rpartition("/")[2]
        if not guest.get_disk(disk_dev):
            raise exception.DiskNotFound(location=disk_dev)
        disk_info = {
            'dev': disk_dev,
            'bus': blockinfo.get_disk_bus_for_disk_dev(
                CONF.libvirt.virt_type, disk_dev),
            'type': 'disk',
            }
        # NOTE (lyarwood): new_connection_info will be modified by the
        # following _connect_volume call down into the volume drivers. The
        # majority of the volume drivers will add a device_path that is in turn
        # used by _get_volume_config to set the source_path of the
        # LibvirtConfigGuestDisk object it returns. We do not explicitly save
        # this to the BDM here as the upper compute swap_volume method will
        # eventually do this for us.
        self._connect_volume(new_connection_info, disk_info, instance)
        conf = self._get_volume_config(new_connection_info, disk_info)
        if not conf.source_path:
            self._disconnect_volume(new_connection_info, disk_dev, instance)
            raise NotImplementedError(_("Swap only supports host devices"))

        try:
            self._swap_volume(guest, disk_dev, conf, resize_to)
        except exception.VolumeRebaseFailed:
            with excutils.save_and_reraise_exception():
                self._disconnect_volume(new_connection_info, disk_dev,
                                        instance)

        self._disconnect_volume(old_connection_info, disk_dev, instance)

    def _get_existing_domain_xml(self, instance, network_info,
                                 block_device_info=None):
        try:
            guest = self._host.get_guest(instance)
            xml = guest.get_xml_desc()
        except exception.InstanceNotFound:
            disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
                                                instance,
                                                instance.image_meta,
                                                block_device_info)
            xml = self._get_guest_xml(nova_context.get_admin_context(),
                                      instance, network_info, disk_info,
                                      instance.image_meta,
                                      block_device_info=block_device_info)
        return xml

    def detach_volume(self, connection_info, instance, mountpoint,
                      encryption=None):
        disk_dev = mountpoint.rpartition("/")[2]
        try:
            guest = self._host.get_guest(instance)

            state = guest.get_power_state(self._host)
            live = state in (power_state.RUNNING, power_state.PAUSED)

            # The volume must be detached from the VM before disconnecting it
            # from its encryptor. Otherwise, the encryptor may report that the
            # volume is still in use.
            wait_for_detach = guest.detach_device_with_retry(guest.get_disk,
                                                             disk_dev,
                                                             live=live)
            wait_for_detach()

        except exception.InstanceNotFound:
            # NOTE(zhaoqin): If the instance does not exist, _lookup_by_name()
            #                will throw InstanceNotFound exception. Need to
            #                disconnect volume under this circumstance.
            LOG.warning("During detach_volume, instance disappeared.",
                        instance=instance)
        except exception.DeviceNotFound:
            # We should still try to disconnect logical device from
            # host, an error might have happened during a previous
            # call.
            LOG.info("Device %s not found in instance.",
                     disk_dev, instance=instance)
        except libvirt.libvirtError as ex:
            # NOTE(vish): This is called to cleanup volumes after live
            #             migration, so we should still disconnect even if
            #             the instance doesn't exist here anymore.
            error_code = ex.get_error_code()
            if error_code == libvirt.VIR_ERR_NO_DOMAIN:
                # NOTE(vish):
                LOG.warning("During detach_volume, instance disappeared.",
                            instance=instance)
            else:
                raise

        try:
            if encryption:
                encryptor = self._get_volume_encryptor(connection_info,
                                                       encryption)
                encryptor.detach_volume(**encryption)
        except processutils.ProcessExecutionError as e:
            # cryptsetup returns 4 when attempting to destroy a non-existent
            # dm-crypt device. We assume here that the caller hasn't specified
            # the wrong device, and that it doesn't exist because it has
            # already been destroyed.
            if e.exit_code == 4:
                LOG.debug("Ignoring exit code 4, volume already destroyed")
            else:
                with excutils.save_and_reraise_exception():
                    LOG.warning("Could not disconnect encrypted volume "
                                "%(volume)s. If dm-crypt device is still "
                                "active it will have to be destroyed manually "
                                "for cleanup to succeed.",
                                {'volume': disk_dev})

        self._disconnect_volume(connection_info, disk_dev, instance)

    def extend_volume(self, connection_info, instance):
        try:
            new_size = self._extend_volume(connection_info, instance)
        except NotImplementedError:
            raise exception.ExtendVolumeNotSupported()

        # Resize the device in QEMU so its size is updated and
        # detected by the instance without rebooting.
        try:
            guest = self._host.get_guest(instance)
            state = guest.get_power_state(self._host)
            active_state = state in (power_state.RUNNING, power_state.PAUSED)
            if active_state:
                disk_path = connection_info['data']['device_path']
                LOG.debug('resizing block device %(dev)s to %(size)u kb',
                          {'dev': disk_path, 'size': new_size})
                dev = guest.get_block_device(disk_path)
                dev.resize(new_size // units.Ki)
            else:
                LOG.debug('Skipping block device resize, guest is not running',
                          instance=instance)
        except exception.InstanceNotFound:
            with excutils.save_and_reraise_exception():
                LOG.warning('During extend_volume, instance disappeared.',
                            instance=instance)
        except libvirt.libvirtError:
            with excutils.save_and_reraise_exception():
                LOG.exception('resizing block device failed.',
                              instance=instance)

    def attach_interface(self, context, instance, image_meta, vif):
        guest = self._host.get_guest(instance)

        self.vif_driver.plug(instance, vif)
        self.firewall_driver.setup_basic_filtering(instance, [vif])
        cfg = self.vif_driver.get_config(instance, vif, image_meta,
                                         instance.flavor,
                                         CONF.libvirt.virt_type,
                                         self._host)
        try:
            state = guest.get_power_state(self._host)
            live = state in (power_state.RUNNING, power_state.PAUSED)
            guest.attach_device(cfg, persistent=True, live=live)
        except libvirt.libvirtError:
            LOG.error('attaching network adapter failed.',
                      instance=instance, exc_info=True)
            self.vif_driver.unplug(instance, vif)
            raise exception.InterfaceAttachFailed(
                    instance_uuid=instance.uuid)
        try:
            # NOTE(artom) If we're attaching with a device role tag, we need to
            # rebuild device_metadata. If we're attaching without a role
            # tag, we're rebuilding it here needlessly anyways. This isn't a
            # massive deal, and it helps reduce code complexity by not having
            # to indicate to the virt driver that the attach is tagged. The
            # really important optimization of not calling the database unless
            # device_metadata has actually changed is done for us by
            # instance.save().
            instance.device_metadata = self._build_device_metadata(
                context, instance)
            instance.save()
        except Exception:
            # NOTE(artom) If we fail here it means the interface attached
            # successfully but building and/or saving the device metadata
            # failed. Just unplugging the vif is therefore not enough cleanup,
            # we need to detach the interface.
            with excutils.save_and_reraise_exception(reraise=False):
                LOG.error('Interface attached successfully but building '
                          'and/or saving device metadata failed.',
                          instance=instance, exc_info=True)
                self.detach_interface(context, instance, vif)
                raise exception.InterfaceAttachFailed(
                    instance_uuid=instance.uuid)

    def detach_interface(self, context, instance, vif):
        guest = self._host.get_guest(instance)
        cfg = self.vif_driver.get_config(instance, vif,
                                         instance.image_meta,
                                         instance.flavor,
                                         CONF.libvirt.virt_type, self._host)
        interface = guest.get_interface_by_cfg(cfg)
        try:
            self.vif_driver.unplug(instance, vif)
            # NOTE(mriedem): When deleting an instance and using Neutron,
            # we can be racing against Neutron deleting the port and
            # sending the vif-deleted event which then triggers a call to
            # detach the interface, so if the interface is not found then
            # we can just log it as a warning.
            if not interface:
                mac = vif.get('address')
                # The interface is gone so just log it as a warning.
                LOG.warning('Detaching interface %(mac)s failed because '
                            'the device is no longer found on the guest.',
                            {'mac': mac}, instance=instance)
                return

            state = guest.get_power_state(self._host)
            live = state in (power_state.RUNNING, power_state.PAUSED)
            # Now we are going to loop until the interface is detached or we
            # timeout.
            wait_for_detach = guest.detach_device_with_retry(
                guest.get_interface_by_cfg, cfg, live=live,
                alternative_device_name=self.vif_driver.get_vif_devname(vif))
            wait_for_detach()
        except exception.DeviceDetachFailed:
            # We failed to detach the device even with the retry loop, so let's
            # dump some debug information to the logs before raising back up.
            with excutils.save_and_reraise_exception():
                devname = self.vif_driver.get_vif_devname(vif)
                interface = guest.get_interface_by_cfg(cfg)
                if interface:
                    LOG.warning(
                        'Failed to detach interface %(devname)s after '
                        'repeated attempts. Final interface xml:\n'
                        '%(interface_xml)s\nFinal guest xml:\n%(guest_xml)s',
                        {'devname': devname,
                         'interface_xml': interface.to_xml(),
                         'guest_xml': guest.get_xml_desc()},
                        instance=instance)
        except exception.DeviceNotFound:
            # The interface is gone so just log it as a warning.
            LOG.warning('Detaching interface %(mac)s failed because '
                        'the device is no longer found on the guest.',
                        {'mac': vif.get('address')}, instance=instance)
        except libvirt.libvirtError as ex:
            error_code = ex.get_error_code()
            if error_code == libvirt.VIR_ERR_NO_DOMAIN:
                LOG.warning("During detach_interface, instance disappeared.",
                            instance=instance)
            else:
                # NOTE(mriedem): When deleting an instance and using Neutron,
                # we can be racing against Neutron deleting the port and
                # sending the vif-deleted event which then triggers a call to
                # detach the interface, so we might have failed because the
                # network device no longer exists. Libvirt will fail with
                # "operation failed: no matching network device was found"
                # which unfortunately does not have a unique error code so we
                # need to look up the interface by config and if it's not found
                # then we can just log it as a warning rather than tracing an
                # error.
                mac = vif.get('address')
                interface = guest.get_interface_by_cfg(cfg)
                if interface:
                    LOG.error('detaching network adapter failed.',
                              instance=instance, exc_info=True)
                    raise exception.InterfaceDetachFailed(
                            instance_uuid=instance.uuid)

                # The interface is gone so just log it as a warning.
                LOG.warning('Detaching interface %(mac)s failed because '
                            'the device is no longer found on the guest.',
                            {'mac': mac}, instance=instance)

    def _create_snapshot_metadata(self, image_meta, instance,
                                  img_fmt, snp_name):
        metadata = {'is_public': False,
                    'status': 'active',
                    'name': snp_name,
                    'properties': {
                                   'kernel_id': instance.kernel_id,
                                   'image_location': 'snapshot',
                                   'image_state': 'available',
                                   'owner_id': instance.project_id,
                                   'ramdisk_id': instance.ramdisk_id,
                                   }
                    }
        if instance.os_type:
            metadata['properties']['os_type'] = instance.os_type

        # NOTE(vish): glance forces ami disk format to be ami
        if image_meta.disk_format == 'ami':
            metadata['disk_format'] = 'ami'
        else:
            metadata['disk_format'] = img_fmt

        if image_meta.obj_attr_is_set("container_format"):
            metadata['container_format'] = image_meta.container_format
        else:
            metadata['container_format'] = "bare"

        return metadata

    def snapshot(self, context, instance, image_id, update_task_state):
        """Create snapshot from a running VM instance.

        This command only works with qemu 0.14+
        """
        try:
            guest = self._host.get_guest(instance)

            # TODO(sahid): We are converting all calls from a
            # virDomain object to use nova.virt.libvirt.Guest.
            # We should be able to remove virt_dom at the end.
            virt_dom = guest._domain
        except exception.InstanceNotFound:
            raise exception.InstanceNotRunning(instance_id=instance.uuid)

        snapshot = self._image_api.get(context, image_id)

        # source_format is an on-disk format
        # source_type is a backend type
        disk_path, source_format = libvirt_utils.find_disk(guest)
        source_type = libvirt_utils.get_disk_type_from_path(disk_path)

        # We won't have source_type for raw or qcow2 disks, because we can't
        # determine that from the path. We should have it from the libvirt
        # xml, though.
        if source_type is None:
            source_type = source_format
        # For lxc instances we won't have it either from libvirt xml
        # (because we just gave libvirt the mounted filesystem), or the path,
        # so source_type is still going to be None. In this case,
        # root_disk is going to default to CONF.libvirt.images_type
        # below, which is still safe.

        image_format = CONF.libvirt.snapshot_image_format or source_type

        # NOTE(bfilippov): save lvm and rbd as raw
        if image_format == 'lvm' or image_format == 'rbd':
            image_format = 'raw'

        metadata = self._create_snapshot_metadata(instance.image_meta,
                                                  instance,
                                                  image_format,
                                                  snapshot['name'])

        snapshot_name = uuid.uuid4().hex

        state = guest.get_power_state(self._host)

        # NOTE(dgenin): Instances with LVM encrypted ephemeral storage require
        #               cold snapshots. Currently, checking for encryption is
        #               redundant because LVM supports only cold snapshots.
        #               It is necessary in case this situation changes in the
        #               future.
        if (self._host.has_min_version(hv_type=host.HV_DRIVER_QEMU)
             and source_type not in ('lvm')
             and not CONF.ephemeral_storage_encryption.enabled
             and not CONF.workarounds.disable_libvirt_livesnapshot):
            live_snapshot = True
            # Abort is an idempotent operation, so make sure any block
            # jobs which may have failed are ended. This operation also
            # confirms the running instance, as opposed to the system as a
            # whole, has a new enough version of the hypervisor (bug 1193146).
            try:
                guest.get_block_device(disk_path).abort_job()
            except libvirt.libvirtError as ex:
                error_code = ex.get_error_code()
                if error_code == libvirt.VIR_ERR_CONFIG_UNSUPPORTED:
                    live_snapshot = False
                else:
                    pass
        else:
            live_snapshot = False

        # NOTE(rmk): We cannot perform live snapshots when a managedSave
        #            file is present, so we will use the cold/legacy method
        #            for instances which are shutdown.
        if state == power_state.SHUTDOWN:
            live_snapshot = False

        self._prepare_domain_for_snapshot(context, live_snapshot, state,
                                          instance)

        root_disk = self.image_backend.by_libvirt_path(
            instance, disk_path, image_type=source_type)

        if live_snapshot:
            LOG.info("Beginning live snapshot process", instance=instance)
        else:
            LOG.info("Beginning cold snapshot process", instance=instance)

        update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD)

        try:
            update_task_state(task_state=task_states.IMAGE_UPLOADING,
                              expected_state=task_states.IMAGE_PENDING_UPLOAD)
            metadata['location'] = root_disk.direct_snapshot(
                context, snapshot_name, image_format, image_id,
                instance.image_ref)
            self._snapshot_domain(context, live_snapshot, virt_dom, state,
                                  instance)
            self._image_api.update(context, image_id, metadata,
                                   purge_props=False)
        except (NotImplementedError, exception.ImageUnacceptable,
                exception.Forbidden) as e:
            if type(e) != NotImplementedError:
                LOG.warning('Performing standard snapshot because direct '
                            'snapshot failed: %(error)s', {'error': e})
            failed_snap = metadata.pop('location', None)
            if failed_snap:
                failed_snap = {'url': str(failed_snap)}
            root_disk.cleanup_direct_snapshot(failed_snap,
                                                  also_destroy_volume=True,
                                                  ignore_errors=True)
            update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD,
                              expected_state=task_states.IMAGE_UPLOADING)

            # TODO(nic): possibly abstract this out to the root_disk
            if source_type == 'rbd' and live_snapshot:
                # Standard snapshot uses qemu-img convert from RBD which is
                # not safe to run with live_snapshot.
                live_snapshot = False
                # Suspend the guest, so this is no longer a live snapshot
                self._prepare_domain_for_snapshot(context, live_snapshot,
                                                  state, instance)

            snapshot_directory = CONF.libvirt.snapshots_directory
            fileutils.ensure_tree(snapshot_directory)
            with utils.tempdir(dir=snapshot_directory) as tmpdir:
                try:
                    out_path = os.path.join(tmpdir, snapshot_name)
                    if live_snapshot:
                        # NOTE(xqueralt): libvirt needs o+x in the tempdir
                        os.chmod(tmpdir, 0o701)
                        self._live_snapshot(context, instance, guest,
                                            disk_path, out_path, source_format,
                                            image_format, instance.image_meta)
                    else:
                        root_disk.snapshot_extract(out_path, image_format)
                finally:
                    self._snapshot_domain(context, live_snapshot, virt_dom,
                                          state, instance)
                    LOG.info("Snapshot extracted, beginning image upload",
                             instance=instance)

                # Upload that image to the image service
                update_task_state(task_state=task_states.IMAGE_UPLOADING,
                        expected_state=task_states.IMAGE_PENDING_UPLOAD)
                with libvirt_utils.file_open(out_path, 'rb') as image_file:
                    self._image_api.update(context,
                                           image_id,
                                           metadata,
                                           image_file)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception(_("Failed to snapshot image"))
                failed_snap = metadata.pop('location', None)
                if failed_snap:
                    failed_snap = {'url': str(failed_snap)}
                root_disk.cleanup_direct_snapshot(
                        failed_snap, also_destroy_volume=True,
                        ignore_errors=True)

        LOG.info("Snapshot image upload complete", instance=instance)

    def _prepare_domain_for_snapshot(self, context, live_snapshot, state,
                                     instance):
        # NOTE(dkang): managedSave does not work for LXC
        if CONF.libvirt.virt_type != 'lxc' and not live_snapshot:
            if state == power_state.RUNNING or state == power_state.PAUSED:
                self.suspend(context, instance)

    def _snapshot_domain(self, context, live_snapshot, virt_dom, state,
                         instance):
        guest = None
        # NOTE(dkang): because previous managedSave is not called
        #              for LXC, _create_domain must not be called.
        if CONF.libvirt.virt_type != 'lxc' and not live_snapshot:
            if state == power_state.RUNNING:
                guest = self._create_domain(domain=virt_dom)
            elif state == power_state.PAUSED:
                guest = self._create_domain(domain=virt_dom, pause=True)

            if guest is not None:
                self._attach_pci_devices(
                    guest, pci_manager.get_instance_pci_devs(instance))
                self._attach_direct_passthrough_ports(
                    context, instance, guest)

    def _can_set_admin_password(self, image_meta):

        if CONF.libvirt.virt_type == 'parallels':
            if not self._host.has_min_version(
                   MIN_LIBVIRT_PARALLELS_SET_ADMIN_PASSWD):
                raise exception.SetAdminPasswdNotSupported()
        elif CONF.libvirt.virt_type in ('kvm', 'qemu'):
            if not self._host.has_min_version(
                   MIN_LIBVIRT_SET_ADMIN_PASSWD):
                raise exception.SetAdminPasswdNotSupported()
            if not image_meta.properties.get('hw_qemu_guest_agent', False):
                raise exception.QemuGuestAgentNotEnabled()
        else:
            raise exception.SetAdminPasswdNotSupported()

    # TODO(melwitt): Combine this with the similar xenapi code at some point.
    def _save_instance_password_if_sshkey_present(self, instance, new_pass):
        sshkey = instance.key_data if 'key_data' in instance else None
        if sshkey and sshkey.startswith("ssh-rsa"):
            enc = crypto.ssh_encrypt_text(sshkey, new_pass)
            # NOTE(melwitt): The convert_password method doesn't actually do
            # anything with the context argument, so we can pass None.
            instance.system_metadata.update(
                password.convert_password(None, base64.encode_as_text(enc)))
            instance.save()

    def set_admin_password(self, instance, new_pass):
        self._can_set_admin_password(instance.image_meta)

        guest = self._host.get_guest(instance)
        user = instance.image_meta.properties.get("os_admin_user")
        if not user:
            if instance.os_type == "windows":
                user = "Administrator"
            else:
                user = "root"
        try:
            guest.set_user_password(user, new_pass)
        except libvirt.libvirtError as ex:
            error_code = ex.get_error_code()
            err_msg = encodeutils.exception_to_unicode(ex)
            msg = (_('Error from libvirt while set password for username '
                     '"%(user)s": [Error Code %(error_code)s] %(ex)s')
                   % {'user': user, 'error_code': error_code, 'ex': err_msg})
            raise exception.InternalError(msg)
        else:
            # Save the password in sysmeta so it may be retrieved from the
            # metadata service.
            self._save_instance_password_if_sshkey_present(instance, new_pass)

    def _can_quiesce(self, instance, image_meta):
        if CONF.libvirt.virt_type not in ('kvm', 'qemu'):
            raise exception.InstanceQuiesceNotSupported(
                instance_id=instance.uuid)

        if not image_meta.properties.get('hw_qemu_guest_agent', False):
            raise exception.QemuGuestAgentNotEnabled()

    def _requires_quiesce(self, image_meta):
        return image_meta.properties.get('os_require_quiesce', False)

    def _set_quiesced(self, context, instance, image_meta, quiesced):
        self._can_quiesce(instance, image_meta)
        try:
            guest = self._host.get_guest(instance)
            if quiesced:
                guest.freeze_filesystems()
            else:
                guest.thaw_filesystems()
        except libvirt.libvirtError as ex:
            error_code = ex.get_error_code()
            err_msg = encodeutils.exception_to_unicode(ex)
            msg = (_('Error from libvirt while quiescing %(instance_name)s: '
                     '[Error Code %(error_code)s] %(ex)s')
                   % {'instance_name': instance.name,
                      'error_code': error_code, 'ex': err_msg})
            raise exception.InternalError(msg)

    def quiesce(self, context, instance, image_meta):
        """Freeze the guest filesystems to prepare for snapshot.

        The qemu-guest-agent must be setup to execute fsfreeze.
        """
        self._set_quiesced(context, instance, image_meta, True)

    def unquiesce(self, context, instance, image_meta):
        """Thaw the guest filesystems after snapshot."""
        self._set_quiesced(context, instance, image_meta, False)

    def _live_snapshot(self, context, instance, guest, disk_path, out_path,
                       source_format, image_format, image_meta):
        """Snapshot an instance without downtime."""
        dev = guest.get_block_device(disk_path)

        # Save a copy of the domain's persistent XML file
        xml = guest.get_xml_desc(dump_inactive=True, dump_sensitive=True)

        # Abort is an idempotent operation, so make sure any block
        # jobs which may have failed are ended.
        try:
            dev.abort_job()
        except Exception:
            pass

        # NOTE (rmk): We are using shallow rebases as a workaround to a bug
        #             in QEMU 1.3. In order to do this, we need to create
        #             a destination image with the original backing file
        #             and matching size of the instance root disk.
        src_disk_size = libvirt_utils.get_disk_size(disk_path,
                                                    format=source_format)
        src_back_path = libvirt_utils.get_disk_backing_file(disk_path,
                                                        format=source_format,
                                                        basename=False)
        disk_delta = out_path + '.delta'
        libvirt_utils.create_cow_image(src_back_path, disk_delta,
                                       src_disk_size)

        quiesced = False
        try:
            self._set_quiesced(context, instance, image_meta, True)
            quiesced = True
        except exception.NovaException as err:
            if self._requires_quiesce(image_meta):
                raise
            LOG.info('Skipping quiescing instance: %(reason)s.',
                     {'reason': err}, instance=instance)

        try:
            # NOTE (rmk): blockRebase cannot be executed on persistent
            #             domains, so we need to temporarily undefine it.
            #             If any part of this block fails, the domain is
            #             re-defined regardless.
            if guest.has_persistent_configuration():
                support_uefi = self._has_uefi_support()
                guest.delete_configuration(support_uefi)

            # NOTE (rmk): Establish a temporary mirror of our root disk and
            #             issue an abort once we have a complete copy.
            dev.rebase(disk_delta, copy=True, reuse_ext=True, shallow=True)

            while not dev.is_job_complete():
                time.sleep(0.5)

            dev.abort_job()
            libvirt_utils.chown(disk_delta, os.getuid())
        finally:
            self._host.write_instance_config(xml)
            if quiesced:
                self._set_quiesced(context, instance, image_meta, False)

        # Convert the delta (CoW) image with a backing file to a flat
        # image with no backing file.
        libvirt_utils.extract_snapshot(disk_delta, 'qcow2',
                                       out_path, image_format)

    def _volume_snapshot_update_status(self, context, snapshot_id, status):
        """Send a snapshot status update to Cinder.

        This method captures and logs exceptions that occur
        since callers cannot do anything useful with these exceptions.

        Operations on the Cinder side waiting for this will time out if
        a failure occurs sending the update.

        :param context: security context
        :param snapshot_id: id of snapshot being updated
        :param status: new status value

        """

        try:
            self._volume_api.update_snapshot_status(context,
                                                    snapshot_id,
                                                    status)
        except Exception:
            LOG.exception(_('Failed to send updated snapshot status '
                            'to volume service.'))

    def _volume_snapshot_create(self, context, instance, guest,
                                volume_id, new_file):
        """Perform volume snapshot.

           :param guest: VM that volume is attached to
           :param volume_id: volume UUID to snapshot
           :param new_file: relative path to new qcow2 file present on share

        """
        xml = guest.get_xml_desc()
        xml_doc = etree.fromstring(xml)

        device_info = vconfig.LibvirtConfigGuest()
        device_info.parse_dom(xml_doc)

        disks_to_snap = []          # to be snapshotted by libvirt
        network_disks_to_snap = []  # network disks (netfs, etc.)
        disks_to_skip = []          # local disks not snapshotted

        for guest_disk in device_info.devices:
            if (guest_disk.root_name != 'disk'):
                continue

            if (guest_disk.target_dev is None):
                continue

            if (guest_disk.serial is None or guest_disk.serial != volume_id):
                disks_to_skip.append(guest_disk.target_dev)
                continue

            # disk is a Cinder volume with the correct volume_id

            disk_info = {
                'dev': guest_disk.target_dev,
                'serial': guest_disk.serial,
                'current_file': guest_disk.source_path,
                'source_protocol': guest_disk.source_protocol,
                'source_name': guest_disk.source_name,
                'source_hosts': guest_disk.source_hosts,
                'source_ports': guest_disk.source_ports
            }

            # Determine path for new_file based on current path
            if disk_info['current_file'] is not None:
                current_file = disk_info['current_file']
                new_file_path = os.path.join(os.path.dirname(current_file),
                                             new_file)
                disks_to_snap.append((current_file, new_file_path))
            # NOTE(mriedem): This used to include a check for gluster in
            # addition to netfs since they were added together. Support for
            # gluster was removed in the 16.0.0 Pike release. It is unclear,
            # however, if other volume drivers rely on the netfs disk source
            # protocol.
            elif disk_info['source_protocol'] == 'netfs':
                network_disks_to_snap.append((disk_info, new_file))

        if not disks_to_snap and not network_disks_to_snap:
            msg = _('Found no disk to snapshot.')
            raise exception.InternalError(msg)

        snapshot = vconfig.LibvirtConfigGuestSnapshot()

        for current_name, new_filename in disks_to_snap:
            snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk()
            snap_disk.name = current_name
            snap_disk.source_path = new_filename
            snap_disk.source_type = 'file'
            snap_disk.snapshot = 'external'
            snap_disk.driver_name = 'qcow2'

            snapshot.add_disk(snap_disk)

        for disk_info, new_filename in network_disks_to_snap:
            snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk()
            snap_disk.name = disk_info['dev']
            snap_disk.source_type = 'network'
            snap_disk.source_protocol = disk_info['source_protocol']
            snap_disk.snapshot = 'external'
            snap_disk.source_path = new_filename
            old_dir = disk_info['source_name'].split('/')[0]
            snap_disk.source_name = '%s/%s' % (old_dir, new_filename)
            snap_disk.source_hosts = disk_info['source_hosts']
            snap_disk.source_ports = disk_info['source_ports']

            snapshot.add_disk(snap_disk)

        for dev in disks_to_skip:
            snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk()
            snap_disk.name = dev
            snap_disk.snapshot = 'no'

            snapshot.add_disk(snap_disk)

        snapshot_xml = snapshot.to_xml()
        LOG.debug("snap xml: %s", snapshot_xml, instance=instance)

        image_meta = instance.image_meta
        try:
            # Check to see if we can quiesce the guest before taking the
            # snapshot.
            self._can_quiesce(instance, image_meta)
            try:
                guest.snapshot(snapshot, no_metadata=True, disk_only=True,
                               reuse_ext=True, quiesce=True)
                return
            except libvirt.libvirtError:
                # If the image says that quiesce is required then we fail.
                if self._requires_quiesce(image_meta):
                    raise
                LOG.exception(_('Unable to create quiesced VM snapshot, '
                                'attempting again with quiescing disabled.'),
                              instance=instance)
        except (exception.InstanceQuiesceNotSupported,
                exception.QemuGuestAgentNotEnabled) as err:
            # If the image says that quiesce is required then we need to fail.
            if self._requires_quiesce(image_meta):
                raise
            LOG.info('Skipping quiescing instance: %(reason)s.',
                     {'reason': err}, instance=instance)

        try:
            guest.snapshot(snapshot, no_metadata=True, disk_only=True,
                           reuse_ext=True, quiesce=False)
        except libvirt.libvirtError:
            LOG.exception(_('Unable to create VM snapshot, '
                            'failing volume_snapshot operation.'),
                          instance=instance)

            raise

    def _volume_refresh_connection_info(self, context, instance, volume_id):
        bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
                  context, volume_id, instance.uuid)

        driver_bdm = driver_block_device.convert_volume(bdm)
        if driver_bdm:
            driver_bdm.refresh_connection_info(context, instance,
                                               self._volume_api, self)

    def volume_snapshot_create(self, context, instance, volume_id,
                               create_info):
        """Create snapshots of a Cinder volume via libvirt.

        :param instance: VM instance object reference
        :param volume_id: id of volume being snapshotted
        :param create_info: dict of information used to create snapshots
                     - snapshot_id : ID of snapshot
                     - type : qcow2 / <other>
                     - new_file : qcow2 file created by Cinder which
                     becomes the VM's active image after
                     the snapshot is complete
        """

        LOG.debug("volume_snapshot_create: create_info: %(c_info)s",
                  {'c_info': create_info}, instance=instance)

        try:
            guest = self._host.get_guest(instance)
        except exception.InstanceNotFound:
            raise exception.InstanceNotRunning(instance_id=instance.uuid)

        if create_info['type'] != 'qcow2':
            msg = _('Unknown type: %s') % create_info['type']
            raise exception.InternalError(msg)

        snapshot_id = create_info.get('snapshot_id', None)
        if snapshot_id is None:
            msg = _('snapshot_id required in create_info')
            raise exception.InternalError(msg)

        try:
            self._volume_snapshot_create(context, instance, guest,
                                         volume_id, create_info['new_file'])
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception(_('Error occurred during '
                                'volume_snapshot_create, '
                                'sending error status to Cinder.'),
                              instance=instance)
                self._volume_snapshot_update_status(
                    context, snapshot_id, 'error')

        self._volume_snapshot_update_status(
            context, snapshot_id, 'creating')

        def _wait_for_snapshot():
            snapshot = self._volume_api.get_snapshot(context, snapshot_id)

            if snapshot.get('status') != 'creating':
                self._volume_refresh_connection_info(context, instance,
                                                     volume_id)
                raise loopingcall.LoopingCallDone()

        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_snapshot)
        timer.start(interval=0.5).wait()

    @staticmethod
    def _rebase_with_qemu_img(guest, device, active_disk_object,
                              rebase_base):
        """Rebase a device tied to a guest using qemu-img.

        :param guest:the Guest which owns the device being rebased
        :type guest: nova.virt.libvirt.guest.Guest
        :param device: the guest block device to rebase
        :type device: nova.virt.libvirt.guest.BlockDevice
        :param active_disk_object: the guest block device to rebase
        :type active_disk_object: nova.virt.libvirt.config.\
                                    LibvirtConfigGuestDisk
        :param rebase_base: the new parent in the backing chain
        :type rebase_base: None or string
        """

        # It's unsure how well qemu-img handles network disks for
        # every protocol. So let's be safe.
        active_protocol = active_disk_object.source_protocol
        if active_protocol is not None:
            msg = _("Something went wrong when deleting a volume snapshot: "
                    "rebasing a %(protocol)s network disk using qemu-img "
                    "has not been fully tested") % {'protocol':
                    active_protocol}
            LOG.error(msg)
            raise exception.InternalError(msg)

        if rebase_base is None:
            # If backing_file is specified as "" (the empty string), then
            # the image is rebased onto no backing file (i.e. it will exist
            # independently of any backing file).
            backing_file = ""
            qemu_img_extra_arg = []
        else:
            # If the rebased image is going to have a backing file then
            # explicitly set the backing file format to avoid any security
            # concerns related to file format auto detection.
            backing_file = rebase_base
            b_file_fmt = images.qemu_img_info(backing_file).file_format
            qemu_img_extra_arg = ['-F', b_file_fmt]

        qemu_img_extra_arg.append(active_disk_object.source_path)
        utils.execute("qemu-img", "rebase", "-b", backing_file,
                      *qemu_img_extra_arg)

    def _volume_snapshot_delete(self, context, instance, volume_id,
                                snapshot_id, delete_info=None):
        """Note:
            if file being merged into == active image:
                do a blockRebase (pull) operation
            else:
                do a blockCommit operation
            Files must be adjacent in snap chain.

        :param instance: instance object reference
        :param volume_id: volume UUID
        :param snapshot_id: snapshot UUID (unused currently)
        :param delete_info: {
            'type':              'qcow2',
            'file_to_merge':     'a.img',
            'merge_target_file': 'b.img' or None (if merging file_to_merge into
                                                  active image)
          }
        """

        LOG.debug('volume_snapshot_delete: delete_info: %s', delete_info,
                  instance=instance)

        if delete_info['type'] != 'qcow2':
            msg = _('Unknown delete_info type %s') % delete_info['type']
            raise exception.InternalError(msg)

        try:
            guest = self._host.get_guest(instance)
        except exception.InstanceNotFound:
            raise exception.InstanceNotRunning(instance_id=instance.uuid)

        # Find dev name
        my_dev = None
        active_disk = None

        xml = guest.get_xml_desc()
        xml_doc = etree.fromstring(xml)

        device_info = vconfig.LibvirtConfigGuest()
        device_info.parse_dom(xml_doc)

        active_disk_object = None

        for guest_disk in device_info.devices:
            if (guest_disk.root_name != 'disk'):
                continue

            if (guest_disk.target_dev is None or guest_disk.serial is None):
                continue

            if guest_disk.serial == volume_id:
                my_dev = guest_disk.target_dev

                active_disk = guest_disk.source_path
                active_protocol = guest_disk.source_protocol
                active_disk_object = guest_disk
                break

        if my_dev is None or (active_disk is None and active_protocol is None):
            LOG.debug('Domain XML: %s', xml, instance=instance)
            msg = (_('Disk with id: %s not found attached to instance.')
                   % volume_id)
            raise exception.InternalError(msg)

        LOG.debug("found device at %s", my_dev, instance=instance)

        def _get_snap_dev(filename, backing_store):
            if filename is None:
                msg = _('filename cannot be None')
                raise exception.InternalError(msg)

            # libgfapi delete
            LOG.debug("XML: %s", xml)

            LOG.debug("active disk object: %s", active_disk_object)

            # determine reference within backing store for desired image
            filename_to_merge = filename
            matched_name = None
            b = backing_store
            index = None

            current_filename = active_disk_object.source_name.split('/')[1]
            if current_filename == filename_to_merge:
                return my_dev + '[0]'

            while b is not None:
                source_filename = b.source_name.split('/')[1]
                if source_filename == filename_to_merge:
                    LOG.debug('found match: %s', b.source_name)
                    matched_name = b.source_name
                    index = b.index
                    break

                b = b.backing_store

            if matched_name is None:
                msg = _('no match found for %s') % (filename_to_merge)
                raise exception.InternalError(msg)

            LOG.debug('index of match (%s) is %s', b.source_name, index)

            my_snap_dev = '%s[%s]' % (my_dev, index)
            return my_snap_dev

        if delete_info['merge_target_file'] is None:
            # pull via blockRebase()

            # Merge the most recent snapshot into the active image

            rebase_disk = my_dev
            rebase_base = delete_info['file_to_merge']  # often None
            if (active_protocol is not None) and (rebase_base is not None):
                rebase_base = _get_snap_dev(rebase_base,
                                            active_disk_object.backing_store)

            # NOTE(deepakcs): libvirt added support for _RELATIVE in v1.2.7,
            # and when available this flag _must_ be used to ensure backing
            # paths are maintained relative by qemu.
            #
            # If _RELATIVE flag not found, continue with old behaviour
            # (relative backing path seems to work for this case)
            try:
                libvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE
                relative = rebase_base is not None
            except AttributeError:
                LOG.warning(
                    "Relative blockrebase support was not detected. "
                    "Continuing with old behaviour.")
                relative = False

            LOG.debug(
                'disk: %(disk)s, base: %(base)s, '
                'bw: %(bw)s, relative: %(relative)s',
                {'disk': rebase_disk,
                 'base': rebase_base,
                 'bw': libvirt_guest.BlockDevice.REBASE_DEFAULT_BANDWIDTH,
                 'relative': str(relative)}, instance=instance)

            dev = guest.get_block_device(rebase_disk)
            if guest.is_active():
                result = dev.rebase(rebase_base, relative=relative)
                if result == 0:
                    LOG.debug('blockRebase started successfully',
                              instance=instance)

                while not dev.is_job_complete():
                    LOG.debug('waiting for blockRebase job completion',
                              instance=instance)
                    time.sleep(0.5)

            # If the guest is not running libvirt won't do a blockRebase.
            # In that case, let's ask qemu-img to rebase the disk.
            else:
                LOG.debug('Guest is not running so doing a block rebase '
                          'using "qemu-img rebase"', instance=instance)
                self._rebase_with_qemu_img(guest, dev, active_disk_object,
                                           rebase_base)

        else:
            # commit with blockCommit()
            my_snap_base = None
            my_snap_top = None
            commit_disk = my_dev

            if active_protocol is not None:
                my_snap_base = _get_snap_dev(delete_info['merge_target_file'],
                                             active_disk_object.backing_store)
                my_snap_top = _get_snap_dev(delete_info['file_to_merge'],
                                            active_disk_object.backing_store)

            commit_base = my_snap_base or delete_info['merge_target_file']
            commit_top = my_snap_top or delete_info['file_to_merge']

            LOG.debug('will call blockCommit with commit_disk=%(commit_disk)s '
                      'commit_base=%(commit_base)s '
                      'commit_top=%(commit_top)s ',
                      {'commit_disk': commit_disk,
                       'commit_base': commit_base,
                       'commit_top': commit_top}, instance=instance)

            dev = guest.get_block_device(commit_disk)
            result = dev.commit(commit_base, commit_top, relative=True)

            if result == 0:
                LOG.debug('blockCommit started successfully',
                          instance=instance)

            while not dev.is_job_complete():
                LOG.debug('waiting for blockCommit job completion',
                          instance=instance)
                time.sleep(0.5)

    def volume_snapshot_delete(self, context, instance, volume_id, snapshot_id,
                               delete_info):
        try:
            self._volume_snapshot_delete(context, instance, volume_id,
                                         snapshot_id, delete_info=delete_info)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception(_('Error occurred during '
                                'volume_snapshot_delete, '
                                'sending error status to Cinder.'),
                              instance=instance)
                self._volume_snapshot_update_status(
                    context, snapshot_id, 'error_deleting')

        self._volume_snapshot_update_status(context, snapshot_id, 'deleting')
        self._volume_refresh_connection_info(context, instance, volume_id)

    def reboot(self, context, instance, network_info, reboot_type,
               block_device_info=None, bad_volumes_callback=None):
        """Reboot a virtual machine, given an instance reference."""
        if reboot_type == 'SOFT':
            # NOTE(vish): This will attempt to do a graceful shutdown/restart.
            try:
                soft_reboot_success = self._soft_reboot(instance)
            except libvirt.libvirtError as e:
                LOG.debug("Instance soft reboot failed: %s", e,
                          instance=instance)
                soft_reboot_success = False

            if soft_reboot_success:
                LOG.info("Instance soft rebooted successfully.",
                         instance=instance)
                return
            else:
                LOG.warning("Failed to soft reboot instance. "
                            "Trying hard reboot.",
                            instance=instance)
        return self._hard_reboot(context, instance, network_info,
                                 block_device_info)

    def _soft_reboot(self, instance):
        """Attempt to shutdown and restart the instance gracefully.

        We use shutdown and create here so we can return if the guest
        responded and actually rebooted. Note that this method only
        succeeds if the guest responds to acpi. Therefore we return
        success or failure so we can fall back to a hard reboot if
        necessary.

        :returns: True if the reboot succeeded
        """
        guest = self._host.get_guest(instance)

        state = guest.get_power_state(self._host)
        old_domid = guest.id
        # NOTE(vish): This check allows us to reboot an instance that
        #             is already shutdown.
        if state == power_state.RUNNING:
            guest.shutdown()
        # NOTE(vish): This actually could take slightly longer than the
        #             FLAG defines depending on how long the get_info
        #             call takes to return.
        self._prepare_pci_devices_for_use(
            pci_manager.get_instance_pci_devs(instance, 'all'))
        for x in range(CONF.libvirt.wait_soft_reboot_seconds):
            guest = self._host.get_guest(instance)

            state = guest.get_power_state(self._host)
            new_domid = guest.id

            # NOTE(ivoks): By checking domain IDs, we make sure we are
            #              not recreating domain that's already running.
            if old_domid != new_domid:
                if state in [power_state.SHUTDOWN,
                             power_state.CRASHED]:
                    LOG.info("Instance shutdown successfully.",
                             instance=instance)
                    self._create_domain(domain=guest._domain)
                    timer = loopingcall.FixedIntervalLoopingCall(
                        self._wait_for_running, instance)
                    timer.start(interval=0.5).wait()
                    return True
                else:
                    LOG.info("Instance may have been rebooted during soft "
                             "reboot, so return now.", instance=instance)
                    return True
            greenthread.sleep(1)
        return False

    def _hard_reboot(self, context, instance, network_info,
                     block_device_info=None):
        """Reboot a virtual machine, given an instance reference.

        Performs a Libvirt reset (if supported) on the domain.

        If Libvirt reset is unavailable this method actually destroys and
        re-creates the domain to ensure the reboot happens, as the guest
        OS cannot ignore this action.
        """
        # NOTE(mdbooth): In addition to performing a hard reboot of the domain,
        # the hard reboot operation is relied upon by operators to be an
        # automated attempt to fix as many things as possible about a
        # non-functioning instance before resorting to manual intervention.
        # With this goal in mind, we tear down all the aspects of an instance
        # we can here without losing data. This allows us to re-initialise from
        # scratch, and hopefully fix, most aspects of a non-functioning guest.
        self.destroy(context, instance, network_info, destroy_disks=False,
                     block_device_info=block_device_info)

        # Convert the system metadata to image metadata
        # NOTE(mdbooth): This is a workaround for stateless Nova compute
        #                https://bugs.launchpad.net/nova/+bug/1349978
        instance_dir = libvirt_utils.get_instance_path(instance)
        fileutils.ensure_tree(instance_dir)

        disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
                                            instance,
                                            instance.image_meta,
                                            block_device_info)
        # NOTE(vish): This could generate the wrong device_format if we are
        #             using the raw backend and the images don't exist yet.
        #             The create_images_and_backing below doesn't properly
        #             regenerate raw backend images, however, so when it
        #             does we need to (re)generate the xml after the images
        #             are in place.
        xml = self._get_guest_xml(context, instance, network_info, disk_info,
                                  instance.image_meta,
                                  block_device_info=block_device_info)

        # NOTE(mdbooth): context.auth_token will not be set when we call
        #                _hard_reboot from resume_state_on_host_boot()
        if context.auth_token is not None:
            # NOTE (rmk): Re-populate any missing backing files.
            config = vconfig.LibvirtConfigGuest()
            config.parse_str(xml)
            backing_disk_info = self._get_instance_disk_info_from_config(
                config, block_device_info)
            self._create_images_and_backing(context, instance, instance_dir,
                                            backing_disk_info)

        # Initialize all the necessary networking, block devices and
        # start the instance.
        # NOTE(melwitt): Pass vifs_already_plugged=True here even though we've
        # unplugged vifs earlier. The behavior of neutron plug events depends
        # on which vif type we're using and we are working with a stale network
        # info cache here, so won't rely on waiting for neutron plug events.
        # vifs_already_plugged=True means "do not wait for neutron plug events"
        self._create_domain_and_network(context, xml, instance, network_info,
                                        block_device_info=block_device_info,
                                        vifs_already_plugged=True)
        self._prepare_pci_devices_for_use(
            pci_manager.get_instance_pci_devs(instance, 'all'))

        def _wait_for_reboot():
            """Called at an interval until the VM is running again."""
            state = self.get_info(instance).state

            if state == power_state.RUNNING:
                LOG.info("Instance rebooted successfully.",
                         instance=instance)
                raise loopingcall.LoopingCallDone()

        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_reboot)
        timer.start(interval=0.5).wait()

    def pause(self, instance):
        """Pause VM instance."""
        self._host.get_guest(instance).pause()

    def unpause(self, instance):
        """Unpause paused VM instance."""
        guest = self._host.get_guest(instance)
        guest.resume()
        guest.sync_guest_time()

    def _clean_shutdown(self, instance, timeout, retry_interval):
        """Attempt to shutdown the instance gracefully.

        :param instance: The instance to be shutdown
        :param timeout: How long to wait in seconds for the instance to
                        shutdown
        :param retry_interval: How often in seconds to signal the instance
                               to shutdown while waiting

        :returns: True if the shutdown succeeded
        """

        # List of states that represent a shutdown instance
        SHUTDOWN_STATES = [power_state.SHUTDOWN,
                           power_state.CRASHED]

        try:
            guest = self._host.get_guest(instance)
        except exception.InstanceNotFound:
            # If the instance has gone then we don't need to
            # wait for it to shutdown
            return True

        state = guest.get_power_state(self._host)
        if state in SHUTDOWN_STATES:
            LOG.info("Instance already shutdown.", instance=instance)
            return True

        LOG.debug("Shutting down instance from state %s", state,
                  instance=instance)
        guest.shutdown()
        retry_countdown = retry_interval

        for sec in range(timeout):

            guest = self._host.get_guest(instance)
            state = guest.get_power_state(self._host)

            if state in SHUTDOWN_STATES:
                LOG.info("Instance shutdown successfully after %d seconds.",
                         sec, instance=instance)
                return True

            # Note(PhilD): We can't assume that the Guest was able to process
            #              any previous shutdown signal (for example it may
            #              have still been startingup, so within the overall
            #              timeout we re-trigger the shutdown every
            #              retry_interval
            if retry_countdown == 0:
                retry_countdown = retry_interval
                # Instance could shutdown at any time, in which case we
                # will get an exception when we call shutdown
                try:
                    LOG.debug("Instance in state %s after %d seconds - "
                              "resending shutdown", state, sec,
                              instance=instance)
                    guest.shutdown()
                except libvirt.libvirtError:
                    # Assume this is because its now shutdown, so loop
                    # one more time to clean up.
                    LOG.debug("Ignoring libvirt exception from shutdown "
                              "request.", instance=instance)
                    continue
            else:
                retry_countdown -= 1

            time.sleep(1)

        LOG.info("Instance failed to shutdown in %d seconds.",
                 timeout, instance=instance)
        return False

    def power_off(self, instance, timeout=0, retry_interval=0):
        """Power off the specified instance."""
        if timeout:
            self._clean_shutdown(instance, timeout, retry_interval)
        self._destroy(instance)

    def power_on(self, context, instance, network_info,
                 block_device_info=None):
        """Power on the specified instance."""
        # We use _hard_reboot here to ensure that all backing files,
        # network, and block device connections, etc. are established
        # and available before we attempt to start the instance.
        self._hard_reboot(context, instance, network_info, block_device_info)

    def trigger_crash_dump(self, instance):

        """Trigger crash dump by injecting an NMI to the specified instance."""
        try:
            self._host.get_guest(instance).inject_nmi()
        except libvirt.libvirtError as ex:
            error_code = ex.get_error_code()

            if error_code == libvirt.VIR_ERR_NO_SUPPORT:
                raise exception.TriggerCrashDumpNotSupported()
            elif error_code == libvirt.VIR_ERR_OPERATION_INVALID:
                raise exception.InstanceNotRunning(instance_id=instance.uuid)

            LOG.exception(_('Error from libvirt while injecting an NMI to '
                            '%(instance_uuid)s: '
                            '[Error Code %(error_code)s] %(ex)s'),
                          {'instance_uuid': instance.uuid,
                           'error_code': error_code, 'ex': ex})
            raise

    def suspend(self, context, instance):
        """Suspend the specified instance."""
        guest = self._host.get_guest(instance)

        self._detach_pci_devices(guest,
            pci_manager.get_instance_pci_devs(instance))
        self._detach_direct_passthrough_ports(context, instance, guest)
        guest.save_memory_state()

    def resume(self, context, instance, network_info, block_device_info=None):
        """resume the specified instance."""
        xml = self._get_existing_domain_xml(instance, network_info,
                                            block_device_info)
        guest = self._create_domain_and_network(context, xml, instance,
                           network_info, block_device_info=block_device_info,
                           vifs_already_plugged=True)
        self._attach_pci_devices(guest,
            pci_manager.get_instance_pci_devs(instance))
        self._attach_direct_passthrough_ports(
            context, instance, guest, network_info)
        timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_running,
                                                     instance)
        timer.start(interval=0.5).wait()
        guest.sync_guest_time()

    def resume_state_on_host_boot(self, context, instance, network_info,
                                  block_device_info=None):
        """resume guest state when a host is booted."""
        # Check if the instance is running already and avoid doing
        # anything if it is.
        try:
            guest = self._host.get_guest(instance)
            state = guest.get_power_state(self._host)

            ignored_states = (power_state.RUNNING,
                              power_state.SUSPENDED,
                              power_state.NOSTATE,
                              power_state.PAUSED)

            if state in ignored_states:
                return
        except (exception.InternalError, exception.InstanceNotFound):
            pass

        # Instance is not up and could be in an unknown state.
        # Be as absolute as possible about getting it back into
        # a known and running state.
        self._hard_reboot(context, instance, network_info, block_device_info)

    def rescue(self, context, instance, network_info, image_meta,
               rescue_password):
        """Loads a VM using rescue images.

        A rescue is normally performed when something goes wrong with the
        primary images and data needs to be corrected/recovered. Rescuing
        should not edit or over-ride the original image, only allow for
        data recovery.

        """
        instance_dir = libvirt_utils.get_instance_path(instance)
        unrescue_xml = self._get_existing_domain_xml(instance, network_info)
        unrescue_xml_path = os.path.join(instance_dir, 'unrescue.xml')
        libvirt_utils.write_to_file(unrescue_xml_path, unrescue_xml)

        rescue_image_id = None
        if image_meta.obj_attr_is_set("id"):
            rescue_image_id = image_meta.id

        rescue_images = {
            'image_id': (rescue_image_id or
                        CONF.libvirt.rescue_image_id or instance.image_ref),
            'kernel_id': (CONF.libvirt.rescue_kernel_id or
                          instance.kernel_id),
            'ramdisk_id': (CONF.libvirt.rescue_ramdisk_id or
                           instance.ramdisk_id),
        }
        disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
                                            instance,
                                            image_meta,
                                            rescue=True)
        injection_info = InjectionInfo(network_info=network_info,
                                       admin_pass=rescue_password,
                                       files=None)
        gen_confdrive = functools.partial(self._create_configdrive,
                                          context, instance, injection_info,
                                          rescue=True)
        self._create_image(context, instance, disk_info['mapping'],
                           injection_info=injection_info, suffix='.rescue',
                           disk_images=rescue_images)
        xml = self._get_guest_xml(context, instance, network_info, disk_info,
                                  image_meta, rescue=rescue_images)
        self._destroy(instance)
        self._create_domain(xml, post_xml_callback=gen_confdrive)

    def unrescue(self, instance, network_info):
        """Reboot the VM which is being rescued back into primary images.
        """
        instance_dir = libvirt_utils.get_instance_path(instance)
        unrescue_xml_path = os.path.join(instance_dir, 'unrescue.xml')
        xml = libvirt_utils.load_file(unrescue_xml_path)
        guest = self._host.get_guest(instance)

        # TODO(sahid): We are converting all calls from a
        # virDomain object to use nova.virt.libvirt.Guest.
        # We should be able to remove virt_dom at the end.
        virt_dom = guest._domain
        self._destroy(instance)
        self._create_domain(xml, virt_dom)
        libvirt_utils.file_delete(unrescue_xml_path)
        rescue_files = os.path.join(instance_dir, "*.rescue")
        for rescue_file in glob.iglob(rescue_files):
            if os.path.isdir(rescue_file):
                shutil.rmtree(rescue_file)
            else:
                libvirt_utils.file_delete(rescue_file)
        # cleanup rescue volume
        lvm.remove_volumes([lvmdisk for lvmdisk in self._lvm_disks(instance)
                                if lvmdisk.endswith('.rescue')])
        if CONF.libvirt.images_type == 'rbd':
            filter_fn = lambda disk: (disk.startswith(instance.uuid) and
                                      disk.endswith('.rescue'))
            LibvirtDriver._get_rbd_driver().cleanup_volumes(filter_fn)

    def poll_rebooting_instances(self, timeout, instances):
        pass

    # NOTE(ilyaalekseyev): Implementation like in multinics
    # for xenapi(tr3buchet)
    def spawn(self, context, instance, image_meta, injected_files,
              admin_password, network_info=None, block_device_info=None):
        disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
                                            instance,
                                            image_meta,
                                            block_device_info)
        injection_info = InjectionInfo(network_info=network_info,
                                       files=injected_files,
                                       admin_pass=admin_password)
        gen_confdrive = functools.partial(self._create_configdrive,
                                          context, instance,
                                          injection_info)
        self._create_image(context, instance, disk_info['mapping'],
                           injection_info=injection_info,
                           block_device_info=block_device_info)

        # Required by Quobyte CI
        self._ensure_console_log_for_instance(instance)

        xml = self._get_guest_xml(context, instance, network_info,
                                  disk_info, image_meta,
                                  block_device_info=block_device_info)
        self._create_domain_and_network(
            context, xml, instance, network_info,
            block_device_info=block_device_info,
            post_xml_callback=gen_confdrive,
            destroy_disks_on_failure=True)
        LOG.debug("Instance is running", instance=instance)

        def _wait_for_boot():
            """Called at an interval until the VM is running."""
            state = self.get_info(instance).state

            if state == power_state.RUNNING:
                LOG.info("Instance spawned successfully.", instance=instance)
                raise loopingcall.LoopingCallDone()

        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_boot)
        timer.start(interval=0.5).wait()

    def _flush_libvirt_console(self, pty):
        out, err = utils.execute('dd',
                                 'if=%s' % pty,
                                 'iflag=nonblock',
                                 run_as_root=True,
                                 check_exit_code=False)
        return out

    def _append_to_file(self, data, fpath):
        LOG.info('data: %(data)r, fpath: %(fpath)r',
                 {'data': data, 'fpath': fpath})
        with open(fpath, 'a+') as fp:
            fp.write(data)

        return fpath

    def _get_console_output_file(self, instance, console_log):
        bytes_to_read = MAX_CONSOLE_BYTES
        log_data = b""  # The last N read bytes
        i = 0  # in case there is a log rotation (like "virtlogd")
        path = console_log
        while bytes_to_read > 0 and os.path.exists(path):
            libvirt_utils.chown(path, os.getuid())
            with libvirt_utils.file_open(path, 'rb') as fp:
                read_log_data, remaining = libvirt_utils.last_bytes(
                                                fp, bytes_to_read)
                # We need the log file content in chronological order,
                # that's why we *prepend* the log data.
                log_data = read_log_data + log_data
                bytes_to_read -= len(read_log_data)
                path = console_log + "." + str(i)
                i += 1
            if remaining > 0:
                LOG.info('Truncated console log returned, '
                         '%d bytes ignored', remaining, instance=instance)
        return log_data

    def get_console_output(self, context, instance):
        guest = self._host.get_guest(instance)

        xml = guest.get_xml_desc()
        tree = etree.fromstring(xml)

        # If the guest has a console logging to a file prefer to use that
        file_consoles = tree.findall("./devices/console[@type='file']")
        if file_consoles:
            for file_console in file_consoles:
                source_node = file_console.find('./source')
                if source_node is None:
                    continue
                path = source_node.get("path")
                if not path:
                    continue

                if not os.path.exists(path):
                    LOG.info('Instance is configured with a file console, '
                             'but the backing file is not (yet?) present',
                             instance=instance)
                    return ""

                return self._get_console_output_file(instance, path)

        # Try 'pty' types
        pty_consoles = tree.findall("./devices/console[@type='pty']")
        if pty_consoles:
            for pty_console in pty_consoles:
                source_node = pty_console.find('./source')
                if source_node is None:
                    continue
                pty = source_node.get("path")
                if not pty:
                    continue
                break
            else:
                raise exception.ConsoleNotAvailable()
        else:
            raise exception.ConsoleNotAvailable()

        console_log = self._get_console_log_path(instance)
        # By default libvirt chowns the console log when it starts a domain.
        # We need to chown it back before attempting to read from or write
        # to it.
        if os.path.exists(console_log):
            libvirt_utils.chown(console_log, os.getuid())

        data = self._flush_libvirt_console(pty)
        # NOTE(markus_z): The virt_types kvm and qemu are the only ones
        # which create a dedicated file device for the console logging.
        # Other virt_types like xen, lxc, uml, parallels depend on the
        # flush of that pty device into the "console.log" file to ensure
        # that a series of "get_console_output" calls return the complete
        # content even after rebooting a guest.
        fpath = self._append_to_file(data, console_log)

        return self._get_console_output_file(instance, fpath)

    def get_host_ip_addr(self):
        ips = compute_utils.get_machine_ips()
        if CONF.my_ip not in ips:
            LOG.warning('my_ip address (%(my_ip)s) was not found on '
                        'any of the interfaces: %(ifaces)s',
                        {'my_ip': CONF.my_ip, 'ifaces': ", ".join(ips)})
        return CONF.my_ip

    def get_vnc_console(self, context, instance):
        def get_vnc_port_for_instance(instance_name):
            guest = self._host.get_guest(instance)

            xml = guest.get_xml_desc()
            xml_dom = etree.fromstring(xml)

            graphic = xml_dom.find("./devices/graphics[@type='vnc']")
            if graphic is not None:
                return graphic.get('port')
            # NOTE(rmk): We had VNC consoles enabled but the instance in
            # question is not actually listening for connections.
            raise exception.ConsoleTypeUnavailable(console_type='vnc')

        port = get_vnc_port_for_instance(instance.name)
        host = CONF.vnc.vncserver_proxyclient_address

        return ctype.ConsoleVNC(host=host, port=port)

    def get_spice_console(self, context, instance):
        def get_spice_ports_for_instance(instance_name):
            guest = self._host.get_guest(instance)

            xml = guest.get_xml_desc()
            xml_dom = etree.fromstring(xml)

            graphic = xml_dom.find("./devices/graphics[@type='spice']")
            if graphic is not None:
                return (graphic.get('port'), graphic.get('tlsPort'))
            # NOTE(rmk): We had Spice consoles enabled but the instance in
            # question is not actually listening for connections.
            raise exception.ConsoleTypeUnavailable(console_type='spice')

        ports = get_spice_ports_for_instance(instance.name)
        host = CONF.spice.server_proxyclient_address

        return ctype.ConsoleSpice(host=host, port=ports[0], tlsPort=ports[1])

    def get_serial_console(self, context, instance):
        guest = self._host.get_guest(instance)
        for hostname, port in self._get_serial_ports_from_guest(
                guest, mode='bind'):
            return ctype.ConsoleSerial(host=hostname, port=port)
        raise exception.ConsoleTypeUnavailable(console_type='serial')

    @staticmethod
    def _supports_direct_io(dirpath):

        if not hasattr(os, 'O_DIRECT'):
            LOG.debug("This python runtime does not support direct I/O")
            return False

        testfile = os.path.join(dirpath, ".directio.test")

        hasDirectIO = True
        fd = None
        try:
            fd = os.open(testfile, os.O_CREAT | os.O_WRONLY | os.O_DIRECT)
            # Check is the write allowed with 512 byte alignment
            align_size = 512
            m = mmap.mmap(-1, align_size)
            m.write(b"x" * align_size)
            os.write(fd, m)
            LOG.debug("Path '%(path)s' supports direct I/O",
                      {'path': dirpath})
        except OSError as e:
            if e.errno == errno.EINVAL:
                LOG.debug("Path '%(path)s' does not support direct I/O: "
                          "'%(ex)s'", {'path': dirpath, 'ex': e})
                hasDirectIO = False
            else:
                with excutils.save_and_reraise_exception():
                    LOG.error("Error on '%(path)s' while checking "
                              "direct I/O: '%(ex)s'",
                              {'path': dirpath, 'ex': e})
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error("Error on '%(path)s' while checking direct I/O: "
                          "'%(ex)s'", {'path': dirpath, 'ex': e})
        finally:
            # ensure unlink(filepath) will actually remove the file by deleting
            # the remaining link to it in close(fd)
            if fd is not None:
                os.close(fd)

            try:
                os.unlink(testfile)
            except Exception:
                pass

        return hasDirectIO

    @staticmethod
    def _create_ephemeral(target, ephemeral_size,
                          fs_label, os_type, is_block_dev=False,
                          context=None, specified_fs=None,
                          vm_mode=None):
        if not is_block_dev:
            if (CONF.libvirt.virt_type == "parallels" and
                    vm_mode == fields.VMMode.EXE):

                libvirt_utils.create_ploop_image('expanded', target,
                                                 '%dG' % ephemeral_size,
                                                 specified_fs)
                return
            libvirt_utils.create_image('raw', target, '%dG' % ephemeral_size)

        # Run as root only for block devices.
        disk_api.mkfs(os_type, fs_label, target, run_as_root=is_block_dev,
                      specified_fs=specified_fs)

    @staticmethod
    def _create_swap(target, swap_mb, context=None):
        """Create a swap file of specified size."""
        libvirt_utils.create_image('raw', target, '%dM' % swap_mb)
        utils.mkfs('swap', target)

    @staticmethod
    def _get_console_log_path(instance):
        return os.path.join(libvirt_utils.get_instance_path(instance),
                            'console.log')

    def _ensure_console_log_for_instance(self, instance):
        # NOTE(mdbooth): Although libvirt will create this file for us
        # automatically when it starts, it will initially create it with
        # root ownership and then chown it depending on the configuration of
        # the domain it is launching. Quobyte CI explicitly disables the
        # chown by setting dynamic_ownership=0 in libvirt's config.
        # Consequently when the domain starts it is unable to write to its
        # console.log. See bug https://bugs.launchpad.net/nova/+bug/1597644
        #
        # To work around this, we create the file manually before starting
        # the domain so it has the same ownership as Nova. This works
        # for Quobyte CI because it is also configured to run qemu as the same
        # user as the Nova service. Installations which don't set
        # dynamic_ownership=0 are not affected because libvirt will always
        # correctly configure permissions regardless of initial ownership.
        #
        # Setting dynamic_ownership=0 is dubious and potentially broken in
        # more ways than console.log (see comment #22 on the above bug), so
        # Future Maintainer who finds this code problematic should check to see
        # if we still support it.
        console_file = self._get_console_log_path(instance)
        LOG.debug('Ensure instance console log exists: %s', console_file,
                  instance=instance)
        try:
            libvirt_utils.file_open(console_file, 'a').close()
        # NOTE(sfinucan): We can safely ignore permission issues here and
        # assume that it is libvirt that has taken ownership of this file.
        except IOError as ex:
            if ex.errno != errno.EACCES:
                raise
            LOG.debug('Console file already exists: %s.', console_file)

    @staticmethod
    def _get_disk_config_image_type():
        # TODO(mikal): there is a bug here if images_type has
        # changed since creation of the instance, but I am pretty
        # sure that this bug already exists.
        return 'rbd' if CONF.libvirt.images_type == 'rbd' else 'raw'

    @staticmethod
    def _is_booted_from_volume(block_device_info):
        """Determines whether the VM is booting from volume

        Determines whether the block device info indicates that the VM
        is booting from a volume.
        """
        block_device_mapping = driver.block_device_info_get_mapping(
            block_device_info)
        return bool(block_device.get_root_bdm(block_device_mapping))

    def _inject_data(self, disk, instance, injection_info):
        """Injects data in a disk image

        Helper used for injecting data in a disk image file system.

        :param disk: The disk we're injecting into (an Image object)
        :param instance: The instance we're injecting into
        :param injection_info: Injection info
        """
        # Handles the partition need to be used.
        LOG.debug('Checking root disk injection %s',
                  str(injection_info), instance=instance)
        target_partition = None
        if not instance.kernel_id:
            target_partition = CONF.libvirt.inject_partition
            if target_partition == 0:
                target_partition = None
        if CONF.libvirt.virt_type == 'lxc':
            target_partition = None

        # Handles the key injection.
        if CONF.libvirt.inject_key and instance.get('key_data'):
            key = str(instance.key_data)
        else:
            key = None

        # Handles the admin password injection.
        if not CONF.libvirt.inject_password:
            admin_pass = None
        else:
            admin_pass = injection_info.admin_pass

        # Handles the network injection.
        net = netutils.get_injected_network_template(
            injection_info.network_info,
            libvirt_virt_type=CONF.libvirt.virt_type)

        # Handles the metadata injection
        metadata = instance.get('metadata')

        if any((key, net, metadata, admin_pass, injection_info.files)):
            LOG.debug('Injecting %s', str(injection_info),
                      instance=instance)
            img_id = instance.image_ref
            try:
                disk_api.inject_data(disk.get_model(self._conn),
                                     key, net, metadata, admin_pass,
                                     injection_info.files,
                                     partition=target_partition,
                                     mandatory=('files',))
            except Exception as e:
                with excutils.save_and_reraise_exception():
                    LOG.error('Error injecting data into image '
                              '%(img_id)s (%(e)s)',
                              {'img_id': img_id, 'e': e},
                              instance=instance)

    # NOTE(sileht): many callers of this method assume that this
    # method doesn't fail if an image already exists but instead
    # think that it will be reused (ie: (live)-migration/resize)
    def _create_image(self, context, instance,
                      disk_mapping, injection_info=None, suffix='',
                      disk_images=None, block_device_info=None,
                      fallback_from_host=None,
                      ignore_bdi_for_swap=False):
        booted_from_volume = self._is_booted_from_volume(block_device_info)

        def image(fname, image_type=CONF.libvirt.images_type):
            return self.image_backend.by_name(instance,
                                              fname + suffix, image_type)

        def raw(fname):
            return image(fname, image_type='raw')

        # ensure directories exist and are writable
        fileutils.ensure_tree(libvirt_utils.get_instance_path(instance))

        LOG.info('Creating image', instance=instance)

        inst_type = instance.get_flavor()
        swap_mb = 0
        if 'disk.swap' in disk_mapping:
            mapping = disk_mapping['disk.swap']

            if ignore_bdi_for_swap:
                # This is a workaround to support legacy swap resizing,
                # which does not touch swap size specified in bdm,
                # but works with flavor specified size only.
                # In this case we follow the legacy logic and ignore block
                # device info completely.
                # NOTE(ft): This workaround must be removed when a correct
                # implementation of resize operation changing sizes in bdms is
                # developed. Also at that stage we probably may get rid of
                # the direct usage of flavor swap size here,
                # leaving the work with bdm only.
                swap_mb = inst_type['swap']
            else:
                swap = driver.block_device_info_get_swap(block_device_info)
                if driver.swap_is_usable(swap):
                    swap_mb = swap['swap_size']
                elif (inst_type['swap'] > 0 and
                      not block_device.volume_in_mapping(
                        mapping['dev'], block_device_info)):
                    swap_mb = inst_type['swap']

            if swap_mb > 0:
                if (CONF.libvirt.virt_type == "parallels" and
                        instance.vm_mode == fields.VMMode.EXE):
                    msg = _("Swap disk is not supported "
                            "for Virtuozzo container")
                    raise exception.Invalid(msg)

        if not disk_images:
            disk_images = {'image_id': instance.image_ref,
                           'kernel_id': instance.kernel_id,
                           'ramdisk_id': instance.ramdisk_id}

        if disk_images['kernel_id']:
            fname = imagecache.get_cache_fname(disk_images['kernel_id'])
            raw('kernel').cache(fetch_func=libvirt_utils.fetch_raw_image,
                                context=context,
                                filename=fname,
                                image_id=disk_images['kernel_id'])
            if disk_images['ramdisk_id']:
                fname = imagecache.get_cache_fname(disk_images['ramdisk_id'])
                raw('ramdisk').cache(fetch_func=libvirt_utils.fetch_raw_image,
                                     context=context,
                                     filename=fname,
                                     image_id=disk_images['ramdisk_id'])

        if CONF.libvirt.virt_type == 'uml':
            libvirt_utils.chown(image('disk').path, 'root')

        self._create_and_inject_local_root(context, instance,
                                           booted_from_volume, suffix,
                                           disk_images, injection_info,
                                           fallback_from_host)

        # Lookup the filesystem type if required
        os_type_with_default = disk_api.get_fs_type_for_os_type(
            instance.os_type)
        # Generate a file extension based on the file system
        # type and the mkfs commands configured if any
        file_extension = disk_api.get_file_extension_for_os_type(
                                                          os_type_with_default)

        vm_mode = fields.VMMode.get_from_instance(instance)
        ephemeral_gb = instance.flavor.ephemeral_gb
        if 'disk.local' in disk_mapping:
            disk_image = image('disk.local')
            fn = functools.partial(self._create_ephemeral,
                                   fs_label='ephemeral0',
                                   os_type=instance.os_type,
                                   is_block_dev=disk_image.is_block_dev,
                                   vm_mode=vm_mode)
            fname = "ephemeral_%s_%s" % (ephemeral_gb, file_extension)
            size = ephemeral_gb * units.Gi
            disk_image.cache(fetch_func=fn,
                             context=context,
                             filename=fname,
                             size=size,
                             ephemeral_size=ephemeral_gb)

        for idx, eph in enumerate(driver.block_device_info_get_ephemerals(
                block_device_info)):
            disk_image = image(blockinfo.get_eph_disk(idx))

            specified_fs = eph.get('guest_format')
            if specified_fs and not self.is_supported_fs_format(specified_fs):
                msg = _("%s format is not supported") % specified_fs
                raise exception.InvalidBDMFormat(details=msg)

            fn = functools.partial(self._create_ephemeral,
                                   fs_label='ephemeral%d' % idx,
                                   os_type=instance.os_type,
                                   is_block_dev=disk_image.is_block_dev,
                                   vm_mode=vm_mode)
            size = eph['size'] * units.Gi
            fname = "ephemeral_%s_%s" % (eph['size'], file_extension)
            disk_image.cache(fetch_func=fn,
                             context=context,
                             filename=fname,
                             size=size,
                             ephemeral_size=eph['size'],
                             specified_fs=specified_fs)

        if swap_mb > 0:
            size = swap_mb * units.Mi
            image('disk.swap').cache(fetch_func=self._create_swap,
                                     context=context,
                                     filename="swap_%s" % swap_mb,
                                     size=size,
                                     swap_mb=swap_mb)

    def _create_and_inject_local_root(self, context, instance,
                                      booted_from_volume, suffix, disk_images,
                                      injection_info, fallback_from_host):
        # File injection only if needed
        need_inject = (not configdrive.required_by(instance) and
                       injection_info is not None and
                       CONF.libvirt.inject_partition != -2)

        # NOTE(ndipanov): Even if disk_mapping was passed in, which
        # currently happens only on rescue - we still don't want to
        # create a base image.
        if not booted_from_volume:
            root_fname = imagecache.get_cache_fname(disk_images['image_id'])
            size = instance.flavor.root_gb * units.Gi

            if size == 0 or suffix == '.rescue':
                size = None

            backend = self.image_backend.by_name(instance, 'disk' + suffix,
                                                 CONF.libvirt.images_type)
            if instance.task_state == task_states.RESIZE_FINISH:
                backend.create_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME)
            if backend.SUPPORTS_CLONE:
                def clone_fallback_to_fetch(*args, **kwargs):
                    try:
                        backend.clone(context, disk_images['image_id'])
                    except exception.ImageUnacceptable:
                        libvirt_utils.fetch_image(*args, **kwargs)
                fetch_func = clone_fallback_to_fetch
            else:
                fetch_func = libvirt_utils.fetch_image
            self._try_fetch_image_cache(backend, fetch_func, context,
                                        root_fname, disk_images['image_id'],
                                        instance, size, fallback_from_host)

            if need_inject:
                self._inject_data(backend, instance, injection_info)

        elif need_inject:
            LOG.warning('File injection into a boot from volume '
                        'instance is not supported', instance=instance)

    def _create_configdrive(self, context, instance, injection_info,
                            rescue=False):
        # As this method being called right after the definition of a
        # domain, but before its actual launch, device metadata will be built
        # and saved in the instance for it to be used by the config drive and
        # the metadata service.
        instance.device_metadata = self._build_device_metadata(context,
                                                               instance)
        if configdrive.required_by(instance):
            LOG.info('Using config drive', instance=instance)

            name = 'disk.config'
            if rescue:
                name += '.rescue'

            config_disk = self.image_backend.by_name(
                instance, name, self._get_disk_config_image_type())

            # Don't overwrite an existing config drive
            if not config_disk.exists():
                extra_md = {}
                if injection_info.admin_pass:
                    extra_md['admin_pass'] = injection_info.admin_pass

                inst_md = instance_metadata.InstanceMetadata(
                    instance, content=injection_info.files, extra_md=extra_md,
                    network_info=injection_info.network_info,
                    request_context=context)

                cdb = configdrive.ConfigDriveBuilder(instance_md=inst_md)
                with cdb:
                    # NOTE(mdbooth): We're hardcoding here the path of the
                    # config disk when using the flat backend. This isn't
                    # good, but it's required because we need a local path we
                    # know we can write to in case we're subsequently
                    # importing into rbd. This will be cleaned up when we
                    # replace this with a call to create_from_func, but that
                    # can't happen until we've updated the backends and we
                    # teach them not to cache config disks. This isn't
                    # possible while we're still using cache() under the hood.
                    config_disk_local_path = os.path.join(
                        libvirt_utils.get_instance_path(instance), name)
                    LOG.info('Creating config drive at %(path)s',
                             {'path': config_disk_local_path},
                             instance=instance)

                    try:
                        cdb.make_drive(config_disk_local_path)
                    except processutils.ProcessExecutionError as e:
                        with excutils.save_and_reraise_exception():
                            LOG.error('Creating config drive failed with '
                                      'error: %s', e, instance=instance)

                try:
                    config_disk.import_file(
                        instance, config_disk_local_path, name)
                finally:
                    # NOTE(mikal): if the config drive was imported into RBD,
                    # then we no longer need the local copy
                    if CONF.libvirt.images_type == 'rbd':
                        LOG.info('Deleting local config drive %(path)s '
                                 'because it was imported into RBD.',
                                 {'path': config_disk_local_path},
                                 instance=instance)
                        os.unlink(config_disk_local_path)

    def _prepare_pci_devices_for_use(self, pci_devices):
        # kvm , qemu support managed mode
        # In managed mode, the configured device will be automatically
        # detached from the host OS drivers when the guest is started,
        # and then re-attached when the guest shuts down.
        if CONF.libvirt.virt_type != 'xen':
            # we do manual detach only for xen
            return
        try:
            for dev in pci_devices:
                libvirt_dev_addr = dev['hypervisor_name']
                libvirt_dev = \
                        self._host.device_lookup_by_name(libvirt_dev_addr)
                # Note(yjiang5) Spelling for 'dettach' is correct, see
                # http://libvirt.org/html/libvirt-libvirt.html.
                libvirt_dev.dettach()

            # Note(yjiang5): A reset of one PCI device may impact other
            # devices on the same bus, thus we need two separated loops
            # to detach and then reset it.
            for dev in pci_devices:
                libvirt_dev_addr = dev['hypervisor_name']
                libvirt_dev = \
                        self._host.device_lookup_by_name(libvirt_dev_addr)
                libvirt_dev.reset()

        except libvirt.libvirtError as exc:
            raise exception.PciDevicePrepareFailed(id=dev['id'],
                                                   instance_uuid=
                                                   dev['instance_uuid'],
                                                   reason=six.text_type(exc))

    def _detach_pci_devices(self, guest, pci_devs):
        try:
            for dev in pci_devs:
                guest.detach_device(self._get_guest_pci_device(dev), live=True)
                # after detachDeviceFlags returned, we should check the dom to
                # ensure the detaching is finished
                xml = guest.get_xml_desc()
                xml_doc = etree.fromstring(xml)
                guest_config = vconfig.LibvirtConfigGuest()
                guest_config.parse_dom(xml_doc)

                for hdev in [d for d in guest_config.devices
                    if isinstance(d, vconfig.LibvirtConfigGuestHostdevPCI)]:
                    hdbsf = [hdev.domain, hdev.bus, hdev.slot, hdev.function]
                    dbsf = pci_utils.parse_address(dev.address)
                    if [int(x, 16) for x in hdbsf] ==\
                            [int(x, 16) for x in dbsf]:
                        raise exception.PciDeviceDetachFailed(reason=
                                                              "timeout",
                                                              dev=dev)

        except libvirt.libvirtError as ex:
            error_code = ex.get_error_code()
            if error_code == libvirt.VIR_ERR_NO_DOMAIN:
                LOG.warning("Instance disappeared while detaching "
                            "a PCI device from it.")
            else:
                raise

    def _attach_pci_devices(self, guest, pci_devs):
        try:
            for dev in pci_devs:
                guest.attach_device(self._get_guest_pci_device(dev))

        except libvirt.libvirtError:
            LOG.error('Attaching PCI devices %(dev)s to %(dom)s failed.',
                      {'dev': pci_devs, 'dom': guest.id})
            raise

    @staticmethod
    def _has_direct_passthrough_port(network_info):
        for vif in network_info:
            if (vif['vnic_type'] in
                network_model.VNIC_TYPES_DIRECT_PASSTHROUGH):
                return True
        return False

    def _attach_direct_passthrough_ports(
        self, context, instance, guest, network_info=None):
        if network_info is None:
            network_info = instance.info_cache.network_info
        if network_info is None:
            return

        if self._has_direct_passthrough_port(network_info):
            for vif in network_info:
                if (vif['vnic_type'] in
                    network_model.VNIC_TYPES_DIRECT_PASSTHROUGH):
                    cfg = self.vif_driver.get_config(instance,
                                                     vif,
                                                     instance.image_meta,
                                                     instance.flavor,
                                                     CONF.libvirt.virt_type,
                                                     self._host)
                    LOG.debug('Attaching direct passthrough port %(port)s '
                              'to %(dom)s', {'port': vif, 'dom': guest.id},
                              instance=instance)
                    guest.attach_device(cfg)

    def _detach_direct_passthrough_ports(self, context, instance, guest):
        network_info = instance.info_cache.network_info
        if network_info is None:
            return

        if self._has_direct_passthrough_port(network_info):
            # In case of VNIC_TYPES_DIRECT_PASSTHROUGH ports we create
            # pci request per direct passthrough port. Therefore we can trust
            # that pci_slot value in the vif is correct.
            direct_passthrough_pci_addresses = [
                vif['profile']['pci_slot']
                for vif in network_info
                if (vif['vnic_type'] in
                    network_model.VNIC_TYPES_DIRECT_PASSTHROUGH and
                    vif['profile'].get('pci_slot') is not None)
            ]

            # use detach_pci_devices to avoid failure in case of
            # multiple guest direct passthrough ports with the same MAC
            # (protection use-case, ports are on different physical
            # interfaces)
            pci_devs = pci_manager.get_instance_pci_devs(instance, 'all')
            direct_passthrough_pci_addresses = (
                [pci_dev for pci_dev in pci_devs
                 if pci_dev.address in direct_passthrough_pci_addresses])
            self._detach_pci_devices(guest, direct_passthrough_pci_addresses)

    def _set_host_enabled(self, enabled,
                          disable_reason=DISABLE_REASON_UNDEFINED):
        """Enables / Disables the compute service on this host.

           This doesn't override non-automatic disablement with an automatic
           setting; thereby permitting operators to keep otherwise
           healthy hosts out of rotation.
        """

        status_name = {True: 'disabled',
                       False: 'enabled'}

        disable_service = not enabled

        ctx = nova_context.get_admin_context()
        try:
            service = objects.Service.get_by_compute_host(ctx, CONF.host)

            if service.disabled != disable_service:
                # Note(jang): this is a quick fix to stop operator-
                # disabled compute hosts from re-enabling themselves
                # automatically. We prefix any automatic reason code
                # with a fixed string. We only re-enable a host
                # automatically if we find that string in place.
                # This should probably be replaced with a separate flag.
                if not service.disabled or (
                        service.disabled_reason and
                        service.disabled_reason.startswith(DISABLE_PREFIX)):
                    service.disabled = disable_service
                    service.disabled_reason = (
                       DISABLE_PREFIX + disable_reason
                       if disable_service and disable_reason else
                           DISABLE_REASON_UNDEFINED)
                    service.save()
                    LOG.debug('Updating compute service status to %s',
                              status_name[disable_service])
                else:
                    LOG.debug('Not overriding manual compute service '
                              'status with: %s',
                              status_name[disable_service])
        except exception.ComputeHostNotFound:
            LOG.warning('Cannot update service status on host "%s" '
                        'since it is not registered.', CONF.host)
        except Exception:
            LOG.warning('Cannot update service status on host "%s" '
                        'due to an unexpected exception.', CONF.host,
                        exc_info=True)

        if enabled:
            mount.get_manager().host_up(self._host)
        else:
            mount.get_manager().host_down()

    def _get_guest_cpu_model_config(self):
        mode = CONF.libvirt.cpu_mode
        model = CONF.libvirt.cpu_model
        extra_flags = set([flag.lower() for flag in
            CONF.libvirt.cpu_model_extra_flags])

        if (CONF.libvirt.virt_type == "kvm" or
            CONF.libvirt.virt_type == "qemu"):
            if mode is None:
                caps = self._host.get_capabilities()
                # AArch64 lacks 'host-model' support because neither libvirt
                # nor QEMU are able to tell what the host CPU model exactly is.
                # And there is no CPU description code for ARM(64) at this
                # point.

                # Also worth noting: 'host-passthrough' mode will completely
                # break live migration, *unless* all the Compute nodes (running
                # libvirtd) have *identical* CPUs.
                if caps.host.cpu.arch == fields.Architecture.AARCH64:
                    mode = "host-passthrough"
                    LOG.info('CPU mode "host-passthrough" was chosen. Live '
                             'migration can break unless all compute nodes '
                             'have identical cpus. AArch64 does not support '
                             'other modes.')
                else:
                    mode = "host-model"
            if mode == "none":
                return vconfig.LibvirtConfigGuestCPU()
        else:
            if mode is None or mode == "none":
                return None

        if ((CONF.libvirt.virt_type != "kvm" and
             CONF.libvirt.virt_type != "qemu")):
            msg = _("Config requested an explicit CPU model, but "
                    "the current libvirt hypervisor '%s' does not "
                    "support selecting CPU models") % CONF.libvirt.virt_type
            raise exception.Invalid(msg)

        if mode == "custom" and model is None:
            msg = _("Config requested a custom CPU model, but no "
                    "model name was provided")
            raise exception.Invalid(msg)
        elif mode != "custom" and model is not None:
            msg = _("A CPU model name should not be set when a "
                    "host CPU model is requested")
            raise exception.Invalid(msg)
        # FIXME (kchamart): We're intentionally restricting the choices
        # (in the conf/libvirt.py) for 'extra_flags` to just 'PCID', to
        # address the immediate guest performance degradation caused by
        # "Meltdown" CVE fixes on certain Intel CPU models.  In a future
        # patch, we will:
        # (a) Remove the restriction of choices for 'extra_flags',
        #     allowing to add / remove additional CPU flags, as it will
        #     make way for other useful features.
        # (b) Remove the below check for "host-model", as it is a
        #     valid configuration to supply additional CPU flags to it.
        # (c) Revisit and fix the warnings / exception handling for
        #     different combinations of CPU modes and 'extra_flags'.
        elif ((mode == "host-model" or mode == "host-passthrough") and
              extra_flags):
            extra_flags = []
            LOG.warning("Setting extra CPU flags is only valid in "
                        "combination with a custom CPU model. Refer "
                        "to the 'nova.conf' documentation for "
                        "'[libvirt]/cpu_model_extra_flags'")

        LOG.debug("CPU mode '%(mode)s' model '%(model)s' was chosen, "
                  "with extra flags: '%(extra_flags)s'",
                  {'mode': mode,
                   'model': (model or ""),
                   'extra_flags': (extra_flags or "")})

        cpu = vconfig.LibvirtConfigGuestCPU()
        cpu.mode = mode
        cpu.model = model

        # NOTE (kchamart): Currently there's no existing way to ask if a
        # given CPU model + CPU flags combination is supported by KVM &
        # a specific QEMU binary.  However, libvirt runs the 'CPUID'
        # command upfront -- before even a Nova instance (a QEMU
        # process) is launched -- to construct CPU models and check
        # their validity; so we are good there.  In the long-term,
        # upstream libvirt intends to add an additional new API that can
        # do fine-grained validation of a certain CPU model + CPU flags
        # against a specific QEMU binary (the libvirt RFE bug for that:
        # https://bugzilla.redhat.com/show_bug.cgi?id=1559832).
        for flag in extra_flags:
            cpu.add_feature(vconfig.LibvirtConfigGuestCPUFeature(flag))

        return cpu

    def _get_guest_cpu_config(self, flavor, image_meta,
                              guest_cpu_numa_config, instance_numa_topology):
        cpu = self._get_guest_cpu_model_config()

        if cpu is None:
            return None

        topology = hardware.get_best_cpu_topology(
                flavor, image_meta, numa_topology=instance_numa_topology)

        cpu.sockets = topology.sockets
        cpu.cores = topology.cores
        cpu.threads = topology.threads
        cpu.numa = guest_cpu_numa_config

        return cpu

    def _get_guest_disk_config(self, instance, name, disk_mapping, inst_type,
                               image_type=None):
        disk_unit = None
        disk = self.image_backend.by_name(instance, name, image_type)
        if (name == 'disk.config' and image_type == 'rbd' and
                not disk.exists()):
            # This is likely an older config drive that has not been migrated
            # to rbd yet. Try to fall back on 'flat' image type.
            # TODO(melwitt): Add online migration of some sort so we can
            # remove this fall back once we know all config drives are in rbd.
            # NOTE(vladikr): make sure that the flat image exist, otherwise
            # the image will be created after the domain definition.
            flat_disk = self.image_backend.by_name(instance, name, 'flat')
            if flat_disk.exists():
                disk = flat_disk
                LOG.debug('Config drive not found in RBD, falling back to the '
                          'instance directory', instance=instance)
        disk_info = disk_mapping[name]
        if 'unit' in disk_mapping and disk_info['bus'] == 'scsi':
            disk_unit = disk_mapping['unit']
            disk_mapping['unit'] += 1  # Increments for the next disk added
        conf = disk.libvirt_info(disk_info['bus'],
                                 disk_info['dev'],
                                 disk_info['type'],
                                 self.disk_cachemode,
                                 inst_type['extra_specs'],
                                 self._host.get_version(),
                                 disk_unit=disk_unit)
        return conf

    def _get_guest_fs_config(self, instance, name, image_type=None):
        disk = self.image_backend.by_name(instance, name, image_type)
        return disk.libvirt_fs_info("/", "ploop")

    def _get_guest_storage_config(self, instance, image_meta,
                                  disk_info,
                                  rescue, block_device_info,
                                  inst_type, os_type):
        devices = []
        disk_mapping = disk_info['mapping']

        block_device_mapping = driver.block_device_info_get_mapping(
            block_device_info)
        mount_rootfs = CONF.libvirt.virt_type == "lxc"
        scsi_controller = self._get_scsi_controller(image_meta)

        if scsi_controller and scsi_controller.model == 'virtio-scsi':
            # The virtio-scsi can handle up to 256 devices but the
            # optional element "address" must be defined to describe
            # where the device is placed on the controller (see:
            # LibvirtConfigGuestDeviceAddressDrive).
            #
            # Note about why it's added in disk_mapping: It's not
            # possible to pass an 'int' by reference in Python, so we
            # use disk_mapping as container to keep reference of the
            # unit added and be able to increment it for each disk
            # added.
            #
            # NOTE(jaypipes,melwitt): If this is a boot-from-volume instance,
            # we need to start the disk mapping unit at 1 since we set the
            # bootable volume's unit to 0 for the bootable volume.
            disk_mapping['unit'] = 0
            if self._is_booted_from_volume(block_device_info):
                disk_mapping['unit'] = 1

        def _get_ephemeral_devices():
            eph_devices = []
            for idx, eph in enumerate(
                driver.block_device_info_get_ephemerals(
                    block_device_info)):
                diskeph = self._get_guest_disk_config(
                    instance,
                    blockinfo.get_eph_disk(idx),
                    disk_mapping, inst_type)
                eph_devices.append(diskeph)
            return eph_devices

        if mount_rootfs:
            fs = vconfig.LibvirtConfigGuestFilesys()
            fs.source_type = "mount"
            fs.source_dir = os.path.join(
                libvirt_utils.get_instance_path(instance), 'rootfs')
            devices.append(fs)
        elif (os_type == fields.VMMode.EXE and
              CONF.libvirt.virt_type == "parallels"):
            if rescue:
                fsrescue = self._get_guest_fs_config(instance, "disk.rescue")
                devices.append(fsrescue)

                fsos = self._get_guest_fs_config(instance, "disk")
                fsos.target_dir = "/mnt/rescue"
                devices.append(fsos)
            else:
                if 'disk' in disk_mapping:
                    fs = self._get_guest_fs_config(instance, "disk")
                    devices.append(fs)
                devices = devices + _get_ephemeral_devices()
        else:

            if rescue:
                diskrescue = self._get_guest_disk_config(instance,
                                                         'disk.rescue',
                                                         disk_mapping,
                                                         inst_type)
                devices.append(diskrescue)

                diskos = self._get_guest_disk_config(instance,
                                                     'disk',
                                                     disk_mapping,
                                                     inst_type)
                devices.append(diskos)
            else:
                if 'disk' in disk_mapping:
                    diskos = self._get_guest_disk_config(instance,
                                                         'disk',
                                                         disk_mapping,
                                                         inst_type)
                    devices.append(diskos)

                if 'disk.local' in disk_mapping:
                    disklocal = self._get_guest_disk_config(instance,
                                                            'disk.local',
                                                            disk_mapping,
                                                            inst_type)
                    devices.append(disklocal)
                    instance.default_ephemeral_device = (
                        block_device.prepend_dev(disklocal.target_dev))

                devices = devices + _get_ephemeral_devices()

                if 'disk.swap' in disk_mapping:
                    diskswap = self._get_guest_disk_config(instance,
                                                           'disk.swap',
                                                           disk_mapping,
                                                           inst_type)
                    devices.append(diskswap)
                    instance.default_swap_device = (
                        block_device.prepend_dev(diskswap.target_dev))

            config_name = 'disk.config.rescue' if rescue else 'disk.config'
            if config_name in disk_mapping:
                diskconfig = self._get_guest_disk_config(
                    instance, config_name, disk_mapping, inst_type,
                    self._get_disk_config_image_type())
                devices.append(diskconfig)

        for vol in block_device.get_bdms_to_connect(block_device_mapping,
                                                   mount_rootfs):
            connection_info = vol['connection_info']
            vol_dev = block_device.prepend_dev(vol['mount_device'])
            info = disk_mapping[vol_dev]
            self._connect_volume(connection_info, info, instance)
            if scsi_controller and scsi_controller.model == 'virtio-scsi':
                # Check if this is the bootable volume when in a
                # boot-from-volume instance, and if so, ensure the unit
                # attribute is 0.
                if vol.get('boot_index') == 0:
                    info['unit'] = 0
                else:
                    info['unit'] = disk_mapping['unit']
                    disk_mapping['unit'] += 1
            cfg = self._get_volume_config(connection_info, info)
            devices.append(cfg)
            vol['connection_info'] = connection_info
            vol.save()

        for d in devices:
            self._set_cache_mode(d)

        if scsi_controller:
            devices.append(scsi_controller)

        return devices

    @staticmethod
    def _get_scsi_controller(image_meta):
        """Return scsi controller or None based on image meta"""
        # TODO(sahid): should raise an exception for an invalid controller
        if image_meta.properties.get('hw_scsi_model'):
            hw_scsi_model = image_meta.properties.hw_scsi_model
            scsi_controller = vconfig.LibvirtConfigGuestController()
            scsi_controller.type = 'scsi'
            scsi_controller.model = hw_scsi_model
            scsi_controller.index = 0
            return scsi_controller

    def _get_host_sysinfo_serial_hardware(self):
        """Get a UUID from the host hardware

        Get a UUID for the host hardware reported by libvirt.
        This is typically from the SMBIOS data, unless it has
        been overridden in /etc/libvirt/libvirtd.conf
        """
        caps = self._host.get_capabilities()
        return caps.host.uuid

    def _get_host_sysinfo_serial_os(self):
        """Get a UUID from the host operating system

        Get a UUID for the host operating system. Modern Linux
        distros based on systemd provide a /etc/machine-id
        file containing a UUID. This is also provided inside
        systemd based containers and can be provided by other
        init systems too, since it is just a plain text file.
        """
        if not os.path.exists("/etc/machine-id"):
            msg = _("Unable to get host UUID: /etc/machine-id does not exist")
            raise exception.InternalError(msg)

        with open("/etc/machine-id") as f:
            # We want to have '-' in the right place
            # so we parse & reformat the value
            lines = f.read().split()
            if not lines:
                msg = _("Unable to get host UUID: /etc/machine-id is empty")
                raise exception.InternalError(msg)

            return str(uuid.UUID(lines[0]))

    def _get_host_sysinfo_serial_auto(self):
        if os.path.exists("/etc/machine-id"):
            return self._get_host_sysinfo_serial_os()
        else:
            return self._get_host_sysinfo_serial_hardware()

    def _get_guest_config_sysinfo(self, instance):
        sysinfo = vconfig.LibvirtConfigGuestSysinfo()

        sysinfo.system_manufacturer = version.vendor_string()
        sysinfo.system_product = version.product_string()
        sysinfo.system_version = version.version_string_with_package()

        sysinfo.system_serial = self._sysinfo_serial_func()
        sysinfo.system_uuid = instance.uuid

        sysinfo.system_family = "Virtual Machine"

        return sysinfo

    def _get_guest_pci_device(self, pci_device):

        dbsf = pci_utils.parse_address(pci_device.address)
        dev = vconfig.LibvirtConfigGuestHostdevPCI()
        dev.domain, dev.bus, dev.slot, dev.function = dbsf

        # only kvm support managed mode
        if CONF.libvirt.virt_type in ('xen', 'parallels',):
            dev.managed = 'no'
        if CONF.libvirt.virt_type in ('kvm', 'qemu'):
            dev.managed = 'yes'

        return dev

    def _get_guest_config_meta(self, instance):
        """Get metadata config for guest."""

        meta = vconfig.LibvirtConfigGuestMetaNovaInstance()
        meta.package = version.version_string_with_package()
        meta.name = instance.display_name
        meta.creationTime = time.time()

        if instance.image_ref not in ("", None):
            meta.roottype = "image"
            meta.rootid = instance.image_ref

        system_meta = instance.system_metadata
        ometa = vconfig.LibvirtConfigGuestMetaNovaOwner()
        ometa.userid = instance.user_id
        ometa.username = system_meta.get('owner_user_name', 'N/A')
        ometa.projectid = instance.project_id
        ometa.projectname = system_meta.get('owner_project_name', 'N/A')
        meta.owner = ometa

        fmeta = vconfig.LibvirtConfigGuestMetaNovaFlavor()
        flavor = instance.flavor
        fmeta.name = flavor.name
        fmeta.memory = flavor.memory_mb
        fmeta.vcpus = flavor.vcpus
        fmeta.ephemeral = flavor.ephemeral_gb
        fmeta.disk = flavor.root_gb
        fmeta.swap = flavor.swap

        meta.flavor = fmeta

        return meta

    def _machine_type_mappings(self):
        mappings = {}
        for mapping in CONF.libvirt.hw_machine_type:
            host_arch, _, machine_type = mapping.partition('=')
            mappings[host_arch] = machine_type
        return mappings

    def _get_machine_type(self, image_meta, caps):
        # The underlying machine type can be set as an image attribute,
        # or otherwise based on some architecture specific defaults

        mach_type = None

        if image_meta.properties.get('hw_machine_type') is not None:
            mach_type = image_meta.properties.hw_machine_type
        else:
            # For ARM systems we will default to vexpress-a15 for armv7
            # and virt for aarch64
            if caps.host.cpu.arch == fields.Architecture.ARMV7:
                mach_type = "vexpress-a15"

            if caps.host.cpu.arch == fields.Architecture.AARCH64:
                mach_type = "virt"

            if caps.host.cpu.arch in (fields.Architecture.S390,
                                      fields.Architecture.S390X):
                mach_type = 's390-ccw-virtio'

            # If set in the config, use that as the default.
            if CONF.libvirt.hw_machine_type:
                mappings = self._machine_type_mappings()
                mach_type = mappings.get(caps.host.cpu.arch)

        return mach_type

    @staticmethod
    def _create_idmaps(klass, map_strings):
        idmaps = []
        if len(map_strings) > 5:
            map_strings = map_strings[0:5]
            LOG.warning("Too many id maps, only included first five.")
        for map_string in map_strings:
            try:
                idmap = klass()
                values = [int(i) for i in map_string.split(":")]
                idmap.start = values[0]
                idmap.target = values[1]
                idmap.count = values[2]
                idmaps.append(idmap)
            except (ValueError, IndexError):
                LOG.warning("Invalid value for id mapping %s", map_string)
        return idmaps

    def _get_guest_idmaps(self):
        id_maps = []
        if CONF.libvirt.virt_type == 'lxc' and CONF.libvirt.uid_maps:
            uid_maps = self._create_idmaps(vconfig.LibvirtConfigGuestUIDMap,
                                           CONF.libvirt.uid_maps)
            id_maps.extend(uid_maps)
        if CONF.libvirt.virt_type == 'lxc' and CONF.libvirt.gid_maps:
            gid_maps = self._create_idmaps(vconfig.LibvirtConfigGuestGIDMap,
                                           CONF.libvirt.gid_maps)
            id_maps.extend(gid_maps)
        return id_maps

    def _update_guest_cputune(self, guest, flavor, virt_type):
        is_able = self._host.is_cpu_control_policy_capable()

        cputuning = ['shares', 'period', 'quota']
        wants_cputune = any([k for k in cputuning
            if "quota:cpu_" + k in flavor.extra_specs.keys()])

        if wants_cputune and not is_able:
            raise exception.UnsupportedHostCPUControlPolicy()

        if not is_able or virt_type not in ('lxc', 'kvm', 'qemu'):
            return

        if guest.cputune is None:
            guest.cputune = vconfig.LibvirtConfigGuestCPUTune()
            # Setting the default cpu.shares value to be a value
            # dependent on the number of vcpus
        guest.cputune.shares = 1024 * guest.vcpus

        for name in cputuning:
            key = "quota:cpu_" + name
            if key in flavor.extra_specs:
                setattr(guest.cputune, name,
                        int(flavor.extra_specs[key]))

    def _get_cpu_numa_config_from_instance(self, instance_numa_topology,
                                           wants_hugepages):
        if instance_numa_topology:
            guest_cpu_numa = vconfig.LibvirtConfigGuestCPUNUMA()
            for instance_cell in instance_numa_topology.cells:
                guest_cell = vconfig.LibvirtConfigGuestCPUNUMACell()
                guest_cell.id = instance_cell.id
                guest_cell.cpus = instance_cell.cpuset
                guest_cell.memory = instance_cell.memory * units.Ki

                # The vhost-user network backend requires file backed
                # guest memory (ie huge pages) to be marked as shared
                # access, not private, so an external process can read
                # and write the pages.
                #
                # You can't change the shared vs private flag for an
                # already running guest, and since we can't predict what
                # types of NIC may be hotplugged, we have no choice but
                # to unconditionally turn on the shared flag. This has
                # no real negative functional effect on the guest, so
                # is a reasonable approach to take
                if wants_hugepages:
                    guest_cell.memAccess = "shared"
                guest_cpu_numa.cells.append(guest_cell)
            return guest_cpu_numa

    def _has_cpu_policy_support(self):
        for ver in BAD_LIBVIRT_CPU_POLICY_VERSIONS:
            if self._host.has_version(ver):
                ver_ = self._version_to_string(ver)
                raise exception.CPUPinningNotSupported(reason=_(
                    'Invalid libvirt version %(version)s') % {'version': ver_})
        return True

    def _wants_hugepages(self, host_topology, instance_topology):
        """Determine if the guest / host topology implies the
           use of huge pages for guest RAM backing
        """

        if host_topology is None or instance_topology is None:
            return False

        avail_pagesize = [page.size_kb
                          for page in host_topology.cells[0].mempages]
        avail_pagesize.sort()
        # Remove smallest page size as that's not classed as a largepage
        avail_pagesize = avail_pagesize[1:]

        # See if we have page size set
        for cell in instance_topology.cells:
            if (cell.pagesize is not None and
                cell.pagesize in avail_pagesize):
                return True

        return False

    def _get_guest_numa_config(self, instance_numa_topology, flavor,
                               allowed_cpus=None, image_meta=None):
        """Returns the config objects for the guest NUMA specs.

        Determines the CPUs that the guest can be pinned to if the guest
        specifies a cell topology and the host supports it. Constructs the
        libvirt XML config object representing the NUMA topology selected
        for the guest. Returns a tuple of:

            (cpu_set, guest_cpu_tune, guest_cpu_numa, guest_numa_tune)

        With the following caveats:

            a) If there is no specified guest NUMA topology, then
               all tuple elements except cpu_set shall be None. cpu_set
               will be populated with the chosen CPUs that the guest
               allowed CPUs fit within, which could be the supplied
               allowed_cpus value if the host doesn't support NUMA
               topologies.

            b) If there is a specified guest NUMA topology, then
               cpu_set will be None and guest_cpu_numa will be the
               LibvirtConfigGuestCPUNUMA object representing the guest's
               NUMA topology. If the host supports NUMA, then guest_cpu_tune
               will contain a LibvirtConfigGuestCPUTune object representing
               the optimized chosen cells that match the host capabilities
               with the instance's requested topology. If the host does
               not support NUMA, then guest_cpu_tune and guest_numa_tune
               will be None.
        """

        if (not self._has_numa_support() and
                instance_numa_topology is not None):
            # We should not get here, since we should have avoided
            # reporting NUMA topology from _get_host_numa_topology
            # in the first place. Just in case of a scheduler
            # mess up though, raise an exception
            raise exception.NUMATopologyUnsupported()

        topology = self._get_host_numa_topology()

        # We have instance NUMA so translate it to the config class
        guest_cpu_numa_config = self._get_cpu_numa_config_from_instance(
                instance_numa_topology,
                self._wants_hugepages(topology, instance_numa_topology))

        if not guest_cpu_numa_config:
            # No NUMA topology defined for instance - let the host kernel deal
            # with the NUMA effects.
            # TODO(ndipanov): Attempt to spread the instance
            # across NUMA nodes and expose the topology to the
            # instance as an optimisation
            return GuestNumaConfig(allowed_cpus, None, None, None)
        else:
            if topology:
                # Now get the CpuTune configuration from the numa_topology
                guest_cpu_tune = vconfig.LibvirtConfigGuestCPUTune()
                guest_numa_tune = vconfig.LibvirtConfigGuestNUMATune()
                emupcpus = []

                numa_mem = vconfig.LibvirtConfigGuestNUMATuneMemory()
                numa_memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()
                                 for _ in guest_cpu_numa_config.cells]

                emulator_threads_isolated = (
                    instance_numa_topology.emulator_threads_isolated)

                vcpus_rt = set([])
                wants_realtime = hardware.is_realtime_enabled(flavor)
                if wants_realtime:
                    if not self._host.has_min_version(
                            MIN_LIBVIRT_REALTIME_VERSION):
                        raise exception.RealtimePolicyNotSupported()
                    # Prepare realtime config for libvirt
                    vcpus_rt = hardware.vcpus_realtime_topology(
                        flavor, image_meta)
                    vcpusched = vconfig.LibvirtConfigGuestCPUTuneVCPUSched()
                    vcpusched.vcpus = vcpus_rt
                    vcpusched.scheduler = "fifo"
                    vcpusched.priority = (
                        CONF.libvirt.realtime_scheduler_priority)
                    guest_cpu_tune.vcpusched.append(vcpusched)

                # TODO(sahid): Defining domain topology should be
                # refactored.
                for host_cell in topology.cells:
                    for guest_node_id, guest_config_cell in enumerate(
                            guest_cpu_numa_config.cells):
                        if guest_config_cell.id == host_cell.id:
                            node = numa_memnodes[guest_node_id]
                            node.cellid = guest_node_id
                            node.nodeset = [host_cell.id]
                            node.mode = "strict"

                            numa_mem.nodeset.append(host_cell.id)

                            object_numa_cell = (
                                    instance_numa_topology.cells[guest_node_id]
                                )
                            for cpu in guest_config_cell.cpus:
                                pin_cpuset = (
                                    vconfig.LibvirtConfigGuestCPUTuneVCPUPin())
                                pin_cpuset.id = cpu
                                # If there is pinning information in the cell
                                # we pin to individual CPUs, otherwise we float
                                # over the whole host NUMA node

                                if (object_numa_cell.cpu_pinning and
                                        self._has_cpu_policy_support()):
                                    pcpu = object_numa_cell.cpu_pinning[cpu]
                                    pin_cpuset.cpuset = set([pcpu])
                                else:
                                    pin_cpuset.cpuset = host_cell.cpuset
                                if emulator_threads_isolated:
                                    if object_numa_cell.cpuset_reserved:
                                        emupcpus.extend(
                                            object_numa_cell.cpuset_reserved)
                                elif not wants_realtime or cpu not in vcpus_rt:
                                    # - If realtime IS NOT enabled, the
                                    #   emulator threads are allowed to float
                                    #   across all the pCPUs associated with
                                    #   the guest vCPUs ("not wants_realtime"
                                    #   is true, so we add all pcpus)
                                    # - If realtime IS enabled, then at least
                                    #   1 vCPU is required to be set aside for
                                    #   non-realtime usage. The emulator
                                    #   threads are allowed to float acros the
                                    #   pCPUs that are associated with the
                                    #   non-realtime VCPUs (the "cpu not in
                                    #   vcpu_rt" check deals with this
                                    #   filtering)
                                    emupcpus.extend(pin_cpuset.cpuset)
                                guest_cpu_tune.vcpupin.append(pin_cpuset)

                # TODO(berrange) When the guest has >1 NUMA node, it will
                # span multiple host NUMA nodes. By pinning emulator threads
                # to the union of all nodes, we guarantee there will be
                # cross-node memory access by the emulator threads when
                # responding to guest I/O operations. The only way to avoid
                # this would be to pin emulator threads to a single node and
                # tell the guest OS to only do I/O from one of its virtual
                # NUMA nodes. This is not even remotely practical.
                #
                # The long term solution is to make use of a new QEMU feature
                # called "I/O Threads" which will let us configure an explicit
                # I/O thread for each guest vCPU or guest NUMA node. It is
                # still TBD how to make use of this feature though, especially
                # how to associate IO threads with guest devices to eliminate
                # cross NUMA node traffic. This is an area of investigation
                # for QEMU community devs.
                emulatorpin = vconfig.LibvirtConfigGuestCPUTuneEmulatorPin()
                emulatorpin.cpuset = set(emupcpus)
                guest_cpu_tune.emulatorpin = emulatorpin
                # Sort the vcpupin list per vCPU id for human-friendlier XML
                guest_cpu_tune.vcpupin.sort(key=operator.attrgetter("id"))

                guest_numa_tune.memory = numa_mem
                guest_numa_tune.memnodes = numa_memnodes

                # normalize cell.id
                for i, (cell, memnode) in enumerate(
                                            zip(guest_cpu_numa_config.cells,
                                                guest_numa_tune.memnodes)):
                    cell.id = i
                    memnode.cellid = i

                return GuestNumaConfig(None, guest_cpu_tune,
                                       guest_cpu_numa_config,
                                       guest_numa_tune)
            else:
                return GuestNumaConfig(allowed_cpus, None,
                                       guest_cpu_numa_config, None)

    def _get_guest_os_type(self, virt_type):
        """Returns the guest OS type based on virt type."""
        if virt_type == "lxc":
            ret = fields.VMMode.EXE
        elif virt_type == "uml":
            ret = fields.VMMode.UML
        elif virt_type == "xen":
            ret = fields.VMMode.XEN
        else:
            ret = fields.VMMode.HVM
        return ret

    def _set_guest_for_rescue(self, rescue, guest, inst_path, virt_type,
                              root_device_name):
        if rescue.get('kernel_id'):
            guest.os_kernel = os.path.join(inst_path, "kernel.rescue")
            guest.os_cmdline = ("root=%s %s" % (root_device_name, CONSOLE))
            if virt_type == "qemu":
                guest.os_cmdline += " no_timer_check"
        if rescue.get('ramdisk_id'):
            guest.os_initrd = os.path.join(inst_path, "ramdisk.rescue")

    def _set_guest_for_inst_kernel(self, instance, guest, inst_path, virt_type,
                                root_device_name, image_meta):
        guest.os_kernel = os.path.join(inst_path, "kernel")
        guest.os_cmdline = ("root=%s %s" % (root_device_name, CONSOLE))
        if virt_type == "qemu":
            guest.os_cmdline += " no_timer_check"
        if instance.ramdisk_id:
            guest.os_initrd = os.path.join(inst_path, "ramdisk")
        # we only support os_command_line with images with an explicit
        # kernel set and don't want to break nova if there's an
        # os_command_line property without a specified kernel_id param
        if image_meta.properties.get("os_command_line"):
            guest.os_cmdline = image_meta.properties.os_command_line

    def _set_clock(self, guest, os_type, image_meta, virt_type):
        # NOTE(mikal): Microsoft Windows expects the clock to be in
        # "localtime". If the clock is set to UTC, then you can use a
        # registry key to let windows know, but Microsoft says this is
        # buggy in http://support.microsoft.com/kb/2687252
        clk = vconfig.LibvirtConfigGuestClock()
        if os_type == 'windows':
            LOG.info('Configuring timezone for windows instance to localtime')
            clk.offset = 'localtime'
        else:
            clk.offset = 'utc'
        guest.set_clock(clk)

        if virt_type == "kvm":
            self._set_kvm_timers(clk, os_type, image_meta)

    def _set_kvm_timers(self, clk, os_type, image_meta):
        # TODO(berrange) One day this should be per-guest
        # OS type configurable
        tmpit = vconfig.LibvirtConfigGuestTimer()
        tmpit.name = "pit"
        tmpit.tickpolicy = "delay"

        tmrtc = vconfig.LibvirtConfigGuestTimer()
        tmrtc.name = "rtc"
        tmrtc.tickpolicy = "catchup"

        clk.add_timer(tmpit)
        clk.add_timer(tmrtc)

        guestarch = libvirt_utils.get_arch(image_meta)
        if guestarch in (fields.Architecture.I686,
                         fields.Architecture.X86_64):
            # NOTE(rfolco): HPET is a hardware timer for x86 arch.
            # qemu -no-hpet is not supported on non-x86 targets.
            tmhpet = vconfig.LibvirtConfigGuestTimer()
            tmhpet.name = "hpet"
            tmhpet.present = False
            clk.add_timer(tmhpet)

        # Provide Windows guests with the paravirtualized hyperv timer source.
        # This is the windows equiv of kvm-clock, allowing Windows
        # guests to accurately keep time.
        if os_type == 'windows':
            tmhyperv = vconfig.LibvirtConfigGuestTimer()
            tmhyperv.name = "hypervclock"
            tmhyperv.present = True
            clk.add_timer(tmhyperv)

    def _set_features(self, guest, os_type, caps, virt_type, image_meta):
        if virt_type == "xen":
            # PAE only makes sense in X86
            if caps.host.cpu.arch in (fields.Architecture.I686,
                                      fields.Architecture.X86_64):
                guest.features.append(vconfig.LibvirtConfigGuestFeaturePAE())

        if (virt_type not in ("lxc", "uml", "parallels", "xen") or
                (virt_type == "xen" and guest.os_type == fields.VMMode.HVM)):
            guest.features.append(vconfig.LibvirtConfigGuestFeatureACPI())
            guest.features.append(vconfig.LibvirtConfigGuestFeatureAPIC())

        if (virt_type in ("qemu", "kvm") and
                os_type == 'windows'):
            hv = vconfig.LibvirtConfigGuestFeatureHyperV()
            hv.relaxed = True

            hv.spinlocks = True
            # Increase spinlock retries - value recommended by
            # KVM maintainers who certify Windows guests
            # with Microsoft
            hv.spinlock_retries = 8191
            hv.vapic = True
            guest.features.append(hv)

        if (virt_type in ("qemu", "kvm") and
                image_meta.properties.get('img_hide_hypervisor_id')):
            guest.features.append(vconfig.LibvirtConfigGuestFeatureKvmHidden())

    def _check_number_of_serial_console(self, num_ports):
        virt_type = CONF.libvirt.virt_type
        if (virt_type in ("kvm", "qemu") and
            num_ports > ALLOWED_QEMU_SERIAL_PORTS):
            raise exception.SerialPortNumberLimitExceeded(
                allowed=ALLOWED_QEMU_SERIAL_PORTS, virt_type=virt_type)

    def _add_video_driver(self, guest, image_meta, flavor):
        VALID_VIDEO_DEVICES = ("vga", "cirrus", "vmvga", "xen", "qxl")
        video = vconfig.LibvirtConfigGuestVideo()
        # NOTE(ldbragst): The following logic sets the video.type
        # depending on supported defaults given the architecture,
        # virtualization type, and features. The video.type attribute can
        # be overridden by the user with image_meta.properties, which
        # is carried out in the next if statement below this one.
        guestarch = libvirt_utils.get_arch(image_meta)
        if guest.os_type == fields.VMMode.XEN:
            video.type = 'xen'
        elif CONF.libvirt.virt_type == 'parallels':
            video.type = 'vga'
        elif guestarch in (fields.Architecture.PPC,
                           fields.Architecture.PPC64,
                           fields.Architecture.PPC64LE):
            # NOTE(ldbragst): PowerKVM doesn't support 'cirrus' be default
            # so use 'vga' instead when running on Power hardware.
            video.type = 'vga'
        elif CONF.spice.enabled:
            video.type = 'qxl'
        if image_meta.properties.get('hw_video_model'):
            video.type = image_meta.properties.hw_video_model
            if (video.type not in VALID_VIDEO_DEVICES):
                raise exception.InvalidVideoMode(model=video.type)

        # Set video memory, only if the flavor's limit is set
        video_ram = image_meta.properties.get('hw_video_ram', 0)
        max_vram = int(flavor.extra_specs.get('hw_video:ram_max_mb', 0))
        if video_ram > max_vram:
            raise exception.RequestedVRamTooHigh(req_vram=video_ram,
                                                 max_vram=max_vram)
        if max_vram and video_ram:
            video.vram = video_ram * units.Mi / units.Ki
        guest.add_device(video)

    def _add_qga_device(self, guest, instance):
        qga = vconfig.LibvirtConfigGuestChannel()
        qga.type = "unix"
        qga.target_name = "org.qemu.guest_agent.0"
        qga.source_path = ("/var/lib/libvirt/qemu/%s.%s.sock" %
                          ("org.qemu.guest_agent.0", instance.name))
        guest.add_device(qga)

    def _add_rng_device(self, guest, flavor):
        rng_device = vconfig.LibvirtConfigGuestRng()
        rate_bytes = flavor.extra_specs.get('hw_rng:rate_bytes', 0)
        period = flavor.extra_specs.get('hw_rng:rate_period', 0)
        if rate_bytes:
            rng_device.rate_bytes = int(rate_bytes)
            rng_device.rate_period = int(period)
        rng_path = CONF.libvirt.rng_dev_path
        if (rng_path and not os.path.exists(rng_path)):
            raise exception.RngDeviceNotExist(path=rng_path)
        rng_device.backend = rng_path
        guest.add_device(rng_device)

    def _set_qemu_guest_agent(self, guest, flavor, instance, image_meta):
        # Enable qga only if the 'hw_qemu_guest_agent' is equal to yes
        if image_meta.properties.get('hw_qemu_guest_agent', False):
            LOG.debug("Qemu guest agent is enabled through image "
                      "metadata", instance=instance)
            self._add_qga_device(guest, instance)
        rng_is_virtio = image_meta.properties.get('hw_rng_model') == 'virtio'
        rng_allowed_str = flavor.extra_specs.get('hw_rng:allowed', '')
        rng_allowed = strutils.bool_from_string(rng_allowed_str)
        if rng_is_virtio and rng_allowed:
            self._add_rng_device(guest, flavor)

    def _get_guest_memory_backing_config(
            self, inst_topology, numatune, flavor):
        wantsmempages = False
        if inst_topology:
            for cell in inst_topology.cells:
                if cell.pagesize:
                    wantsmempages = True
                    break

        wantsrealtime = hardware.is_realtime_enabled(flavor)

        membacking = None
        if wantsmempages:
            pages = self._get_memory_backing_hugepages_support(
                inst_topology, numatune)
            if pages:
                membacking = vconfig.LibvirtConfigGuestMemoryBacking()
                membacking.hugepages = pages
        if wantsrealtime:
            if not membacking:
                membacking = vconfig.LibvirtConfigGuestMemoryBacking()
            membacking.locked = True
            membacking.sharedpages = False

        return membacking

    def _get_memory_backing_hugepages_support(self, inst_topology, numatune):
        if not self._has_numa_support():
            # We should not get here, since we should have avoided
            # reporting NUMA topology from _get_host_numa_topology
            # in the first place. Just in case of a scheduler
            # mess up though, raise an exception
            raise exception.MemoryPagesUnsupported()

        host_topology = self._get_host_numa_topology()

        if host_topology is None:
            # As above, we should not get here but just in case...
            raise exception.MemoryPagesUnsupported()

        # Currently libvirt does not support the smallest
        # pagesize set as a backend memory.
        # https://bugzilla.redhat.com/show_bug.cgi?id=1173507
        avail_pagesize = [page.size_kb
                          for page in host_topology.cells[0].mempages]
        avail_pagesize.sort()
        smallest = avail_pagesize[0]

        pages = []
        for guest_cellid, inst_cell in enumerate(inst_topology.cells):
            if inst_cell.pagesize and inst_cell.pagesize > smallest:
                for memnode in numatune.memnodes:
                    if guest_cellid == memnode.cellid:
                        page = (
                            vconfig.LibvirtConfigGuestMemoryBackingPage())
                        page.nodeset = [guest_cellid]
                        page.size_kb = inst_cell.pagesize
                        pages.append(page)
                        break  # Quit early...
        return pages

    def _get_flavor(self, ctxt, instance, flavor):
        if flavor is not None:
            return flavor
        return instance.flavor

    def _has_uefi_support(self):
        # This means that the host can support uefi booting for guests
        supported_archs = [fields.Architecture.X86_64,
                           fields.Architecture.AARCH64]
        caps = self._host.get_capabilities()
        return ((caps.host.cpu.arch in supported_archs) and
                os.path.exists(DEFAULT_UEFI_LOADER_PATH[caps.host.cpu.arch]))

    def _get_supported_perf_events(self):

        if (len(CONF.libvirt.enabled_perf_events) == 0 or
             not self._host.has_min_version(MIN_LIBVIRT_PERF_VERSION)):
            return []

        supported_events = []
        host_cpu_info = self._get_cpu_info()
        for event in CONF.libvirt.enabled_perf_events:
            if self._supported_perf_event(event, host_cpu_info['features']):
                supported_events.append(event)
        return supported_events

    def _supported_perf_event(self, event, cpu_features):

        libvirt_perf_event_name = LIBVIRT_PERF_EVENT_PREFIX + event.upper()

        if not hasattr(libvirt, libvirt_perf_event_name):
            LOG.warning("Libvirt doesn't support event type %s.", event)
            return False

        if (event in PERF_EVENTS_CPU_FLAG_MAPPING
            and PERF_EVENTS_CPU_FLAG_MAPPING[event] not in cpu_features):
            LOG.warning("Host does not support event type %s.", event)
            return False

        return True

    def _configure_guest_by_virt_type(self, guest, virt_type, caps, instance,
                                      image_meta, flavor, root_device_name):
        if virt_type == "xen":
            if guest.os_type == fields.VMMode.HVM:
                guest.os_loader = CONF.libvirt.xen_hvmloader_path
            else:
                guest.os_cmdline = CONSOLE
        elif virt_type in ("kvm", "qemu"):
            if caps.host.cpu.arch in (fields.Architecture.I686,
                                      fields.Architecture.X86_64):
                guest.sysinfo = self._get_guest_config_sysinfo(instance)
                guest.os_smbios = vconfig.LibvirtConfigGuestSMBIOS()
            hw_firmware_type = image_meta.properties.get('hw_firmware_type')
            if caps.host.cpu.arch == fields.Architecture.AARCH64:
                if not hw_firmware_type:
                    hw_firmware_type = fields.FirmwareType.UEFI
            if hw_firmware_type == fields.FirmwareType.UEFI:
                if self._has_uefi_support():
                    global uefi_logged
                    if not uefi_logged:
                        LOG.warning("uefi support is without some kind of "
                                    "functional testing and therefore "
                                    "considered experimental.")
                        uefi_logged = True
                    guest.os_loader = DEFAULT_UEFI_LOADER_PATH[
                        caps.host.cpu.arch]
                    guest.os_loader_type = "pflash"
                else:
                    raise exception.UEFINotSupported()
            guest.os_mach_type = self._get_machine_type(image_meta, caps)
            if image_meta.properties.get('hw_boot_menu') is None:
                guest.os_bootmenu = strutils.bool_from_string(
                    flavor.extra_specs.get('hw:boot_menu', 'no'))
            else:
                guest.os_bootmenu = image_meta.properties.hw_boot_menu

        elif virt_type == "lxc":
            guest.os_init_path = "/sbin/init"
            guest.os_cmdline = CONSOLE
        elif virt_type == "uml":
            guest.os_kernel = "/usr/bin/linux"
            guest.os_root = root_device_name
        elif virt_type == "parallels":
            if guest.os_type == fields.VMMode.EXE:
                guest.os_init_path = "/sbin/init"

    def _conf_non_lxc_uml(self, virt_type, guest, root_device_name, rescue,
                    instance, inst_path, image_meta, disk_info):
        if rescue:
            self._set_guest_for_rescue(rescue, guest, inst_path, virt_type,
                                       root_device_name)
        elif instance.kernel_id:
            self._set_guest_for_inst_kernel(instance, guest, inst_path,
                                            virt_type, root_device_name,
                                            image_meta)
        else:
            guest.os_boot_dev = blockinfo.get_boot_order(disk_info)

    def _create_consoles(self, virt_type, guest_cfg, instance, flavor,
                         image_meta):
        # NOTE(markus_z): Beware! Below are so many conditionals that it is
        # easy to lose track. Use this chart to figure out your case:
        #
        # case | is serial | has       | is qemu | resulting
        #      | enabled?  | virtlogd? | or kvm? | devices
        # --------------------------------------------------
        #    1 |        no |        no |     no  | pty*
        #    2 |        no |        no |     yes | file + pty
        #    3 |        no |       yes |      no | see case 1
        #    4 |        no |       yes |     yes | pty with logd
        #    5 |       yes |        no |      no | see case 1
        #    6 |       yes |        no |     yes | tcp + pty
        #    7 |       yes |       yes |      no | see case 1
        #    8 |       yes |       yes |     yes | tcp with logd
        #    * exception: virt_type "parallels" doesn't create a device
        if virt_type == 'parallels':
            pass
        elif virt_type not in ("qemu", "kvm"):
            log_path = self._get_console_log_path(instance)
            self._create_pty_device(guest_cfg,
                                    vconfig.LibvirtConfigGuestConsole,
                                    log_path=log_path)
        elif (virt_type in ("qemu", "kvm") and
                  self._is_s390x_guest(image_meta)):
            self._create_consoles_s390x(guest_cfg, instance,
                                        flavor, image_meta)
        elif virt_type in ("qemu", "kvm"):
            self._create_consoles_qemu_kvm(guest_cfg, instance,
                                        flavor, image_meta)

    def _is_s390x_guest(self, image_meta):
        s390x_archs = (fields.Architecture.S390, fields.Architecture.S390X)
        return libvirt_utils.get_arch(image_meta) in s390x_archs

    def _create_consoles_qemu_kvm(self, guest_cfg, instance, flavor,
                                  image_meta):
        char_dev_cls = vconfig.LibvirtConfigGuestSerial
        log_path = self._get_console_log_path(instance)
        if CONF.serial_console.enabled:
            if not self._serial_ports_already_defined(instance):
                num_ports = hardware.get_number_of_serial_ports(flavor,
                                                                image_meta)
                self._check_number_of_serial_console(num_ports)
                self._create_serial_consoles(guest_cfg, num_ports,
                                             char_dev_cls, log_path)
        else:
            self._create_file_device(guest_cfg, instance, char_dev_cls)
        self._create_pty_device(guest_cfg, char_dev_cls, log_path=log_path)

    def _create_consoles_s390x(self, guest_cfg, instance, flavor, image_meta):
        char_dev_cls = vconfig.LibvirtConfigGuestConsole
        log_path = self._get_console_log_path(instance)
        if CONF.serial_console.enabled:
            if not self._serial_ports_already_defined(instance):
                num_ports = hardware.get_number_of_serial_ports(flavor,
                                                                image_meta)
                self._create_serial_consoles(guest_cfg, num_ports,
                                             char_dev_cls, log_path)
        else:
            self._create_file_device(guest_cfg, instance, char_dev_cls,
                                     "sclplm")
        self._create_pty_device(guest_cfg, char_dev_cls, "sclp", log_path)

    def _create_pty_device(self, guest_cfg, char_dev_cls, target_type=None,
                           log_path=None):
        def _create_base_dev():
            consolepty = char_dev_cls()
            consolepty.target_type = target_type
            consolepty.type = "pty"
            return consolepty

        def _create_logd_dev():
            consolepty = _create_base_dev()
            log = vconfig.LibvirtConfigGuestCharDeviceLog()
            log.file = log_path
            consolepty.log = log
            return consolepty

        if CONF.serial_console.enabled:
            if self._is_virtlogd_available():
                return
            else:
                # NOTE(markus_z): You may wonder why this is necessary and
                # so do I. I'm certain that this is *not* needed in any
                # real use case. It is, however, useful if you want to
                # pypass the Nova API and use "virsh console <guest>" on
                # an hypervisor, as this CLI command doesn't work with TCP
                # devices (like the serial console is).
                #     https://bugzilla.redhat.com/show_bug.cgi?id=781467
                # Pypassing the Nova API however is a thing we don't want.
                # Future changes should remove this and fix the unit tests
                # which ask for the existence.
                guest_cfg.add_device(_create_base_dev())
        else:
            if self._is_virtlogd_available():
                guest_cfg.add_device(_create_logd_dev())
            else:
                guest_cfg.add_device(_create_base_dev())

    def _create_file_device(self, guest_cfg, instance, char_dev_cls,
                            target_type=None):
        if self._is_virtlogd_available():
            return

        consolelog = char_dev_cls()
        consolelog.target_type = target_type
        consolelog.type = "file"
        consolelog.source_path = self._get_console_log_path(instance)
        guest_cfg.add_device(consolelog)

    def _serial_ports_already_defined(self, instance):
        try:
            guest = self._host.get_guest(instance)
            if list(self._get_serial_ports_from_guest(guest)):
                # Serial port are already configured for instance that
                # means we are in a context of migration.
                return True
        except exception.InstanceNotFound:
            LOG.debug(
                "Instance does not exist yet on libvirt, we can "
                "safely pass on looking for already defined serial "
                "ports in its domain XML", instance=instance)
        return False

    def _create_serial_consoles(self, guest_cfg, num_ports, char_dev_cls,
                                log_path):
        for port in six.moves.range(num_ports):
            console = char_dev_cls()
            console.port = port
            console.type = "tcp"
            console.listen_host = CONF.serial_console.proxyclient_address
            listen_port = serial_console.acquire_port(console.listen_host)
            console.listen_port = listen_port
            # NOTE: only the first serial console gets the boot messages,
            # that's why we attach the logd subdevice only to that.
            if port == 0 and self._is_virtlogd_available():
                log = vconfig.LibvirtConfigGuestCharDeviceLog()
                log.file = log_path
                console.log = log
            guest_cfg.add_device(console)

    def _cpu_config_to_vcpu_model(self, cpu_config, vcpu_model):
        """Update VirtCPUModel object according to libvirt CPU config.

        :param:cpu_config: vconfig.LibvirtConfigGuestCPU presenting the
                           instance's virtual cpu configuration.
        :param:vcpu_model: VirtCPUModel object. A new object will be created
                           if None.

        :return: Updated VirtCPUModel object, or None if cpu_config is None

        """

        if not cpu_config:
            return
        if not vcpu_model:
            vcpu_model = objects.VirtCPUModel()

        vcpu_model.arch = cpu_config.arch
        vcpu_model.vendor = cpu_config.vendor
        vcpu_model.model = cpu_config.model
        vcpu_model.mode = cpu_config.mode
        vcpu_model.match = cpu_config.match

        if cpu_config.sockets:
            vcpu_model.topology = objects.VirtCPUTopology(
                sockets=cpu_config.sockets,
                cores=cpu_config.cores,
                threads=cpu_config.threads)
        else:
            vcpu_model.topology = None

        features = [objects.VirtCPUFeature(
            name=f.name,
            policy=f.policy) for f in cpu_config.features]
        vcpu_model.features = features

        return vcpu_model

    def _vcpu_model_to_cpu_config(self, vcpu_model):
        """Create libvirt CPU config according to VirtCPUModel object.

        :param:vcpu_model: VirtCPUModel object.

        :return: vconfig.LibvirtConfigGuestCPU.

        """

        cpu_config = vconfig.LibvirtConfigGuestCPU()
        cpu_config.arch = vcpu_model.arch
        cpu_config.model = vcpu_model.model
        cpu_config.mode = vcpu_model.mode
        cpu_config.match = vcpu_model.match
        cpu_config.vendor = vcpu_model.vendor
        if vcpu_model.topology:
            cpu_config.sockets = vcpu_model.topology.sockets
            cpu_config.cores = vcpu_model.topology.cores
            cpu_config.threads = vcpu_model.topology.threads
        if vcpu_model.features:
            for f in vcpu_model.features:
                xf = vconfig.LibvirtConfigGuestCPUFeature()
                xf.name = f.name
                xf.policy = f.policy
                cpu_config.features.add(xf)
        return cpu_config

    def _get_guest_config(self, instance, network_info, image_meta,
                          disk_info, rescue=None, block_device_info=None,
                          context=None):
        """Get config data for parameters.

        :param rescue: optional dictionary that should contain the key
            'ramdisk_id' if a ramdisk is needed for the rescue image and
            'kernel_id' if a kernel is needed for the rescue image.
        """
        flavor = instance.flavor
        inst_path = libvirt_utils.get_instance_path(instance)
        disk_mapping = disk_info['mapping']

        virt_type = CONF.libvirt.virt_type
        guest = vconfig.LibvirtConfigGuest()
        guest.virt_type = virt_type
        guest.name = instance.name
        guest.uuid = instance.uuid
        # We are using default unit for memory: KiB
        guest.memory = flavor.memory_mb * units.Ki
        guest.vcpus = flavor.vcpus
        allowed_cpus = hardware.get_vcpu_pin_set()

        guest_numa_config = self._get_guest_numa_config(
            instance.numa_topology, flavor, allowed_cpus, image_meta)

        guest.cpuset = guest_numa_config.cpuset
        guest.cputune = guest_numa_config.cputune
        guest.numatune = guest_numa_config.numatune

        guest.membacking = self._get_guest_memory_backing_config(
            instance.numa_topology,
            guest_numa_config.numatune,
            flavor)

        guest.metadata.append(self._get_guest_config_meta(instance))
        guest.idmaps = self._get_guest_idmaps()

        for event in self._supported_perf_events:
            guest.add_perf_event(event)

        self._update_guest_cputune(guest, flavor, virt_type)

        guest.cpu = self._get_guest_cpu_config(
            flavor, image_meta, guest_numa_config.numaconfig,
            instance.numa_topology)

        # Notes(yjiang5): we always sync the instance's vcpu model with
        # the corresponding config file.
        instance.vcpu_model = self._cpu_config_to_vcpu_model(
            guest.cpu, instance.vcpu_model)

        if 'root' in disk_mapping:
            root_device_name = block_device.prepend_dev(
                disk_mapping['root']['dev'])
        else:
            root_device_name = None

        if root_device_name:
            # NOTE(yamahata):
            # for nova.api.ec2.cloud.CloudController.get_metadata()
            instance.root_device_name = root_device_name

        guest.os_type = (fields.VMMode.get_from_instance(instance) or
                self._get_guest_os_type(virt_type))
        caps = self._host.get_capabilities()

        self._configure_guest_by_virt_type(guest, virt_type, caps, instance,
                                           image_meta, flavor,
                                           root_device_name)
        if virt_type not in ('lxc', 'uml'):
            self._conf_non_lxc_uml(virt_type, guest, root_device_name, rescue,
                    instance, inst_path, image_meta, disk_info)

        self._set_features(guest, instance.os_type, caps, virt_type,
                           image_meta)
        self._set_clock(guest, instance.os_type, image_meta, virt_type)

        storage_configs = self._get_guest_storage_config(
                instance, image_meta, disk_info, rescue, block_device_info,
                flavor, guest.os_type)
        for config in storage_configs:
            guest.add_device(config)

        for vif in network_info:
            config = self.vif_driver.get_config(
                instance, vif, image_meta,
                flavor, virt_type, self._host)
            guest.add_device(config)

        self._create_consoles(virt_type, guest, instance, flavor, image_meta)

        pointer = self._get_guest_pointer_model(guest.os_type, image_meta)
        if pointer:
            guest.add_device(pointer)

        self._guest_add_spice_channel(guest)

        if self._guest_add_video_device(guest):
            self._add_video_driver(guest, image_meta, flavor)

        # Qemu guest agent only support 'qemu' and 'kvm' hypervisor
        if virt_type in ('qemu', 'kvm'):
            self._set_qemu_guest_agent(guest, flavor, instance, image_meta)

        self._guest_add_pci_devices(guest, instance)

        self._guest_add_watchdog_action(guest, flavor, image_meta)

        self._guest_add_memory_balloon(guest)

        return guest

    @staticmethod
    def _guest_add_spice_channel(guest):
        if (CONF.spice.enabled and CONF.spice.agent_enabled
                and guest.virt_type not in ('lxc', 'uml', 'xen')):
            channel = vconfig.LibvirtConfigGuestChannel()
            channel.type = 'spicevmc'
            channel.target_name = "com.redhat.spice.0"
            guest.add_device(channel)

    @staticmethod
    def _guest_add_memory_balloon(guest):
        virt_type = guest.virt_type
        # Memory balloon device only support 'qemu/kvm' and 'xen' hypervisor
        if (virt_type in ('xen', 'qemu', 'kvm') and
                    CONF.libvirt.mem_stats_period_seconds > 0):
            balloon = vconfig.LibvirtConfigMemoryBalloon()
            if virt_type in ('qemu', 'kvm'):
                balloon.model = 'virtio'
            else:
                balloon.model = 'xen'
            balloon.period = CONF.libvirt.mem_stats_period_seconds
            guest.add_device(balloon)

    @staticmethod
    def _guest_add_watchdog_action(guest, flavor, image_meta):
        # image meta takes precedence over flavor extra specs; disable the
        # watchdog action by default
        watchdog_action = (flavor.extra_specs.get('hw:watchdog_action')
                           or 'disabled')
        watchdog_action = image_meta.properties.get('hw_watchdog_action',
                                                    watchdog_action)
        # NB(sross): currently only actually supported by KVM/QEmu
        if watchdog_action != 'disabled':
            if watchdog_action in fields.WatchdogAction.ALL:
                bark = vconfig.LibvirtConfigGuestWatchdog()
                bark.action = watchdog_action
                guest.add_device(bark)
            else:
                raise exception.InvalidWatchdogAction(action=watchdog_action)

    def _guest_add_pci_devices(self, guest, instance):
        virt_type = guest.virt_type
        if virt_type in ('xen', 'qemu', 'kvm'):
            # Get all generic PCI devices (non-SR-IOV).
            for pci_dev in pci_manager.get_instance_pci_devs(instance):
                guest.add_device(self._get_guest_pci_device(pci_dev))
        else:
            # PCI devices is only supported for hypervisors
            #  'xen', 'qemu' and 'kvm'.
            if pci_manager.get_instance_pci_devs(instance, 'all'):
                raise exception.PciDeviceUnsupportedHypervisor(type=virt_type)

    @staticmethod
    def _guest_add_video_device(guest):
        # NB some versions of libvirt support both SPICE and VNC
        # at the same time. We're not trying to second guess which
        # those versions are. We'll just let libvirt report the
        # errors appropriately if the user enables both.
        add_video_driver = False
        if CONF.vnc.enabled and guest.virt_type not in ('lxc', 'uml'):
            graphics = vconfig.LibvirtConfigGuestGraphics()
            graphics.type = "vnc"
            if CONF.vnc.keymap:
                # TODO(stephenfin): There are some issues here that may
                # necessitate deprecating this option entirely in the future.
                # Refer to bug #1682020 for more information.
                graphics.keymap = CONF.vnc.keymap
            graphics.listen = CONF.vnc.vncserver_listen
            guest.add_device(graphics)
            add_video_driver = True
        if CONF.spice.enabled and guest.virt_type not in ('lxc', 'uml', 'xen'):
            graphics = vconfig.LibvirtConfigGuestGraphics()
            graphics.type = "spice"
            if CONF.spice.keymap:
                # TODO(stephenfin): There are some issues here that may
                # necessitate deprecating this option entirely in the future.
                # Refer to bug #1682020 for more information.
                graphics.keymap = CONF.spice.keymap
            graphics.listen = CONF.spice.server_listen
            guest.add_device(graphics)
            add_video_driver = True
        return add_video_driver

    def _get_guest_pointer_model(self, os_type, image_meta):
        pointer_model = image_meta.properties.get(
            'hw_pointer_model', CONF.pointer_model)
        if pointer_model is None and CONF.libvirt.use_usb_tablet:
            # TODO(sahid): We set pointer_model to keep compatibility
            # until the next release O*. It means operators can continue
            # to use the deprecated option "use_usb_tablet" or set a
            # specific device to use
            pointer_model = "usbtablet"
            LOG.warning('The option "use_usb_tablet" has been '
                        'deprecated for Newton in favor of the more '
                        'generic "pointer_model". Please update '
                        'nova.conf to address this change.')

        if pointer_model == "usbtablet":
            # We want a tablet if VNC is enabled, or SPICE is enabled and
            # the SPICE agent is disabled. If the SPICE agent is enabled
            # it provides a paravirt mouse which drastically reduces
            # overhead (by eliminating USB polling).
            if CONF.vnc.enabled or (
                    CONF.spice.enabled and not CONF.spice.agent_enabled):
                return self._get_guest_usb_tablet(os_type)
            else:
                if CONF.pointer_model or CONF.libvirt.use_usb_tablet:
                    # For backward compatibility We don't want to break
                    # process of booting an instance if host is configured
                    # to use USB tablet without VNC or SPICE and SPICE
                    # agent disable.
                    LOG.warning('USB tablet requested for guests by host '
                                'configuration. In order to accept this '
                                'request VNC should be enabled or SPICE '
                                'and SPICE agent disabled on host.')
                else:
                    raise exception.UnsupportedPointerModelRequested(
                        model="usbtablet")

    def _get_guest_usb_tablet(self, os_type):
        tablet = None
        if os_type == fields.VMMode.HVM:
            tablet = vconfig.LibvirtConfigGuestInput()
            tablet.type = "tablet"
            tablet.bus = "usb"
        else:
            if CONF.pointer_model or CONF.libvirt.use_usb_tablet:
                # For backward compatibility We don't want to break
                # process of booting an instance if virtual machine mode
                # is not configured as HVM.
                LOG.warning('USB tablet requested for guests by host '
                            'configuration. In order to accept this '
                            'request the machine mode should be '
                            'configured as HVM.')
            else:
                raise exception.UnsupportedPointerModelRequested(
                    model="usbtablet")
        return tablet

    def _get_guest_xml(self, context, instance, network_info, disk_info,
                       image_meta, rescue=None,
                       block_device_info=None):
        # NOTE(danms): Stringifying a NetworkInfo will take a lock. Do
        # this ahead of time so that we don't acquire it while also
        # holding the logging lock.
        network_info_str = str(network_info)
        msg = ('Start _get_guest_xml '
               'network_info=%(network_info)s '
               'disk_info=%(disk_info)s '
               'image_meta=%(image_meta)s rescue=%(rescue)s '
               'block_device_info=%(block_device_info)s' %
               {'network_info': network_info_str, 'disk_info': disk_info,
                'image_meta': image_meta, 'rescue': rescue,
                'block_device_info': block_device_info})
        # NOTE(mriedem): block_device_info can contain auth_password so we
        # need to sanitize the password in the message.
        LOG.debug(strutils.mask_password(msg), instance=instance)
        conf = self._get_guest_config(instance, network_info, image_meta,
                                      disk_info, rescue, block_device_info,
                                      context)
        xml = conf.to_xml()

        LOG.debug('End _get_guest_xml xml=%(xml)s',
                  {'xml': xml}, instance=instance)
        return xml

    def get_info(self, instance):
        """Retrieve information from libvirt for a specific instance.

        If a libvirt error is encountered during lookup, we might raise a
        NotFound exception or Error exception depending on how severe the
        libvirt error is.

        :param instance: nova.objects.instance.Instance object
        :returns: An InstanceInfo object
        """
        guest = self._host.get_guest(instance)
        # Kind of ugly but we need to pass host to get_info as for a
        # workaround, see libvirt/compat.py
        return guest.get_info(self._host)

    def _create_domain_setup_lxc(self, instance, image_meta,
                                 block_device_info):
        inst_path = libvirt_utils.get_instance_path(instance)
        block_device_mapping = driver.block_device_info_get_mapping(
            block_device_info)
        root_disk = block_device.get_root_bdm(block_device_mapping)
        if root_disk:
            disk_info = blockinfo.get_info_from_bdm(
                instance, CONF.libvirt.virt_type, image_meta, root_disk)
            self._connect_volume(root_disk['connection_info'], disk_info,
                                 instance)
            disk_path = root_disk['connection_info']['data']['device_path']

            # NOTE(apmelton) - Even though the instance is being booted from a
            # cinder volume, it is still presented as a local block device.
            # LocalBlockImage is used here to indicate that the instance's
            # disk is backed by a local block device.
            image_model = imgmodel.LocalBlockImage(disk_path)
        else:
            root_disk = self.image_backend.by_name(instance, 'disk')
            image_model = root_disk.get_model(self._conn)

        container_dir = os.path.join(inst_path, 'rootfs')
        fileutils.ensure_tree(container_dir)
        rootfs_dev = disk_api.setup_container(image_model,
                                              container_dir=container_dir)

        try:
            # Save rootfs device to disconnect it when deleting the instance
            if rootfs_dev:
                instance.system_metadata['rootfs_device_name'] = rootfs_dev
            if CONF.libvirt.uid_maps or CONF.libvirt.gid_maps:
                id_maps = self._get_guest_idmaps()
                libvirt_utils.chown_for_id_maps(container_dir, id_maps)
        except Exception:
            with excutils.save_and_reraise_exception():
                self._create_domain_cleanup_lxc(instance)

    def _create_domain_cleanup_lxc(self, instance):
        inst_path = libvirt_utils.get_instance_path(instance)
        container_dir = os.path.join(inst_path, 'rootfs')

        try:
            state = self.get_info(instance).state
        except exception.InstanceNotFound:
            # The domain may not be present if the instance failed to start
            state = None

        if state == power_state.RUNNING:
            # NOTE(uni): Now the container is running with its own private
            # mount namespace and so there is no need to keep the container
            # rootfs mounted in the host namespace
            LOG.debug('Attempting to unmount container filesystem: %s',
                      container_dir, instance=instance)
            disk_api.clean_lxc_namespace(container_dir=container_dir)
        else:
            disk_api.teardown_container(container_dir=container_dir)

    @contextlib.contextmanager
    def _lxc_disk_handler(self, instance, image_meta, block_device_info):
        """Context manager to handle the pre and post instance boot,
           LXC specific disk operations.

           An image or a volume path will be prepared and setup to be
           used by the container, prior to starting it.
           The disk will be disconnected and unmounted if a container has
           failed to start.
        """

        if CONF.libvirt.virt_type != 'lxc':
            yield
            return

        self._create_domain_setup_lxc(instance, image_meta, block_device_info)

        try:
            yield
        finally:
            self._create_domain_cleanup_lxc(instance)

    # TODO(sahid): Consider renaming this to _create_guest.
    def _create_domain(self, xml=None, domain=None,
                       power_on=True, pause=False, post_xml_callback=None):
        """Create a domain.

        Either domain or xml must be passed in. If both are passed, then
        the domain definition is overwritten from the xml.

        :returns guest.Guest: Guest just created
        """
        if xml:
            guest = libvirt_guest.Guest.create(xml, self._host)
            if post_xml_callback is not None:
                post_xml_callback()
        else:
            guest = libvirt_guest.Guest(domain)

        if power_on or pause:
            guest.launch(pause=pause)

        if not utils.is_neutron():
            guest.enable_hairpin()

        return guest

    def _neutron_failed_callback(self, event_name, instance):
        LOG.error('Neutron Reported failure on event '
                  '%(event)s for instance %(uuid)s',
                  {'event': event_name, 'uuid': instance.uuid},
                  instance=instance)
        if CONF.vif_plugging_is_fatal:
            raise exception.VirtualInterfaceCreateException()

    def _neutron_failed_live_migration_callback(self, event_name, instance):
        msg = ('Neutron reported failure during live migration '
               'with %(event)s for instance %(uuid)s' %
               {'event': event_name, 'uuid': instance.uuid})
        raise exception.MigrationError(reason=msg)

    def _get_neutron_events(self, network_info):
        # NOTE(danms): We need to collect any VIFs that are currently
        # down that we expect a down->up event for. Anything that is
        # already up will not undergo that transition, and for
        # anything that might be stale (cache-wise) assume it's
        # already up so we don't block on it.
        return [('network-vif-plugged', vif['id'])
                for vif in network_info if vif.get('active', True) is False]

    def _get_neutron_events_for_live_migration(self, network_info):
        # Neutron should send events to Nova indicating that the VIFs
        # are successfully plugged on destination host.

        # TODO(sahid): Currently we only use the mechanism of waiting
        # for neutron events during live-migration for linux-bridge.
        return [('network-vif-plugged', vif['id'])
                for vif in network_info if (
                        vif.get('type') == network_model.VIF_TYPE_BRIDGE)]

    def _cleanup_failed_start(self, context, instance, network_info,
                              block_device_info, guest, destroy_disks):
        try:
            if guest and guest.is_active():
                guest.poweroff()
        finally:
            self.cleanup(context, instance, network_info=network_info,
                         block_device_info=block_device_info,
                         destroy_disks=destroy_disks)

    def _create_domain_and_network(self, context, xml, instance, network_info,
                                   block_device_info=None,
                                   power_on=True, reboot=False,
                                   vifs_already_plugged=False,
                                   post_xml_callback=None,
                                   destroy_disks_on_failure=False):

        """Do required network setup and create domain."""
        block_device_mapping = driver.block_device_info_get_mapping(
            block_device_info)

        for vol in block_device_mapping:
            connection_info = vol['connection_info']

            if (not reboot and 'data' in connection_info and
                    'volume_id' in connection_info['data']):
                volume_id = connection_info['data']['volume_id']
                encryption = encryptors.get_encryption_metadata(
                    context, self._volume_api, volume_id, connection_info)

                if encryption:
                    encryptor = self._get_volume_encryptor(connection_info,
                                                           encryption)
                    encryptor.attach_volume(context, **encryption)

        timeout = CONF.vif_plugging_timeout
        if (self._conn_supports_start_paused and
            utils.is_neutron() and not
            vifs_already_plugged and power_on and timeout):
            events = self._get_neutron_events(network_info)
        else:
            events = []

        pause = bool(events)
        guest = None
        try:
            with self.virtapi.wait_for_instance_event(
                    instance, events, deadline=timeout,
                    error_callback=self._neutron_failed_callback):
                self.plug_vifs(instance, network_info)
                self.firewall_driver.setup_basic_filtering(instance,
                                                           network_info)
                self.firewall_driver.prepare_instance_filter(instance,
                                                             network_info)
                with self._lxc_disk_handler(instance, instance.image_meta,
                                            block_device_info):
                    guest = self._create_domain(
                        xml, pause=pause, power_on=power_on,
                        post_xml_callback=post_xml_callback)

                self.firewall_driver.apply_instance_filter(instance,
                                                           network_info)
        except exception.VirtualInterfaceCreateException:
            # Neutron reported failure and we didn't swallow it, so
            # bail here
            with excutils.save_and_reraise_exception():
                self._cleanup_failed_start(context, instance, network_info,
                                           block_device_info, guest,
                                           destroy_disks_on_failure)
        except eventlet.timeout.Timeout:
            # We never heard from Neutron
            LOG.warning('Timeout waiting for vif plugging callback for '
                        'instance with vm_state %(vm_state)s and '
                        'task_state %(task_state)s.',
                        {'vm_state': instance.vm_state,
                         'task_state': instance.task_state},
                        instance=instance)
            if CONF.vif_plugging_is_fatal:
                self._cleanup_failed_start(context, instance, network_info,
                                           block_device_info, guest,
                                           destroy_disks_on_failure)
                raise exception.VirtualInterfaceCreateException()
        except Exception:
            # Any other error, be sure to clean up
            LOG.error('Failed to start libvirt guest', instance=instance)
            with excutils.save_and_reraise_exception():
                self._cleanup_failed_start(context, instance, network_info,
                                           block_device_info, guest,
                                           destroy_disks_on_failure)

        # Resume only if domain has been paused
        if pause:
            guest.resume()
        return guest

    def _get_vcpu_total(self):
        """Get available vcpu number of physical computer.

        :returns: the number of cpu core instances can be used.

        """
        try:
            total_pcpus = self._host.get_cpu_count()
        except libvirt.libvirtError:
            LOG.warning("Cannot get the number of cpu, because this "
                        "function is not implemented for this platform. ")
            return 0

        if not CONF.vcpu_pin_set:
            return total_pcpus

        available_ids = hardware.get_vcpu_pin_set()
        # We get the list of online CPUs on the host and see if the requested
        # set falls under these. If not, we retain the old behavior.
        online_pcpus = None
        try:
            online_pcpus = self._host.get_online_cpus()
        except libvirt.libvirtError as ex:
            error_code = ex.get_error_code()
            LOG.warning(
                "Couldn't retrieve the online CPUs due to a Libvirt "
                "error: %(error)s with error code: %(error_code)s",
                {'error': ex, 'error_code': error_code})
        if online_pcpus:
            if not (available_ids <= online_pcpus):
                msg = (_("Invalid vcpu_pin_set config, one or more of the "
                         "specified cpuset is not online. Online cpuset(s): "
                         "%(online)s, requested cpuset(s): %(req)s"),
                       {'online': sorted(online_pcpus),
                        'req': sorted(available_ids)})
                raise exception.Invalid(msg)
        elif sorted(available_ids)[-1] >= total_pcpus:
            raise exception.Invalid(_("Invalid vcpu_pin_set config, "
                                      "out of hypervisor cpu range."))
        return len(available_ids)

    @staticmethod
    def _get_local_gb_info():
        """Get local storage info of the compute node in GB.

        :returns: A dict containing:
             :total: How big the overall usable filesystem is (in gigabytes)
             :free: How much space is free (in gigabytes)
             :used: How much space is used (in gigabytes)
        """

        if CONF.libvirt.images_type == 'lvm':
            info = lvm.get_volume_group_info(
                               CONF.libvirt.images_volume_group)
        elif CONF.libvirt.images_type == 'rbd':
            info = LibvirtDriver._get_rbd_driver().get_pool_info()
        else:
            info = libvirt_utils.get_fs_info(CONF.instances_path)

        for (k, v) in info.items():
            info[k] = v / units.Gi

        return info

    def _get_vcpu_used(self):
        """Get vcpu usage number of physical computer.

        :returns: The total number of vcpu(s) that are currently being used.

        """

        total = 0

        # Not all libvirt drivers will support the get_vcpus_info()
        #
        # For example, LXC does not have a concept of vCPUs, while
        # QEMU (TCG) traditionally handles all vCPUs in a single
        # thread. So both will report an exception when the vcpus()
        # API call is made. In such a case we should report the
        # guest as having 1 vCPU, since that lets us still do
        # CPU over commit calculations that apply as the total
        # guest count scales.
        #
        # It is also possible that we might see an exception if
        # the guest is just in middle of shutting down. Technically
        # we should report 0 for vCPU usage in this case, but we
        # we can't reliably distinguish the vcpu not supported
        # case from the just shutting down case. Thus we don't know
        # whether to report 1 or 0 for vCPU count.
        #
        # Under-reporting vCPUs is bad because it could conceivably
        # let the scheduler place too many guests on the host. Over-
        # reporting vCPUs is not a problem as it'll auto-correct on
        # the next refresh of usage data.
        #
        # Thus when getting an exception we always report 1 as the
        # vCPU count, as the least worst value.
        for guest in self._host.list_guests():
            try:
                vcpus = guest.get_vcpus_info()
                total += len(list(vcpus))
            except libvirt.libvirtError:
                total += 1
            # NOTE(gtt116): give other tasks a chance.
            greenthread.sleep(0)
        return total

    def _get_instance_capabilities(self):
        """Get hypervisor instance capabilities

        Returns a list of tuples that describe instances the
        hypervisor is capable of hosting.  Each tuple consists
        of the triplet (arch, hypervisor_type, vm_mode).

        :returns: List of tuples describing instance capabilities
        """
        caps = self._host.get_capabilities()
        instance_caps = list()
        for g in caps.guests:
            for dt in g.domtype:
                instance_cap = (
                    fields.Architecture.canonicalize(g.arch),
                    fields.HVType.canonicalize(dt),
                    fields.VMMode.canonicalize(g.ostype))
                instance_caps.append(instance_cap)

        return instance_caps

    def _get_cpu_info(self):
        """Get cpuinfo information.

        Obtains cpu feature from virConnect.getCapabilities.

        :return: see above description

        """

        caps = self._host.get_capabilities()
        cpu_info = dict()

        cpu_info['arch'] = caps.host.cpu.arch
        cpu_info['model'] = caps.host.cpu.model
        cpu_info['vendor'] = caps.host.cpu.vendor

        topology = dict()
        topology['cells'] = len(getattr(caps.host.topology, 'cells', [1]))
        topology['sockets'] = caps.host.cpu.sockets
        topology['cores'] = caps.host.cpu.cores
        topology['threads'] = caps.host.cpu.threads
        cpu_info['topology'] = topology

        features = set()
        for f in caps.host.cpu.features:
            features.add(f.name)
        cpu_info['features'] = features
        return cpu_info

    def _get_pcinet_info(self, vf_address):
        """Returns a dict of NET device."""
        devname = pci_utils.get_net_name_by_vf_pci_address(vf_address)
        if not devname:
            return

        virtdev = self._host.device_lookup_by_name(devname)
        xmlstr = virtdev.XMLDesc(0)
        cfgdev = vconfig.LibvirtConfigNodeDevice()
        cfgdev.parse_str(xmlstr)
        return {'name': cfgdev.name,
                'capabilities': cfgdev.pci_capability.features}

    def _get_pcidev_info(self, devname):
        """Returns a dict of PCI device."""

        def _get_device_type(cfgdev, pci_address):
            """Get a PCI device's device type.

            An assignable PCI device can be a normal PCI device,
            a SR-IOV Physical Function (PF), or a SR-IOV Virtual
            Function (VF). Only normal PCI devices or SR-IOV VFs
            are assignable, while SR-IOV PFs are always owned by
            hypervisor.
            """
            for fun_cap in cfgdev.pci_capability.fun_capability:
                if fun_cap.type == 'virt_functions':
                    return {
                        'dev_type': fields.PciDeviceType.SRIOV_PF,
                    }
                if (fun_cap.type == 'phys_function' and
                    len(fun_cap.device_addrs) != 0):
                    phys_address = "%04x:%02x:%02x.%01x" % (
                        fun_cap.device_addrs[0][0],
                        fun_cap.device_addrs[0][1],
                        fun_cap.device_addrs[0][2],
                        fun_cap.device_addrs[0][3])
                    return {
                        'dev_type': fields.PciDeviceType.SRIOV_VF,
                        'parent_addr': phys_address,
                    }

            # Note(moshele): libvirt < 1.3 reported virt_functions capability
            # only when VFs are enabled. The check below is a workaround
            # to get the correct report regardless of whether or not any
            # VFs are enabled for the device.
            if not self._host.has_min_version(
                MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION):
                is_physical_function = pci_utils.is_physical_function(
                    *pci_utils.get_pci_address_fields(pci_address))
                if is_physical_function:
                    return {'dev_type': fields.PciDeviceType.SRIOV_PF}

            return {'dev_type': fields.PciDeviceType.STANDARD}

        def _get_device_capabilities(device, address):
            """Get PCI VF device's additional capabilities.

            If a PCI device is a virtual function, this function reads the PCI
            parent's network capabilities (must be always a NIC device) and
            appends this information to the device's dictionary.
            """
            if device.get('dev_type') == fields.PciDeviceType.SRIOV_VF:
                pcinet_info = self._get_pcinet_info(address)
                if pcinet_info:
                    return {'capabilities':
                                {'network': pcinet_info.get('capabilities')}}
            return {}

        virtdev = self._host.device_lookup_by_name(devname)
        xmlstr = virtdev.XMLDesc(0)
        cfgdev = vconfig.LibvirtConfigNodeDevice()
        cfgdev.parse_str(xmlstr)

        address = "%04x:%02x:%02x.%1x" % (
            cfgdev.pci_capability.domain,
            cfgdev.pci_capability.bus,
            cfgdev.pci_capability.slot,
            cfgdev.pci_capability.function)

        device = {
            "dev_id": cfgdev.name,
            "address": address,
            "product_id": "%04x" % cfgdev.pci_capability.product_id,
            "vendor_id": "%04x" % cfgdev.pci_capability.vendor_id,
            }

        device["numa_node"] = cfgdev.pci_capability.numa_node

        # requirement by DataBase Model
        device['label'] = 'label_%(vendor_id)s_%(product_id)s' % device
        device.update(_get_device_type(cfgdev, address))
        device.update(_get_device_capabilities(device, address))
        return device

    def _get_pci_passthrough_devices(self):
        """Get host PCI devices information.

        Obtains pci devices information from libvirt, and returns
        as a JSON string.

        Each device information is a dictionary, with mandatory keys
        of 'address', 'vendor_id', 'product_id', 'dev_type', 'dev_id',
        'label' and other optional device specific information.

        Refer to the objects/pci_device.py for more idea of these keys.

        :returns: a JSON string containing a list of the assignable PCI
                  devices information
        """
        # Bail early if we know we can't support `listDevices` to avoid
        # repeated warnings within a periodic task
        if not getattr(self, '_list_devices_supported', True):
            return jsonutils.dumps([])

        try:
            dev_names = self._host.list_pci_devices() or []
        except libvirt.libvirtError as ex:
            error_code = ex.get_error_code()
            if error_code == libvirt.VIR_ERR_NO_SUPPORT:
                self._list_devices_supported = False
                LOG.warning("URI %(uri)s does not support "
                            "listDevices: %(error)s",
                            {'uri': self._uri(), 'error': ex})
                return jsonutils.dumps([])
            else:
                raise

        pci_info = []
        for name in dev_names:
            pci_info.append(self._get_pcidev_info(name))

        return jsonutils.dumps(pci_info)

    def _has_numa_support(self):
        # This means that the host can support LibvirtConfigGuestNUMATune
        # and the nodeset field in LibvirtConfigGuestMemoryBackingPage
        for ver in BAD_LIBVIRT_NUMA_VERSIONS:
            if self._host.has_version(ver):
                if not getattr(self, '_bad_libvirt_numa_version_warn', False):
                    LOG.warning('You are running with libvirt version %s '
                                'which is known to have broken NUMA support. '
                                'Consider patching or updating libvirt on '
                                'this host if you need NUMA support.',
                                self._version_to_string(ver))
                    self._bad_libvirt_numa_version_warn = True
                return False

        caps = self._host.get_capabilities()

        if (caps.host.cpu.arch in (fields.Architecture.I686,
                                   fields.Architecture.X86_64,
                                   fields.Architecture.AARCH64) and
                self._host.has_min_version(hv_type=host.HV_DRIVER_QEMU)):
            return True
        elif (caps.host.cpu.arch in (fields.Architecture.PPC64,
                                     fields.Architecture.PPC64LE) and
                self._host.has_min_version(MIN_LIBVIRT_NUMA_VERSION_PPC,
                                           hv_type=host.HV_DRIVER_QEMU)):
            return True

        return False

    def _get_host_numa_topology(self):
        if not self._has_numa_support():
            return

        caps = self._host.get_capabilities()
        topology = caps.host.topology

        if topology is None or not topology.cells:
            return

        cells = []
        allowed_cpus = hardware.get_vcpu_pin_set()
        online_cpus = self._host.get_online_cpus()
        if allowed_cpus:
            allowed_cpus &= online_cpus
        else:
            allowed_cpus = online_cpus

        def _get_reserved_memory_for_cell(self, cell_id, page_size):
            cell = self._reserved_hugepages.get(cell_id, {})
            return cell.get(page_size, 0)

        for cell in topology.cells:
            cpuset = set(cpu.id for cpu in cell.cpus)
            siblings = sorted(map(set,
                                  set(tuple(cpu.siblings)
                                        if cpu.siblings else ()
                                      for cpu in cell.cpus)
                                  ))
            cpuset &= allowed_cpus
            siblings = [sib & allowed_cpus for sib in siblings]
            # Filter out singles and empty sibling sets that may be left
            siblings = [sib for sib in siblings if len(sib) > 1]

            mempages = [
                objects.NUMAPagesTopology(
                    size_kb=pages.size,
                    total=pages.total,
                    used=0,
                    reserved=_get_reserved_memory_for_cell(
                        self, cell.id, pages.size))
                for pages in cell.mempages]

            cell = objects.NUMACell(id=cell.id, cpuset=cpuset,
                                    memory=cell.memory / units.Ki,
                                    cpu_usage=0, memory_usage=0,
                                    siblings=siblings,
                                    pinned_cpus=set([]),
                                    mempages=mempages)
            cells.append(cell)

        return objects.NUMATopology(cells=cells)

    def get_all_volume_usage(self, context, compute_host_bdms):
        """Return usage info for volumes attached to vms on
           a given host.
        """
        vol_usage = []

        for instance_bdms in compute_host_bdms:
            instance = instance_bdms['instance']

            for bdm in instance_bdms['instance_bdms']:
                mountpoint = bdm['device_name']
                if mountpoint.startswith('/dev/'):
                    mountpoint = mountpoint[5:]
                volume_id = bdm['volume_id']

                LOG.debug("Trying to get stats for the volume %s",
                          volume_id, instance=instance)
                vol_stats = self.block_stats(instance, mountpoint)

                if vol_stats:
                    stats = dict(volume=volume_id,
                                 instance=instance,
                                 rd_req=vol_stats[0],
                                 rd_bytes=vol_stats[1],
                                 wr_req=vol_stats[2],
                                 wr_bytes=vol_stats[3])
                    LOG.debug(
                        "Got volume usage stats for the volume=%(volume)s,"
                        " rd_req=%(rd_req)d, rd_bytes=%(rd_bytes)d, "
                        "wr_req=%(wr_req)d, wr_bytes=%(wr_bytes)d",
                        stats, instance=instance)
                    vol_usage.append(stats)

        return vol_usage

    def block_stats(self, instance, disk_id):
        """Note that this function takes an instance name."""
        try:
            guest = self._host.get_guest(instance)

            # TODO(sahid): We are converting all calls from a
            # virDomain object to use nova.virt.libvirt.Guest.
            # We should be able to remove domain at the end.
            domain = guest._domain
            return domain.blockStats(disk_id)
        except libvirt.libvirtError as e:
            errcode = e.get_error_code()
            LOG.info('Getting block stats failed, device might have '
                     'been detached. Instance=%(instance_name)s '
                     'Disk=%(disk)s Code=%(errcode)s Error=%(e)s',
                     {'instance_name': instance.name, 'disk': disk_id,
                      'errcode': errcode, 'e': e},
                     instance=instance)
        except exception.InstanceNotFound:
            LOG.info('Could not find domain in libvirt for instance %s. '
                     'Cannot get block stats for device', instance.name,
                     instance=instance)

    def get_console_pool_info(self, console_type):
        # TODO(mdragon): console proxy should be implemented for libvirt,
        #                in case someone wants to use it with kvm or
        #                such. For now return fake data.
        return {'address': '127.0.0.1',
                'username': 'fakeuser',
                'password': 'fakepassword'}

    def refresh_security_group_rules(self, security_group_id):
        self.firewall_driver.refresh_security_group_rules(security_group_id)

    def refresh_instance_security_rules(self, instance):
        self.firewall_driver.refresh_instance_security_rules(instance)

    def get_inventory(self, nodename):
        """Return a dict, keyed by resource class, of inventory information for
        the supplied node.
        """
        disk_gb = int(self._get_local_gb_info()['total'])
        memory_mb = int(self._host.get_memory_mb_total())
        vcpus = self._get_vcpu_total()
        # NOTE(jaypipes): We leave some fields like allocation_ratio and
        # reserved out of the returned dicts here because, for now at least,
        # the RT injects those values into the inventory dict based on the
        # compute_nodes record values.
        result = {
            fields.ResourceClass.VCPU: {
                'total': vcpus,
                'min_unit': 1,
                'max_unit': vcpus,
                'step_size': 1,
            },
            fields.ResourceClass.MEMORY_MB: {
                'total': memory_mb,
                'min_unit': 1,
                'max_unit': memory_mb,
                'step_size': 1,
            },
            fields.ResourceClass.DISK_GB: {
                'total': disk_gb,
                'min_unit': 1,
                'max_unit': disk_gb,
                'step_size': 1,
            },
        }
        return result

    def get_available_resource(self, nodename):
        """Retrieve resource information.

        This method is called when nova-compute launches, and
        as part of a periodic task that records the results in the DB.

        :param nodename: unused in this driver
        :returns: dictionary containing resource info
        """

        disk_info_dict = self._get_local_gb_info()
        data = {}

        # NOTE(dprince): calling capabilities before getVersion works around
        # an initialization issue with some versions of Libvirt (1.0.5.5).
        # See: https://bugzilla.redhat.com/show_bug.cgi?id=1000116
        # See: https://bugs.launchpad.net/nova/+bug/1215593
        data["supported_instances"] = self._get_instance_capabilities()

        data["vcpus"] = self._get_vcpu_total()
        data["memory_mb"] = self._host.get_memory_mb_total()
        data["local_gb"] = disk_info_dict['total']
        data["vcpus_used"] = self._get_vcpu_used()
        data["memory_mb_used"] = self._host.get_memory_mb_used()
        data["local_gb_used"] = disk_info_dict['used']
        data["hypervisor_type"] = self._host.get_driver_type()
        data["hypervisor_version"] = self._host.get_version()
        data["hypervisor_hostname"] = self._host.get_hostname()
        # TODO(berrange): why do we bother converting the
        # libvirt capabilities XML into a special JSON format ?
        # The data format is different across all the drivers
        # so we could just return the raw capabilities XML
        # which 'compare_cpu' could use directly
        #
        # That said, arch_filter.py now seems to rely on
        # the libvirt drivers format which suggests this
        # data format needs to be standardized across drivers
        data["cpu_info"] = jsonutils.dumps(self._get_cpu_info())

        disk_free_gb = disk_info_dict['free']
        disk_over_committed = self._get_disk_over_committed_size_total()
        available_least = disk_free_gb * units.Gi - disk_over_committed
        data['disk_available_least'] = available_least / units.Gi

        data['pci_passthrough_devices'] = \
            self._get_pci_passthrough_devices()

        numa_topology = self._get_host_numa_topology()
        if numa_topology:
            data['numa_topology'] = numa_topology._to_json()
        else:
            data['numa_topology'] = None

        return data

    def check_instance_shared_storage_local(self, context, instance):
        """Check if instance files located on shared storage.

        This runs check on the destination host, and then calls
        back to the source host to check the results.

        :param context: security context
        :param instance: nova.objects.instance.Instance object
        :returns:
         - tempfile: A dict containing the tempfile info on the destination
                     host
         - None:

            1. If the instance path is not existing.
            2. If the image backend is shared block storage type.
        """
        if self.image_backend.backend().is_shared_block_storage():
            return None

        dirpath = libvirt_utils.get_instance_path(instance)

        if not os.path.exists(dirpath):
            return None

        fd, tmp_file = tempfile.mkstemp(dir=dirpath)
        LOG.debug("Creating tmpfile %s to verify with other "
                  "compute node that the instance is on "
                  "the same shared storage.",
                  tmp_file, instance=instance)
        os.close(fd)
        return {"filename": tmp_file}

    def check_instance_shared_storage_remote(self, context, data):
        return os.path.exists(data['filename'])

    def check_instance_shared_storage_cleanup(self, context, data):
        fileutils.delete_if_exists(data["filename"])

    def check_can_live_migrate_destination(self, context, instance,
                                           src_compute_info, dst_compute_info,
                                           block_migration=False,
                                           disk_over_commit=False):
        """Check if it is possible to execute live migration.

        This runs checks on the destination host, and then calls
        back to the source host to check the results.

        :param context: security context
        :param instance: nova.db.sqlalchemy.models.Instance
        :param block_migration: if true, prepare for block migration
        :param disk_over_commit: if true, allow disk over commit
        :returns: a LibvirtLiveMigrateData object
        """
        disk_available_gb = dst_compute_info['disk_available_least']
        disk_available_mb = (
            (disk_available_gb * units.Ki) - CONF.reserved_host_disk_mb)

        # Compare CPU
        if not instance.vcpu_model or not instance.vcpu_model.model:
            source_cpu_info = src_compute_info['cpu_info']
            self._compare_cpu(None, source_cpu_info, instance)
        else:
            self._compare_cpu(instance.vcpu_model, None, instance)

        # Create file on storage, to be checked on source host
        filename = self._create_shared_storage_test_file(instance)

        data = objects.LibvirtLiveMigrateData()
        data.filename = filename
        data.image_type = CONF.libvirt.images_type
        data.graphics_listen_addr_vnc = CONF.vnc.vncserver_listen
        data.graphics_listen_addr_spice = CONF.spice.server_listen
        if CONF.serial_console.enabled:
            data.serial_listen_addr = CONF.serial_console.proxyclient_address
        else:
            data.serial_listen_addr = None
        # Notes(eliqiao): block_migration and disk_over_commit are not
        # nullable, so just don't set them if they are None
        if block_migration is not None:
            data.block_migration = block_migration
        if disk_over_commit is not None:
            data.disk_over_commit = disk_over_commit
        data.disk_available_mb = disk_available_mb
        return data

    def cleanup_live_migration_destination_check(self, context,
                                                 dest_check_data):
        """Do required cleanup on dest host after check_can_live_migrate calls

        :param context: security context
        """
        filename = dest_check_data.filename
        self._cleanup_shared_storage_test_file(filename)

    def check_can_live_migrate_source(self, context, instance,
                                      dest_check_data,
                                      block_device_info=None):
        """Check if it is possible to execute live migration.

        This checks if the live migration can succeed, based on the
        results from check_can_live_migrate_destination.

        :param context: security context
        :param instance: nova.db.sqlalchemy.models.Instance
        :param dest_check_data: result of check_can_live_migrate_destination
        :param block_device_info: result of _get_instance_block_device_info
        :returns: a LibvirtLiveMigrateData object
        """
        if not isinstance(dest_check_data, migrate_data_obj.LiveMigrateData):
            md_obj = objects.LibvirtLiveMigrateData()
            md_obj.from_legacy_dict(dest_check_data)
            dest_check_data = md_obj

        # Checking shared storage connectivity
        # if block migration, instances_path should not be on shared storage.
        source = CONF.host

        dest_check_data.is_shared_instance_path = (
            self._check_shared_storage_test_file(
                dest_check_data.filename, instance))

        dest_check_data.is_shared_block_storage = (
            self._is_shared_block_storage(instance, dest_check_data,
                                          block_device_info))

        if 'block_migration' not in dest_check_data:
            dest_check_data.block_migration = (
                not dest_check_data.is_on_shared_storage())

        if dest_check_data.block_migration:
            # TODO(eliqiao): Once block_migration flag is removed from the API
            # we can safely remove the if condition
            if dest_check_data.is_on_shared_storage():
                reason = _("Block migration can not be used "
                           "with shared storage.")
                raise exception.InvalidLocalStorage(reason=reason, path=source)
            if 'disk_over_commit' in dest_check_data:
                self._assert_dest_node_has_enough_disk(context, instance,
                                        dest_check_data.disk_available_mb,
                                        dest_check_data.disk_over_commit,
                                        block_device_info)
            if block_device_info:
                bdm = block_device_info.get('block_device_mapping')
                # NOTE(pkoniszewski): libvirt from version 1.2.17 upwards
                # supports selective block device migration. It means that it
                # is possible to define subset of block devices to be copied
                # during migration. If they are not specified - block devices
                # won't be migrated. However, it does not work when live
                # migration is tunnelled through libvirt.
                if bdm and not self._host.has_min_version(
                        MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION):
                    # NOTE(stpierre): if this instance has mapped volumes,
                    # we can't do a block migration, since that will result
                    # in volumes being copied from themselves to themselves,
                    # which is a recipe for disaster.
                    ver = ".".join([str(x) for x in
                                    MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION])
                    msg = (_('Cannot block migrate instance %(uuid)s with'
                             ' mapped volumes. Selective block device'
                             ' migration feature requires libvirt version'
                             ' %(libvirt_ver)s') %
                           {'uuid': instance.uuid, 'libvirt_ver': ver})
                    LOG.error(msg, instance=instance)
                    raise exception.MigrationPreCheckError(reason=msg)
                # NOTE(eliqiao): Selective disk migrations are not supported
                # with tunnelled block migrations so we can block them early.
                if (bdm and
                    (self._block_migration_flags &
                     libvirt.VIR_MIGRATE_TUNNELLED != 0)):
                    msg = (_('Cannot block migrate instance %(uuid)s with'
                             ' mapped volumes. Selective block device'
                             ' migration is not supported with tunnelled'
                             ' block migrations.') % {'uuid': instance.uuid})
                    LOG.error(msg, instance=instance)
                    raise exception.MigrationPreCheckError(reason=msg)
        elif not (dest_check_data.is_shared_block_storage or
                  dest_check_data.is_shared_instance_path):
            reason = _("Shared storage live-migration requires either shared "
                       "storage or boot-from-volume with no local disks.")
            raise exception.InvalidSharedStorage(reason=reason, path=source)

        # NOTE(mikal): include the instance directory name here because it
        # doesn't yet exist on the destination but we want to force that
        # same name to be used
        instance_path = libvirt_utils.get_instance_path(instance,
                                                        relative=True)
        dest_check_data.instance_relative_path = instance_path

        return dest_check_data

    def _is_shared_block_storage(self, instance, dest_check_data,
                                 block_device_info=None):
        """Check if all block storage of an instance can be shared
        between source and destination of a live migration.

        Returns true if the instance is volume backed and has no local disks,
        or if the image backend is the same on source and destination and the
        backend shares block storage between compute nodes.

        :param instance: nova.objects.instance.Instance object
        :param dest_check_data: dict with boolean fields image_type,
                                is_shared_instance_path, and is_volume_backed
        """
        if (dest_check_data.obj_attr_is_set('image_type') and
                CONF.libvirt.images_type == dest_check_data.image_type and
                self.image_backend.backend().is_shared_block_storage()):
            # NOTE(dgenin): currently true only for RBD image backend
            return True

        if (dest_check_data.is_shared_instance_path and
                self.image_backend.backend().is_file_in_instance_path()):
            # NOTE(angdraug): file based image backends (Flat, Qcow2)
            # place block device files under the instance path
            return True

        if (dest_check_data.is_volume_backed and
                not bool(self._get_instance_disk_info(instance,
                                                      block_device_info))):
            return True

        return False

    def _assert_dest_node_has_enough_disk(self, context, instance,
                                             available_mb, disk_over_commit,
                                             block_device_info):
        """Checks if destination has enough disk for block migration."""
        # Libvirt supports qcow2 disk format,which is usually compressed
        # on compute nodes.
        # Real disk image (compressed) may enlarged to "virtual disk size",
        # that is specified as the maximum disk size.
        # (See qemu-img -f path-to-disk)
        # Scheduler recognizes destination host still has enough disk space
        # if real disk size < available disk size
        # if disk_over_commit is True,
        #  otherwise virtual disk size < available disk size.

        available = 0
        if available_mb:
            available = available_mb * units.Mi

        disk_infos = self._get_instance_disk_info(instance, block_device_info)

        necessary = 0
        if disk_over_commit:
            for info in disk_infos:
                necessary += int(info['disk_size'])
        else:
            for info in disk_infos:
                necessary += int(info['virt_disk_size'])

        # Check that available disk > necessary disk
        if (available - necessary) < 0:
            reason = (_('Unable to migrate %(instance_uuid)s: '
                        'Disk of instance is too large(available'
                        ' on destination host:%(available)s '
                        '< need:%(necessary)s)') %
                      {'instance_uuid': instance.uuid,
                       'available': available,
                       'necessary': necessary})
            raise exception.MigrationPreCheckError(reason=reason)

    def _compare_cpu(self, guest_cpu, host_cpu_str, instance):
        """Check the host is compatible with the requested CPU

        :param guest_cpu: nova.objects.VirtCPUModel or None
        :param host_cpu_str: JSON from _get_cpu_info() method

        If the 'guest_cpu' parameter is not None, this will be
        validated for migration compatibility with the host.
        Otherwise the 'host_cpu_str' JSON string will be used for
        validation.

        :returns:
            None. if given cpu info is not compatible to this server,
            raise exception.
        """

        # NOTE(kchamart): Comparing host to guest CPU model for emulated
        # guests (<domain type='qemu'>) should not matter -- in this
        # mode (QEMU "TCG") the CPU is fully emulated in software and no
        # hardware acceleration, like KVM, is involved. So, skip the CPU
        # compatibility check for the QEMU domain type, and retain it for
        # KVM guests.
        if CONF.libvirt.virt_type not in ['kvm']:
            return

        if guest_cpu is None:
            info = jsonutils.loads(host_cpu_str)
            LOG.info('Instance launched has CPU info: %s', host_cpu_str)
            cpu = vconfig.LibvirtConfigCPU()
            cpu.arch = info['arch']
            cpu.model = info['model']
            cpu.vendor = info['vendor']
            cpu.sockets = info['topology']['sockets']
            cpu.cores = info['topology']['cores']
            cpu.threads = info['topology']['threads']
            for f in info['features']:
                cpu.add_feature(vconfig.LibvirtConfigCPUFeature(f))
        else:
            cpu = self._vcpu_model_to_cpu_config(guest_cpu)

        u = ("http://libvirt.org/html/libvirt-libvirt-host.html#"
             "virCPUCompareResult")
        m = _("CPU doesn't have compatibility.\n\n%(ret)s\n\nRefer to %(u)s")
        # unknown character exists in xml, then libvirt complains
        try:
            cpu_xml = cpu.to_xml()
            LOG.debug("cpu compare xml: %s", cpu_xml, instance=instance)
            ret = self._host.compare_cpu(cpu_xml)
        except libvirt.libvirtError as e:
            error_code = e.get_error_code()
            if error_code == libvirt.VIR_ERR_NO_SUPPORT:
                LOG.debug("URI %(uri)s does not support cpu comparison. "
                          "It will be proceeded though. Error: %(error)s",
                          {'uri': self._uri(), 'error': e})
                return
            else:
                LOG.error(m, {'ret': e, 'u': u})
                raise exception.MigrationPreCheckError(
                    reason=m % {'ret': e, 'u': u})

        if ret <= 0:
            LOG.error(m, {'ret': ret, 'u': u})
            raise exception.InvalidCPUInfo(reason=m % {'ret': ret, 'u': u})

    def _create_shared_storage_test_file(self, instance):
        """Makes tmpfile under CONF.instances_path."""
        dirpath = CONF.instances_path
        fd, tmp_file = tempfile.mkstemp(dir=dirpath)
        LOG.debug("Creating tmpfile %s to notify to other "
                  "compute nodes that they should mount "
                  "the same storage.", tmp_file, instance=instance)
        os.close(fd)
        return os.path.basename(tmp_file)

    def _check_shared_storage_test_file(self, filename, instance):
        """Confirms existence of the tmpfile under CONF.instances_path.

        Cannot confirm tmpfile return False.
        """
        # NOTE(tpatzig): if instances_path is a shared volume that is
        # under heavy IO (many instances on many compute nodes),
        # then checking the existence of the testfile fails,
        # just because it takes longer until the client refreshes and new
        # content gets visible.
        # os.utime (like touch) on the directory forces the client to refresh.
        os.utime(CONF.instances_path, None)

        tmp_file = os.path.join(CONF.instances_path, filename)
        if not os.path.exists(tmp_file):
            exists = False
        else:
            exists = True
        LOG.debug('Check if temp file %s exists to indicate shared storage '
                  'is being used for migration. Exists? %s', tmp_file, exists,
                  instance=instance)
        return exists

    def _cleanup_shared_storage_test_file(self, filename):
        """Removes existence of the tmpfile under CONF.instances_path."""
        tmp_file = os.path.join(CONF.instances_path, filename)
        os.remove(tmp_file)

    def ensure_filtering_rules_for_instance(self, instance, network_info):
        """Ensure that an instance's filtering rules are enabled.

        When migrating an instance, we need the filtering rules to
        be configured on the destination host before starting the
        migration.

        Also, when restarting the compute service, we need to ensure
        that filtering rules exist for all running services.
        """

        self.firewall_driver.setup_basic_filtering(instance, network_info)
        self.firewall_driver.prepare_instance_filter(instance,
                network_info)

        # nwfilters may be defined in a separate thread in the case
        # of libvirt non-blocking mode, so we wait for completion
        timeout_count = list(range(CONF.live_migration_retry_count))
        while timeout_count:
            if self.firewall_driver.instance_filter_exists(instance,
                                                           network_info):
                break
            timeout_count.pop()
            if len(timeout_count) == 0:
                msg = _('The firewall filter for %s does not exist')
                raise exception.InternalError(msg % instance.name)
            greenthread.sleep(1)

    def filter_defer_apply_on(self):
        self.firewall_driver.filter_defer_apply_on()

    def filter_defer_apply_off(self):
        self.firewall_driver.filter_defer_apply_off()

    def live_migration(self, context, instance, dest,
                       post_method, recover_method, block_migration=False,
                       migrate_data=None):
        """Spawning live_migration operation for distributing high-load.

        :param context: security context
        :param instance:
            nova.db.sqlalchemy.models.Instance object
            instance object that is migrated.
        :param dest: destination host
        :param post_method:
            post operation method.
            expected nova.compute.manager._post_live_migration.
        :param recover_method:
            recovery method when any exception occurs.
            expected nova.compute.manager._rollback_live_migration.
        :param block_migration: if true, do block migration.
        :param migrate_data: a LibvirtLiveMigrateData object

        """

        # 'dest' will be substituted into 'migration_uri' so ensure
        # it does't contain any characters that could be used to
        # exploit the URI accepted by libivrt
        if not libvirt_utils.is_valid_hostname(dest):
            raise exception.InvalidHostname(hostname=dest)

        self._live_migration(context, instance, dest,
                             post_method, recover_method, block_migration,
                             migrate_data)

    def live_migration_abort(self, instance):
        """Aborting a running live-migration.

        :param instance: instance object that is in migration

        """

        guest = self._host.get_guest(instance)
        dom = guest._domain

        try:
            dom.abortJob()
        except libvirt.libvirtError as e:
            LOG.error("Failed to cancel migration %s", e, instance=instance)
            raise

    def _verify_serial_console_is_disabled(self):
        if CONF.serial_console.enabled:

            msg = _('Your destination node does not support'
                    ' retrieving listen addresses.  In order'
                    ' for live migration to work properly you'
                    ' must disable serial console.')
            raise exception.MigrationError(reason=msg)

    def _live_migration_operation(self, context, instance, dest,
                                  block_migration, migrate_data, guest,
                                  device_names, bandwidth):
        """Invoke the live migration operation

        :param context: security context
        :param instance:
            nova.db.sqlalchemy.models.Instance object
            instance object that is migrated.
        :param dest: destination host
        :param block_migration: if true, do block migration.
        :param migrate_data: a LibvirtLiveMigrateData object
        :param guest: the guest domain object
        :param device_names: list of device names that are being migrated with
            instance
        :param bandwidth: MiB/s of bandwidth allowed for the migration at start

        This method is intended to be run in a background thread and will
        block that thread until the migration is finished or failed.
        """
        try:
            if migrate_data.block_migration:
                migration_flags = self._block_migration_flags
            else:
                migration_flags = self._live_migration_flags

            serial_listen_addr = libvirt_migrate.serial_listen_addr(
                migrate_data)
            if not serial_listen_addr:
                # In this context we want to ensure that serial console is
                # disabled on source node. This is because nova couldn't
                # retrieve serial listen address from destination node, so we
                # consider that destination node might have serial console
                # disabled as well.
                self._verify_serial_console_is_disabled()

            # NOTE(aplanas) migrate_uri will have a value only in the
            # case that `live_migration_inbound_addr` parameter is
            # set, and we propose a non tunneled migration.
            migrate_uri = None
            if ('target_connect_addr' in migrate_data and
                    migrate_data.target_connect_addr is not None):
                dest = migrate_data.target_connect_addr
                if (migration_flags &
                    libvirt.VIR_MIGRATE_TUNNELLED == 0):
                    migrate_uri = self._migrate_uri(dest)

            params = None
            new_xml_str = None
            if CONF.libvirt.virt_type != "parallels":
                new_xml_str = libvirt_migrate.get_updated_guest_xml(
                    # TODO(sahid): It's not a really good idea to pass
                    # the method _get_volume_config and we should to find
                    # a way to avoid this in future.
                    guest, migrate_data, self._get_volume_config)
            if self._host.has_min_version(
                    MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION):
                params = {
                    'destination_xml': new_xml_str,
                    'migrate_disks': device_names,
                }
                # NOTE(pkoniszewski): Because of precheck which blocks
                # tunnelled block live migration with mapped volumes we
                # can safely remove migrate_disks when tunnelling is on.
                # Otherwise we will block all tunnelled block migrations,
                # even when an instance does not have volumes mapped.
                # This is because selective disk migration is not
                # supported in tunnelled block live migration. Also we
                # cannot fallback to migrateToURI2 in this case because of
                # bug #1398999
                if (migration_flags &
                    libvirt.VIR_MIGRATE_TUNNELLED != 0):
                    params.pop('migrate_disks')

            # TODO(sahid): This should be in
            # post_live_migration_at_source but no way to retrieve
            # ports acquired on the host for the guest at this
            # step. Since the domain is going to be removed from
            # libvird on source host after migration, we backup the
            # serial ports to release them if all went well.
            serial_ports = []
            if CONF.serial_console.enabled:
                serial_ports = list(self._get_serial_ports_from_guest(guest))

            guest.migrate(self._live_migration_uri(dest),
                          migrate_uri=migrate_uri,
                          flags=migration_flags,
                          params=params,
                          domain_xml=new_xml_str,
                          bandwidth=bandwidth)

            for hostname, port in serial_ports:
                serial_console.release_port(host=hostname, port=port)
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error("Live Migration failure: %s", e, instance=instance)

        # If 'migrateToURI' fails we don't know what state the
        # VM instances on each host are in. Possibilities include
        #
        #  1. src==running, dst==none
        #
        #     Migration failed & rolled back, or never started
        #
        #  2. src==running, dst==paused
        #
        #     Migration started but is still ongoing
        #
        #  3. src==paused,  dst==paused
        #
        #     Migration data transfer completed, but switchover
        #     is still ongoing, or failed
        #
        #  4. src==paused,  dst==running
        #
        #     Migration data transfer completed, switchover
        #     happened but cleanup on source failed
        #
        #  5. src==none,    dst==running
        #
        #     Migration fully succeeded.
        #
        # Libvirt will aim to complete any migration operation
        # or roll it back. So even if the migrateToURI call has
        # returned an error, if the migration was not finished
        # libvirt should clean up.
        #
        # So we take the error raise here with a pinch of salt
        # and rely on the domain job info status to figure out
        # what really happened to the VM, which is a much more
        # reliable indicator.
        #
        # In particular we need to try very hard to ensure that
        # Nova does not "forget" about the guest. ie leaving it
        # running on a different host to the one recorded in
        # the database, as that would be a serious resource leak

        LOG.debug("Migration operation thread has finished",
                  instance=instance)

    def _live_migration_copy_disk_paths(self, context, instance, guest):
        '''Get list of disks to copy during migration

        :param context: security context
        :param instance: the instance being migrated
        :param guest: the Guest instance being migrated

        Get the list of disks to copy during migration.

        :returns: a list of local source paths and a list of device names to
            copy
        '''

        disk_paths = []
        device_names = []
        block_devices = []

        # TODO(pkoniszewski): Remove version check when we bump min libvirt
        # version to >= 1.2.17.
        if (self._block_migration_flags &
                libvirt.VIR_MIGRATE_TUNNELLED == 0 and
                self._host.has_min_version(
                    MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION)):
            bdm_list = objects.BlockDeviceMappingList.get_by_instance_uuid(
                context, instance.uuid)
            block_device_info = driver.get_block_device_info(instance,
                                                             bdm_list)

            block_device_mappings = driver.block_device_info_get_mapping(
                block_device_info)
            for bdm in block_device_mappings:
                device_name = str(bdm['mount_device'].rsplit('/', 1)[1])
                block_devices.append(device_name)

        for dev in guest.get_all_disks():
            if dev.readonly or dev.shareable:
                continue
            if dev.source_type not in ["file", "block"]:
                continue
            if dev.target_dev in block_devices:
                continue
            disk_paths.append(dev.source_path)
            device_names.append(dev.target_dev)
        return (disk_paths, device_names)

    def _live_migration_data_gb(self, instance, disk_paths):
        '''Calculate total amount of data to be transferred

        :param instance: the nova.objects.Instance being migrated
        :param disk_paths: list of disk paths that are being migrated
        with instance

        Calculates the total amount of data that needs to be
        transferred during the live migration. The actual
        amount copied will be larger than this, due to the
        guest OS continuing to dirty RAM while the migration
        is taking place. So this value represents the minimal
        data size possible.

        :returns: data size to be copied in GB
        '''

        ram_gb = instance.flavor.memory_mb * units.Mi / units.Gi
        if ram_gb < 2:
            ram_gb = 2

        disk_gb = 0
        for path in disk_paths:
            try:
                size = os.stat(path).st_size
                size_gb = (size / units.Gi)
                if size_gb < 2:
                    size_gb = 2
                disk_gb += size_gb
            except OSError as e:
                LOG.warning("Unable to stat %(disk)s: %(ex)s",
                            {'disk': path, 'ex': e})
                # Ignore error since we don't want to break
                # the migration monitoring thread operation

        return ram_gb + disk_gb

    def _get_migration_flags(self, is_block_migration):
        if is_block_migration:
            return self._block_migration_flags
        return self._live_migration_flags

    def _live_migration_monitor(self, context, instance, guest,
                                dest, post_method,
                                recover_method, block_migration,
                                migrate_data, finish_event,
                                disk_paths):
        on_migration_failure = deque()
        data_gb = self._live_migration_data_gb(instance, disk_paths)
        downtime_steps = list(libvirt_migrate.downtime_steps(data_gb))
        migration = migrate_data.migration
        curdowntime = None

        migration_flags = self._get_migration_flags(
                                  migrate_data.block_migration)

        n = 0
        start = time.time()
        progress_time = start
        progress_watermark = None
        previous_data_remaining = -1
        is_post_copy_enabled = self._is_post_copy_enabled(migration_flags)
        while True:
            info = guest.get_job_info()

            if info.type == libvirt.VIR_DOMAIN_JOB_NONE:
                # Either still running, or failed or completed,
                # lets untangle the mess
                if not finish_event.ready():
                    LOG.debug("Operation thread is still running",
                              instance=instance)
                else:
                    info.type = libvirt_migrate.find_job_type(guest, instance)
                    LOG.debug("Fixed incorrect job type to be %d",
                              info.type, instance=instance)

            if info.type == libvirt.VIR_DOMAIN_JOB_NONE:
                # Migration is not yet started
                LOG.debug("Migration not running yet",
                          instance=instance)
            elif info.type == libvirt.VIR_DOMAIN_JOB_UNBOUNDED:
                # Migration is still running
                #
                # This is where we wire up calls to change live
                # migration status. eg change max downtime, cancel
                # the operation, change max bandwidth
                libvirt_migrate.run_tasks(guest, instance,
                                          self.active_migrations,
                                          on_migration_failure,
                                          migration,
                                          is_post_copy_enabled)

                now = time.time()
                elapsed = now - start

                if ((progress_watermark is None) or
                    (progress_watermark == 0) or
                    (progress_watermark > info.data_remaining)):
                    progress_watermark = info.data_remaining
                    progress_time = now

                progress_timeout = CONF.libvirt.live_migration_progress_timeout
                completion_timeout = int(
                    CONF.libvirt.live_migration_completion_timeout * data_gb)
                if libvirt_migrate.should_abort(instance, now, progress_time,
                                                progress_timeout, elapsed,
                                                completion_timeout,
                                                migration.status):
                    try:
                        guest.abort_job()
                    except libvirt.libvirtError as e:
                        LOG.warning("Failed to abort migration %s",
                                    e, instance=instance)
                        self._clear_empty_migration(instance)
                        raise

                if (is_post_copy_enabled and
                    libvirt_migrate.should_switch_to_postcopy(
                    info.memory_iteration, info.data_remaining,
                    previous_data_remaining, migration.status)):
                    libvirt_migrate.trigger_postcopy_switch(guest,
                                                            instance,
                                                            migration)
                previous_data_remaining = info.data_remaining

                curdowntime = libvirt_migrate.update_downtime(
                    guest, instance, curdowntime,
                    downtime_steps, elapsed)

                # We loop every 500ms, so don't log on every
                # iteration to avoid spamming logs for long
                # running migrations. Just once every 5 secs
                # is sufficient for developers to debug problems.
                # We log once every 30 seconds at info to help
                # admins see slow running migration operations
                # when debug logs are off.
                if (n % 10) == 0:
                    # Ignoring memory_processed, as due to repeated
                    # dirtying of data, this can be way larger than
                    # memory_total. Best to just look at what's
                    # remaining to copy and ignore what's done already
                    #
                    # TODO(berrange) perhaps we could include disk
                    # transfer stats in the progress too, but it
                    # might make memory info more obscure as large
                    # disk sizes might dwarf memory size
                    remaining = 100
                    if info.memory_total != 0:
                        remaining = round(info.memory_remaining *
                                          100 / info.memory_total)

                    libvirt_migrate.save_stats(instance, migration,
                                               info, remaining)

                    lg = LOG.debug
                    if (n % 60) == 0:
                        lg = LOG.info

                    lg("Migration running for %(secs)d secs, "
                       "memory %(remaining)d%% remaining; "
                       "(bytes processed=%(processed_memory)d, "
                       "remaining=%(remaining_memory)d, "
                       "total=%(total_memory)d)",
                       {"secs": n / 2, "remaining": remaining,
                        "processed_memory": info.memory_processed,
                        "remaining_memory": info.memory_remaining,
                        "total_memory": info.memory_total}, instance=instance)
                    if info.data_remaining > progress_watermark:
                        lg("Data remaining %(remaining)d bytes, "
                           "low watermark %(watermark)d bytes "
                           "%(last)d seconds ago",
                           {"remaining": info.data_remaining,
                            "watermark": progress_watermark,
                            "last": (now - progress_time)}, instance=instance)

                n = n + 1
            elif info.type == libvirt.VIR_DOMAIN_JOB_COMPLETED:
                # Migration is all done
                LOG.info("Migration operation has completed",
                         instance=instance)
                post_method(context, instance, dest, block_migration,
                            migrate_data)
                break
            elif info.type == libvirt.VIR_DOMAIN_JOB_FAILED:
                # Migration did not succeed
                LOG.error("Migration operation has aborted", instance=instance)
                libvirt_migrate.run_recover_tasks(self._host, guest, instance,
                                                  on_migration_failure)
                recover_method(context, instance, dest, migrate_data)
                break
            elif info.type == libvirt.VIR_DOMAIN_JOB_CANCELLED:
                # Migration was stopped by admin
                LOG.warning("Migration operation was cancelled",
                            instance=instance)
                libvirt_migrate.run_recover_tasks(self._host, guest, instance,
                                                  on_migration_failure)
                recover_method(context, instance, dest, migrate_data,
                               migration_status='cancelled')
                break
            else:
                LOG.warning("Unexpected migration job type: %d",
                            info.type, instance=instance)

            time.sleep(0.5)
        self._clear_empty_migration(instance)

    def _clear_empty_migration(self, instance):
        try:
            del self.active_migrations[instance.uuid]
        except KeyError:
            LOG.warning("There are no records in active migrations "
                        "for instance", instance=instance)

    def _live_migration(self, context, instance, dest, post_method,
                        recover_method, block_migration,
                        migrate_data):
        """Do live migration.

        :param context: security context
        :param instance:
            nova.db.sqlalchemy.models.Instance object
            instance object that is migrated.
        :param dest: destination host
        :param post_method:
            post operation method.
            expected nova.compute.manager._post_live_migration.
        :param recover_method:
            recovery method when any exception occurs.
            expected nova.compute.manager._rollback_live_migration.
        :param block_migration: if true, do block migration.
        :param migrate_data: a LibvirtLiveMigrateData object

        This fires off a new thread to run the blocking migration
        operation, and then this thread monitors the progress of
        migration and controls its operation
        """

        guest = self._host.get_guest(instance)

        disk_paths = []
        device_names = []
        if (migrate_data.block_migration and
                CONF.libvirt.virt_type != "parallels"):
            disk_paths, device_names = self._live_migration_copy_disk_paths(
                context, instance, guest)

        deadline = CONF.vif_plugging_timeout
        if utils.is_neutron() and deadline:
            # We don't generate events if CONF.vif_plugging_timeout=0
            # meaning that the operator disabled using them.

            # In case of Linux Bridge, the agent is waiting for new
            # TAP devices on destination node. They are going to be
            # created by libvirt at the very beginning of the
            # live-migration process. Then receiving the events from
            # Neutron will ensure that everything is configured
            # correctly.
            events = self._get_neutron_events_for_live_migration(
                instance.get_network_info())
        else:
            # TODO(sahid): This 'is_neutron()' condition should be
            # removed when nova-network will be erased from the tree
            # (Rocky).
            events = []

        if events:
            # We start migration with the minimum bandwidth
            # speed. Depending on the VIF type (see:
            # _get_neutron_events_for_live_migration) we will wait for
            # Neutron to send events that confirm network is setup or
            # directly configure QEMU to use the maximun BW allowed.
            bandwidth = MIN_MIGRATION_SPEED_BW
        else:
            bandwidth = CONF.libvirt.live_migration_bandwidth

        try:
            error_cb = self._neutron_failed_live_migration_callback
            with self.virtapi.wait_for_instance_event(instance, events,
                                                      deadline=deadline,
                                                      error_callback=error_cb):
                opthread = utils.spawn(self._live_migration_operation,
                                       context, instance, dest,
                                       block_migration,
                                       migrate_data, guest,
                                       device_names, bandwidth)
        except eventlet.timeout.Timeout:
            msg = ('Timeout waiting for VIF plugging events, '
                   'canceling migration')
            raise exception.MigrationError(reason=msg)
        else:
            if utils.is_neutron() and events:
                LOG.debug('VIF events received, continuing migration '
                          'with max bandwidth configured: %d',
                          CONF.libvirt.live_migration_bandwidth,
                          instance=instance)
                # Configure QEMU to use the maximum bandwidth allowed.
                guest.migrate_configure_max_speed(
                    CONF.libvirt.live_migration_bandwidth)

        finish_event = eventlet.event.Event()
        self.active_migrations[instance.uuid] = deque()

        def thread_finished(thread, event):
            LOG.debug("Migration operation thread notification",
                      instance=instance)
            event.send()
        opthread.link(thread_finished, finish_event)

        # Let eventlet schedule the new thread right away
        time.sleep(0)

        try:
            LOG.debug("Starting monitoring of live migration",
                      instance=instance)
            self._live_migration_monitor(context, instance, guest, dest,
                                         post_method, recover_method,
                                         block_migration, migrate_data,
                                         finish_event, disk_paths)
        except Exception as ex:
            LOG.warning("Error monitoring migration: %(ex)s",
                        {"ex": ex}, instance=instance, exc_info=True)
            raise
        finally:
            LOG.debug("Live migration monitoring is all done",
                      instance=instance)

    def _is_post_copy_enabled(self, migration_flags):
        if self._is_post_copy_available():
            if (migration_flags & libvirt.VIR_MIGRATE_POSTCOPY) != 0:
                return True
        return False

    def live_migration_force_complete(self, instance):
        try:
            self.active_migrations[instance.uuid].append('force-complete')
        except KeyError:
            raise exception.NoActiveMigrationForInstance(
                instance_id=instance.uuid)

    def _try_fetch_image(self, context, path, image_id, instance,
                         fallback_from_host=None):
        try:
            libvirt_utils.fetch_image(context, path, image_id)
        except exception.ImageNotFound:
            if not fallback_from_host:
                raise
            LOG.debug("Image %(image_id)s doesn't exist anymore on "
                      "image service, attempting to copy image "
                      "from %(host)s",
                      {'image_id': image_id, 'host': fallback_from_host})
            libvirt_utils.copy_image(src=path, dest=path,
                                     host=fallback_from_host,
                                     receive=True)

    def _fetch_instance_kernel_ramdisk(self, context, instance,
                                       fallback_from_host=None):
        """Download kernel and ramdisk for instance in instance directory."""
        instance_dir = libvirt_utils.get_instance_path(instance)
        if instance.kernel_id:
            kernel_path = os.path.join(instance_dir, 'kernel')
            # NOTE(dsanders): only fetch image if it's not available at
            # kernel_path. This also avoids ImageNotFound exception if
            # the image has been deleted from glance
            if not os.path.exists(kernel_path):
                self._try_fetch_image(context,
                                      kernel_path,
                                      instance.kernel_id,
                                      instance, fallback_from_host)
            if instance.ramdisk_id:
                ramdisk_path = os.path.join(instance_dir, 'ramdisk')
                # NOTE(dsanders): only fetch image if it's not available at
                # ramdisk_path. This also avoids ImageNotFound exception if
                # the image has been deleted from glance
                if not os.path.exists(ramdisk_path):
                    self._try_fetch_image(context,
                                          ramdisk_path,
                                          instance.ramdisk_id,
                                          instance, fallback_from_host)

    def rollback_live_migration_at_destination(self, context, instance,
                                               network_info,
                                               block_device_info,
                                               destroy_disks=True,
                                               migrate_data=None):
        """Clean up destination node after a failed live migration."""
        try:
            self.destroy(context, instance, network_info, block_device_info,
                         destroy_disks)
        finally:
            # NOTE(gcb): Failed block live migration may leave instance
            # directory at destination node, ensure it is always deleted.
            is_shared_instance_path = True
            if migrate_data:
                is_shared_instance_path = migrate_data.is_shared_instance_path
                if (migrate_data.obj_attr_is_set("serial_listen_ports")
                    and migrate_data.serial_listen_ports):
                    # Releases serial ports reserved.
                    for port in migrate_data.serial_listen_ports:
                        serial_console.release_port(
                            host=migrate_data.serial_listen_addr, port=port)

            if not is_shared_instance_path:
                instance_dir = libvirt_utils.get_instance_path_at_destination(
                    instance, migrate_data)
                if os.path.exists(instance_dir):
                    shutil.rmtree(instance_dir)

    def pre_live_migration(self, context, instance, block_device_info,
                           network_info, disk_info, migrate_data):
        """Preparation live migration."""
        if disk_info is not None:
            disk_info = jsonutils.loads(disk_info)

        LOG.debug('migrate_data in pre_live_migration: %s', migrate_data,
                  instance=instance)
        is_shared_block_storage = migrate_data.is_shared_block_storage
        is_shared_instance_path = migrate_data.is_shared_instance_path
        is_block_migration = migrate_data.block_migration

        if not is_shared_instance_path:
            instance_dir = libvirt_utils.get_instance_path_at_destination(
                            instance, migrate_data)

            if os.path.exists(instance_dir):
                raise exception.DestinationDiskExists(path=instance_dir)

            LOG.debug('Creating instance directory: %s', instance_dir,
                      instance=instance)
            os.mkdir(instance_dir)

            # Recreate the disk.info file and in doing so stop the
            # imagebackend from recreating it incorrectly by inspecting the
            # contents of each file when using the Raw backend.
            if disk_info:
                image_disk_info = {}
                for info in disk_info:
                    image_file = os.path.basename(info['path'])
                    image_path = os.path.join(instance_dir, image_file)
                    image_disk_info[image_path] = info['type']

                LOG.debug('Creating disk.info with the contents: %s',
                          image_disk_info, instance=instance)

                image_disk_info_path = os.path.join(instance_dir,
                                                    'disk.info')
                libvirt_utils.write_to_file(image_disk_info_path,
                                            jsonutils.dumps(image_disk_info))

            if not is_shared_block_storage:
                # Ensure images and backing files are present.
                LOG.debug('Checking to make sure images and backing files are '
                          'present before live migration.', instance=instance)
                self._create_images_and_backing(
                    context, instance, instance_dir, disk_info,
                    fallback_from_host=instance.host)
                if (configdrive.required_by(instance) and
                        CONF.config_drive_format == 'iso9660'):
                    # NOTE(pkoniszewski): Due to a bug in libvirt iso config
                    # drive needs to be copied to destination prior to
                    # migration when instance path is not shared and block
                    # storage is not shared. Files that are already present
                    # on destination are excluded from a list of files that
                    # need to be copied to destination. If we don't do that
                    # live migration will fail on copying iso config drive to
                    # destination and writing to read-only device.
                    # Please see bug/1246201 for more details.
                    src = "%s:%s/disk.config" % (instance.host, instance_dir)
                    self._remotefs.copy_file(src, instance_dir)

            if not is_block_migration:
                # NOTE(angdraug): when block storage is shared between source
                # and destination and instance path isn't (e.g. volume backed
                # or rbd backed instance), instance path on destination has to
                # be prepared

                # Required by Quobyte CI
                self._ensure_console_log_for_instance(instance)

                # if image has kernel and ramdisk, just download
                # following normal way.
                self._fetch_instance_kernel_ramdisk(context, instance)

        # Establishing connection to volume server.
        block_device_mapping = driver.block_device_info_get_mapping(
            block_device_info)

        if len(block_device_mapping):
            LOG.debug('Connecting volumes before live migration.',
                      instance=instance)

        for bdm in block_device_mapping:
            connection_info = bdm['connection_info']
            disk_info = blockinfo.get_info_from_bdm(
                instance, CONF.libvirt.virt_type,
                instance.image_meta, bdm)
            self._connect_volume(connection_info, disk_info, instance)

        # We call plug_vifs before the compute manager calls
        # ensure_filtering_rules_for_instance, to ensure bridge is set up
        # Retry operation is necessary because continuously request comes,
        # concurrent request occurs to iptables, then it complains.
        LOG.debug('Plugging VIFs before live migration.', instance=instance)
        max_retry = CONF.live_migration_retry_count
        for cnt in range(max_retry):
            try:
                self.plug_vifs(instance, network_info)
                break
            except processutils.ProcessExecutionError:
                if cnt == max_retry - 1:
                    raise
                else:
                    LOG.warning('plug_vifs() failed %(cnt)d. Retry up to '
                                '%(max_retry)d.',
                                {'cnt': cnt, 'max_retry': max_retry},
                                instance=instance)
                    greenthread.sleep(1)

        # Store vncserver_listen and latest disk device info
        if not migrate_data:
            migrate_data = objects.LibvirtLiveMigrateData(bdms=[])
        else:
            migrate_data.bdms = []
        # Store live_migration_inbound_addr
        migrate_data.target_connect_addr = \
            CONF.libvirt.live_migration_inbound_addr
        migrate_data.supported_perf_events = self._supported_perf_events

        migrate_data.serial_listen_ports = []
        if CONF.serial_console.enabled:
            num_ports = hardware.get_number_of_serial_ports(
                instance.flavor, instance.image_meta)
            for port in six.moves.range(num_ports):
                migrate_data.serial_listen_ports.append(
                    serial_console.acquire_port(
                        migrate_data.serial_listen_addr))

        for vol in block_device_mapping:
            connection_info = vol['connection_info']
            if connection_info.get('serial'):
                disk_info = blockinfo.get_info_from_bdm(
                    instance, CONF.libvirt.virt_type,
                    instance.image_meta, vol)

                bdmi = objects.LibvirtLiveMigrateBDMInfo()
                bdmi.serial = connection_info['serial']
                bdmi.connection_info = connection_info
                bdmi.bus = disk_info['bus']
                bdmi.dev = disk_info['dev']
                bdmi.type = disk_info['type']
                bdmi.format = disk_info.get('format')
                bdmi.boot_index = disk_info.get('boot_index')
                migrate_data.bdms.append(bdmi)

        return migrate_data

    def _try_fetch_image_cache(self, image, fetch_func, context, filename,
                               image_id, instance, size,
                               fallback_from_host=None):
        try:
            image.cache(fetch_func=fetch_func,
                        context=context,
                        filename=filename,
                        image_id=image_id,
                        size=size)
        except exception.ImageNotFound:
            if not fallback_from_host:
                raise
            LOG.debug("Image %(image_id)s doesn't exist anymore "
                      "on image service, attempting to copy "
                      "image from %(host)s",
                      {'image_id': image_id, 'host': fallback_from_host},
                      instance=instance)

            def copy_from_host(target):
                libvirt_utils.copy_image(src=target,
                                         dest=target,
                                         host=fallback_from_host,
                                         receive=True)
            image.cache(fetch_func=copy_from_host,
                        filename=filename)

    def _create_images_and_backing(self, context, instance, instance_dir,
                                   disk_info, fallback_from_host=None):
        """:param context: security context
           :param instance:
               nova.db.sqlalchemy.models.Instance object
               instance object that is migrated.
           :param instance_dir:
               instance path to use, calculated externally to handle block
               migrating an instance with an old style instance path
           :param disk_info:
               disk info specified in _get_instance_disk_info_from_config
               (list of dicts)
           :param fallback_from_host:
               host where we can retrieve images if the glance images are
               not available.

        """

        # Virtuozzo containers don't use backing file
        if (CONF.libvirt.virt_type == "parallels" and
                instance.vm_mode == fields.VMMode.EXE):
            return

        if not disk_info:
            disk_info = []

        for info in disk_info:
            base = os.path.basename(info['path'])
            # Get image type and create empty disk image, and
            # create backing file in case of qcow2.
            instance_disk = os.path.join(instance_dir, base)
            if not info['backing_file'] and not os.path.exists(instance_disk):
                libvirt_utils.create_image(info['type'], instance_disk,
                                           info['virt_disk_size'])
            elif info['backing_file']:
                # Creating backing file follows same way as spawning instances.
                cache_name = os.path.basename(info['backing_file'])

                disk = self.image_backend.by_name(instance, instance_disk,
                                                  CONF.libvirt.images_type)
                if cache_name.startswith('ephemeral'):
                    # The argument 'size' is used by image.cache to
                    # validate disk size retrieved from cache against
                    # the instance disk size (should always return OK)
                    # and ephemeral_size is used by _create_ephemeral
                    # to build the image if the disk is not already
                    # cached.
                    disk.cache(
                        fetch_func=self._create_ephemeral,
                        fs_label=cache_name,
                        os_type=instance.os_type,
                        filename=cache_name,
                        size=info['virt_disk_size'],
                        ephemeral_size=info['virt_disk_size'] / units.Gi)
                elif cache_name.startswith('swap'):
                    inst_type = instance.get_flavor()
                    swap_mb = inst_type.swap
                    disk.cache(fetch_func=self._create_swap,
                                filename="swap_%s" % swap_mb,
                                size=swap_mb * units.Mi,
                                swap_mb=swap_mb)
                else:
                    self._try_fetch_image_cache(disk,
                                                libvirt_utils.fetch_image,
                                                context, cache_name,
                                                instance.image_ref,
                                                instance,
                                                info['virt_disk_size'],
                                                fallback_from_host)

        # if disk has kernel and ramdisk, just download
        # following normal way.
        self._fetch_instance_kernel_ramdisk(
            context, instance, fallback_from_host=fallback_from_host)

    def post_live_migration(self, context, instance, block_device_info,
                            migrate_data=None):
        # Disconnect from volume server
        block_device_mapping = driver.block_device_info_get_mapping(
                block_device_info)
        connector = self.get_volume_connector(instance)
        volume_api = self._volume_api
        for vol in block_device_mapping:
            # Retrieve connection info from Cinder's initialize_connection API.
            # The info returned will be accurate for the source server.
            volume_id = vol['connection_info']['serial']
            connection_info = volume_api.initialize_connection(context,
                                                               volume_id,
                                                               connector)

            # TODO(leeantho) The following multipath_id logic is temporary
            # and will be removed in the future once os-brick is updated
            # to handle multipath for drivers in a more efficient way.
            # For now this logic is needed to ensure the connection info
            # data is correct.

            # Pull out multipath_id from the bdm information. The
            # multipath_id can be placed into the connection info
            # because it is based off of the volume and will be the
            # same on the source and destination hosts.
            if 'multipath_id' in vol['connection_info']['data']:
                multipath_id = vol['connection_info']['data']['multipath_id']
                connection_info['data']['multipath_id'] = multipath_id

            disk_dev = vol['mount_device'].rpartition("/")[2]
            self._disconnect_volume(connection_info, disk_dev, instance)

    def post_live_migration_at_source(self, context, instance, network_info):
        """Unplug VIFs from networks at source.

        :param context: security context
        :param instance: instance object reference
        :param network_info: instance network information
        """
        self.unplug_vifs(instance, network_info)

    def post_live_migration_at_destination(self, context,
                                           instance,
                                           network_info,
                                           block_migration=False,
                                           block_device_info=None):
        """Post operation of live migration at destination host.

        :param context: security context
        :param instance:
            nova.db.sqlalchemy.models.Instance object
            instance object that is migrated.
        :param network_info: instance network information
        :param block_migration: if true, post operation of block_migration.
        """
        guest = self._host.get_guest(instance)

        # TODO(sahid): In Ocata we have added the migration flag
        # VIR_MIGRATE_PERSIST_DEST to libvirt, which means that the
        # guest XML is going to be set in libvirtd on destination node
        # automatically. However we do not remove that part until P*
        # because during an upgrade, to ensure migrating instances
        # from node running Newton is still going to set the guest XML
        # in libvirtd on destination node.

        # Make sure we define the migrated instance in libvirt
        xml = guest.get_xml_desc()
        self._host.write_instance_config(xml)

    def _get_instance_disk_info_from_config(self, guest_config,
                                            block_device_info):
        """Get the non-volume disk information from the domain xml

        :param LibvirtConfigGuest guest_config: the libvirt domain config
                                                for the instance
        :param dict block_device_info: block device info for BDMs
        :returns disk_info: list of dicts with keys:

          * 'type': the disk type (str)
          * 'path': the disk path (str)
          * 'virt_disk_size': the virtual disk size (int)
          * 'backing_file': backing file of a disk image (str)
          * 'disk_size': physical disk size (int)
          * 'over_committed_disk_size': virt_disk_size - disk_size or 0
        """
        block_device_mapping = driver.block_device_info_get_mapping(
            block_device_info)

        volume_devices = set()
        for vol in block_device_mapping:
            disk_dev = vol['mount_device'].rpartition("/")[2]
            volume_devices.add(disk_dev)

        disk_info = []

        if (guest_config.virt_type == 'parallels' and
                guest_config.os_type == fields.VMMode.EXE):
            node_type = 'filesystem'
        else:
            node_type = 'disk'

        for device in guest_config.devices:
            if device.root_name != node_type:
                continue
            disk_type = device.source_type
            if device.root_name == 'filesystem':
                target = device.target_dir
                if device.source_type == 'file':
                    path = device.source_file
                elif device.source_type == 'block':
                    path = device.source_dev
                else:
                    path = None
            else:
                target = device.target_dev
                path = device.source_path

            if not path:
                LOG.debug('skipping disk for %s as it does not have a path',
                          guest_config.name)
                continue

            if disk_type not in ['file', 'block']:
                LOG.debug('skipping disk because it looks like a volume', path)
                continue

            if target in volume_devices:
                LOG.debug('skipping disk %(path)s (%(target)s) as it is a '
                          'volume', {'path': path, 'target': target})
                continue

            if device.root_name == 'filesystem':
                driver_type = device.driver_type
            else:
                driver_type = device.driver_format
            # get the real disk size or
            # raise a localized error if image is unavailable
            if disk_type == 'file':
                if driver_type == 'ploop':
                    dk_size = 0
                    for dirpath, dirnames, filenames in os.walk(path):
                        for f in filenames:
                            fp = os.path.join(dirpath, f)
                            dk_size += os.path.getsize(fp)
                else:
                    dk_size = disk_api.get_allocated_disk_size(path)

                # NOTE(lyarwood): Fetch the virtual size for all file disks.
                virt_size = disk_api.get_disk_size(path)

            elif disk_type == 'block' and block_device_info:
                # FIXME(lyarwood): There's no reason to use a separate call
                # here, once disk_api uses privsep this should be removed along
                # with the surrounding conditionals to simplify this mess.
                dk_size = lvm.get_volume_size(path)
                # NOTE(lyarwood): As above, we should be using disk_api to
                # fetch the virt-size but can't as it currently runs qemu-img
                # as an unprivileged user, causing a failure for block devices.
                virt_size = dk_size
            else:
                LOG.debug('skipping disk %(path)s (%(target)s) - unable to '
                          'determine if volume',
                          {'path': path, 'target': target})
                continue

            if driver_type in ("qcow2", "ploop"):
                backing_file = libvirt_utils.get_disk_backing_file(path)
                over_commit_size = int(virt_size) - dk_size
            else:
                backing_file = ""
                over_commit_size = 0

            disk_info.append({'type': driver_type,
                              'path': path,
                              'virt_disk_size': virt_size,
                              'backing_file': backing_file,
                              'disk_size': dk_size,
                              'over_committed_disk_size': over_commit_size})
        return disk_info

    def _get_instance_disk_info(self, instance, block_device_info):
        try:
            guest = self._host.get_guest(instance)
            config = guest.get_config()
        except libvirt.libvirtError as ex:
            error_code = ex.get_error_code()
            LOG.warning('Error from libvirt while getting description of '
                        '%(instance_name)s: [Error Code %(error_code)s] '
                        '%(ex)s',
                        {'instance_name': instance.name,
                         'error_code': error_code,
                         'ex': ex},
                        instance=instance)
            raise exception.InstanceNotFound(instance_id=instance.uuid)

        return self._get_instance_disk_info_from_config(config,
                                                        block_device_info)

    def get_instance_disk_info(self, instance,
                               block_device_info=None):
        return jsonutils.dumps(
            self._get_instance_disk_info(instance, block_device_info))

    def _get_disk_over_committed_size_total(self):
        """Return total over committed disk size for all instances."""
        # Disk size that all instance uses : virtual_size - disk_size
        disk_over_committed_size = 0
        instance_domains = self._host.list_instance_domains(only_running=False)
        if not instance_domains:
            return disk_over_committed_size

        # Get all instance uuids
        instance_uuids = [dom.UUIDString() for dom in instance_domains]
        ctx = nova_context.get_admin_context()
        # Get instance object list by uuid filter
        filters = {'uuid': instance_uuids}
        # NOTE(ankit): objects.InstanceList.get_by_filters method is
        # getting called twice one is here and another in the
        # _update_available_resource method of resource_tracker. Since
        # _update_available_resource method is synchronized, there is a
        # possibility the instances list retrieved here to calculate
        # disk_over_committed_size would differ to the list you would get
        # in _update_available_resource method for calculating usages based
        # on instance utilization.
        local_instance_list = objects.InstanceList.get_by_filters(
            ctx, filters, use_slave=True)
        # Convert instance list to dictionary with instance uuid as key.
        local_instances = {inst.uuid: inst for inst in local_instance_list}

        # Get bdms by instance uuids
        bdms = objects.BlockDeviceMappingList.bdms_by_instance_uuid(
            ctx, instance_uuids)

        for dom in instance_domains:
            try:
                guest = libvirt_guest.Guest(dom)
                config = guest.get_config()

                block_device_info = None
                if guest.uuid in local_instances \
                        and (bdms and guest.uuid in bdms):
                    # Get block device info for instance
                    block_device_info = driver.get_block_device_info(
                        local_instances[guest.uuid], bdms[guest.uuid])

                disk_infos = self._get_instance_disk_info_from_config(
                    config, block_device_info)
                if not disk_infos:
                    continue

                for info in disk_infos:
                    disk_over_committed_size += int(
                        info['over_committed_disk_size'])
            except libvirt.libvirtError as ex:
                error_code = ex.get_error_code()
                LOG.warning(
                    'Error from libvirt while getting description of '
                    '%(instance_name)s: [Error Code %(error_code)s] %(ex)s',
                    {'instance_name': guest.name,
                     'error_code': error_code,
                     'ex': ex})
            except OSError as e:
                if e.errno in (errno.ENOENT, errno.ESTALE):
                    LOG.warning('Periodic task is updating the host stat, '
                                'it is trying to get disk %(i_name)s, '
                                'but disk file was removed by concurrent '
                                'operations such as resize.',
                                {'i_name': guest.name})
                elif e.errno == errno.EACCES:
                    LOG.warning('Periodic task is updating the host stat, '
                                'it is trying to get disk %(i_name)s, '
                                'but access is denied. It is most likely '
                                'due to a VM that exists on the compute '
                                'node but is not managed by Nova.',
                                {'i_name': guest.name})
                else:
                    raise
            except exception.VolumeBDMPathNotFound as e:
                LOG.warning('Periodic task is updating the host stats, '
                            'it is trying to get disk info for %(i_name)s, '
                            'but the backing volume block device was removed '
                            'by concurrent operations such as resize. '
                            'Error: %(error)s',
                            {'i_name': guest.name, 'error': e})
            except exception.DiskNotFound:
                with excutils.save_and_reraise_exception() as err_ctxt:
                    # If the instance is undergoing a task state transition,
                    # like moving to another host or is being deleted, we
                    # should ignore this instance and move on.
                    if guest.uuid in local_instances:
                        inst = local_instances[guest.uuid]
                        if inst.task_state is not None:
                            LOG.info('Periodic task is updating the host '
                                     'stats; it is trying to get disk info '
                                     'for %(i_name)s, but the backing disk '
                                     'was removed by a concurrent operation '
                                     '(task_state=%(task_state)s)',
                                     {'i_name': guest.name,
                                      'task_state': inst.task_state},
                                     instance=inst)
                            err_ctxt.reraise = False

            # NOTE(gtt116): give other tasks a chance.
            greenthread.sleep(0)
        return disk_over_committed_size

    def unfilter_instance(self, instance, network_info):
        """See comments of same method in firewall_driver."""
        self.firewall_driver.unfilter_instance(instance,
                                               network_info=network_info)

    def get_available_nodes(self, refresh=False):
        return [self._host.get_hostname()]

    def get_host_cpu_stats(self):
        """Return the current CPU state of the host."""
        return self._host.get_cpu_stats()

    def get_host_uptime(self):
        """Returns the result of calling "uptime"."""
        out, err = utils.execute('env', 'LANG=C', 'uptime')
        return out

    def manage_image_cache(self, context, all_instances):
        """Manage the local cache of images."""
        self.image_cache_manager.update(context, all_instances)

    def _cleanup_remote_migration(self, dest, inst_base, inst_base_resize,
                                  shared_storage=False):
        """Used only for cleanup in case migrate_disk_and_power_off fails."""
        try:
            if os.path.exists(inst_base_resize):
                utils.execute('rm', '-rf', inst_base)
                utils.execute('mv', inst_base_resize, inst_base)
                if not shared_storage:
                    self._remotefs.remove_dir(dest, inst_base)
        except Exception:
            pass

    def _is_storage_shared_with(self, dest, inst_base):
        # NOTE (rmk): There are two methods of determining whether we are
        #             on the same filesystem: the source and dest IP are the
        #             same, or we create a file on the dest system via SSH
        #             and check whether the source system can also see it.
        # NOTE (drwahl): Actually, there is a 3rd way: if images_type is rbd,
        #                it will always be shared storage
        if CONF.libvirt.images_type == 'rbd':
            return True
        shared_storage = (dest == self.get_host_ip_addr())
        if not shared_storage:
            tmp_file = uuid.uuid4().hex + '.tmp'
            tmp_path = os.path.join(inst_base, tmp_file)

            try:
                self._remotefs.create_file(dest, tmp_path)
                if os.path.exists(tmp_path):
                    shared_storage = True
                    os.unlink(tmp_path)
                else:
                    self._remotefs.remove_file(dest, tmp_path)
            except Exception:
                pass
        return shared_storage

    def migrate_disk_and_power_off(self, context, instance, dest,
                                   flavor, network_info,
                                   block_device_info=None,
                                   timeout=0, retry_interval=0):
        LOG.debug("Starting migrate_disk_and_power_off",
                   instance=instance)

        ephemerals = driver.block_device_info_get_ephemerals(block_device_info)

        # get_bdm_ephemeral_disk_size() will return 0 if the new
        # instance's requested block device mapping contain no
        # ephemeral devices. However, we still want to check if
        # the original instance's ephemeral_gb property was set and
        # ensure that the new requested flavor ephemeral size is greater
        eph_size = (block_device.get_bdm_ephemeral_disk_size(ephemerals) or
                    instance.flavor.ephemeral_gb)

        # Checks if the migration needs a disk resize down.
        root_down = flavor.root_gb < instance.flavor.root_gb
        ephemeral_down = flavor.ephemeral_gb < eph_size
        booted_from_volume = self._is_booted_from_volume(block_device_info)

        if (root_down and not booted_from_volume) or ephemeral_down:
            reason = _("Unable to resize disk down.")
            raise exception.InstanceFaultRollback(
                exception.ResizeError(reason=reason))

        # NOTE(dgenin): Migration is not implemented for LVM backed instances.
        if CONF.libvirt.images_type == 'lvm' and not booted_from_volume:
            reason = _("Migration is not supported for LVM backed instances")
            raise exception.InstanceFaultRollback(
                exception.MigrationPreCheckError(reason=reason))

        # copy disks to destination
        # rename instance dir to +_resize at first for using
        # shared storage for instance dir (eg. NFS).
        inst_base = libvirt_utils.get_instance_path(instance)
        inst_base_resize = inst_base + "_resize"
        shared_storage = self._is_storage_shared_with(dest, inst_base)

        # try to create the directory on the remote compute node
        # if this fails we pass the exception up the stack so we can catch
        # failures here earlier
        if not shared_storage:
            try:
                self._remotefs.create_dir(dest, inst_base)
            except processutils.ProcessExecutionError as e:
                reason = _("not able to execute ssh command: %s") % e
                raise exception.InstanceFaultRollback(
                    exception.ResizeError(reason=reason))

        self.power_off(instance, timeout, retry_interval)

        block_device_mapping = driver.block_device_info_get_mapping(
            block_device_info)
        for vol in block_device_mapping:
            connection_info = vol['connection_info']
            disk_dev = vol['mount_device'].rpartition("/")[2]
            self._disconnect_volume(connection_info, disk_dev, instance)

        disk_info = self._get_instance_disk_info(instance, block_device_info)

        try:
            utils.execute('mv', inst_base, inst_base_resize)
            # if we are migrating the instance with shared storage then
            # create the directory.  If it is a remote node the directory
            # has already been created
            if shared_storage:
                dest = None
                utils.execute('mkdir', '-p', inst_base)

            on_execute = lambda process: \
                self.job_tracker.add_job(instance, process.pid)
            on_completion = lambda process: \
                self.job_tracker.remove_job(instance, process.pid)

            for info in disk_info:
                # assume inst_base == dirname(info['path'])
                img_path = info['path']
                fname = os.path.basename(img_path)
                from_path = os.path.join(inst_base_resize, fname)

                # We will not copy over the swap disk here, and rely on
                # finish_migration to re-create it for us. This is ok because
                # the OS is shut down, and as recreating a swap disk is very
                # cheap it is more efficient than copying either locally or
                # over the network. This also means we don't have to resize it.
                if fname == 'disk.swap':
                    continue

                compression = info['type'] not in NO_COMPRESSION_TYPES
                libvirt_utils.copy_image(from_path, img_path, host=dest,
                                         on_execute=on_execute,
                                         on_completion=on_completion,
                                         compression=compression)

            # Ensure disk.info is written to the new path to avoid disks being
            # reinspected and potentially changing format.
            src_disk_info_path = os.path.join(inst_base_resize, 'disk.info')
            if os.path.exists(src_disk_info_path):
                dst_disk_info_path = os.path.join(inst_base, 'disk.info')
                libvirt_utils.copy_image(src_disk_info_path,
                                         dst_disk_info_path,
                                         host=dest, on_execute=on_execute,
                                         on_completion=on_completion)
        except Exception:
            with excutils.save_and_reraise_exception():
                self._cleanup_remote_migration(dest, inst_base,
                                               inst_base_resize,
                                               shared_storage)

        return jsonutils.dumps(disk_info)

    def _wait_for_running(self, instance):
        state = self.get_info(instance).state

        if state == power_state.RUNNING:
            LOG.info("Instance running successfully.", instance=instance)
            raise loopingcall.LoopingCallDone()

    @staticmethod
    def _disk_raw_to_qcow2(path):
        """Converts a raw disk to qcow2."""
        path_qcow = path + '_qcow'
        utils.execute('qemu-img', 'convert', '-f', 'raw',
                      '-O', 'qcow2', path, path_qcow)
        utils.execute('mv', path_qcow, path)

    @staticmethod
    def _disk_qcow2_to_raw(path):
        """Converts a qcow2 disk to raw."""
        path_raw = path + '_raw'
        utils.execute('qemu-img', 'convert', '-f', 'qcow2',
                      '-O', 'raw', path, path_raw)
        utils.execute('mv', path_raw, path)

    def finish_migration(self, context, migration, instance, disk_info,
                         network_info, image_meta, resize_instance,
                         block_device_info=None, power_on=True):
        LOG.debug("Starting finish_migration", instance=instance)

        block_disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
                                                  instance,
                                                  image_meta,
                                                  block_device_info)
        # assume _create_image does nothing if a target file exists.
        # NOTE: This has the intended side-effect of fetching a missing
        # backing file.
        self._create_image(context, instance, block_disk_info['mapping'],
                           block_device_info=block_device_info,
                           ignore_bdi_for_swap=True,
                           fallback_from_host=migration.source_compute)

        # Required by Quobyte CI
        self._ensure_console_log_for_instance(instance)

        gen_confdrive = functools.partial(
            self._create_configdrive, context, instance,
            InjectionInfo(admin_pass=None, network_info=network_info,
                          files=None))

        # Convert raw disks to qcow2 if migrating to host which uses
        # qcow2 from host which uses raw.
        disk_info = jsonutils.loads(disk_info)
        for info in disk_info:
            path = info['path']
            disk_name = os.path.basename(path)

            # NOTE(mdbooth): The code below looks wrong, but is actually
            # required to prevent a security hole when migrating from a host
            # with use_cow_images=False to one with use_cow_images=True.
            # Imagebackend uses use_cow_images to select between the
            # atrociously-named-Raw and Qcow2 backends. The Qcow2 backend
            # writes to disk.info, but does not read it as it assumes qcow2.
            # Therefore if we don't convert raw to qcow2 here, a raw disk will
            # be incorrectly assumed to be qcow2, which is a severe security
            # flaw. The reverse is not true, because the atrociously-named-Raw
            # backend supports both qcow2 and raw disks, and will choose
            # appropriately between them as long as disk.info exists and is
            # correctly populated, which it is because Qcow2 writes to
            # disk.info.
            #
            # In general, we do not yet support format conversion during
            # migration. For example:
            #   * Converting from use_cow_images=True to use_cow_images=False
            #     isn't handled. This isn't a security bug, but is almost
            #     certainly buggy in other cases, as the 'Raw' backend doesn't
            #     expect a backing file.
            #   * Converting to/from lvm and rbd backends is not supported.
            #
            # This behaviour is inconsistent, and therefore undesirable for
            # users. It is tightly-coupled to implementation quirks of 2
            # out of 5 backends in imagebackend and defends against a severe
            # security flaw which is not at all obvious without deep analysis,
            # and is therefore undesirable to developers. We should aim to
            # remove it. This will not be possible, though, until we can
            # represent the storage layout of a specific instance
            # independent of the default configuration of the local compute
            # host.

            # Config disks are hard-coded to be raw even when
            # use_cow_images=True (see _get_disk_config_image_type),so don't
            # need to be converted.
            if (disk_name != 'disk.config' and
                        info['type'] == 'raw' and CONF.use_cow_images):
                self._disk_raw_to_qcow2(info['path'])

        xml = self._get_guest_xml(context, instance, network_info,
                                  block_disk_info, image_meta,
                                  block_device_info=block_device_info)
        # NOTE(mriedem): vifs_already_plugged=True here, regardless of whether
        # or not we've migrated to another host, because we unplug VIFs locally
        # and the status change in the port might go undetected by the neutron
        # L2 agent (or neutron server) so neutron may not know that the VIF was
        # unplugged in the first place and never send an event.
        guest = self._create_domain_and_network(context, xml, instance,
                                        network_info,
                                        block_device_info=block_device_info,
                                        power_on=power_on,
                                        vifs_already_plugged=True,
                                        post_xml_callback=gen_confdrive)
        if power_on:
            timer = loopingcall.FixedIntervalLoopingCall(
                                                    self._wait_for_running,
                                                    instance)
            timer.start(interval=0.5).wait()

            # Sync guest time after migration.
            guest.sync_guest_time()

        LOG.debug("finish_migration finished successfully.", instance=instance)

    def _cleanup_failed_migration(self, inst_base):
        """Make sure that a failed migrate doesn't prevent us from rolling
        back in a revert.
        """
        try:
            shutil.rmtree(inst_base)
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise

    def finish_revert_migration(self, context, instance, network_info,
                                block_device_info=None, power_on=True):
        LOG.debug("Starting finish_revert_migration",
                  instance=instance)

        inst_base = libvirt_utils.get_instance_path(instance)
        inst_base_resize = inst_base + "_resize"

        # NOTE(danms): if we're recovering from a failed migration,
        # make sure we don't have a left-over same-host base directory
        # that would conflict. Also, don't fail on the rename if the
        # failure happened early.
        if os.path.exists(inst_base_resize):
            self._cleanup_failed_migration(inst_base)
            utils.execute('mv', inst_base_resize, inst_base)

        root_disk = self.image_backend.by_name(instance, 'disk')
        # Once we rollback, the snapshot is no longer needed, so remove it
        # TODO(nic): Remove the try/except/finally in a future release
        # To avoid any upgrade issues surrounding instances being in pending
        # resize state when the software is updated, this portion of the
        # method logs exceptions rather than failing on them.  Once it can be
        # reasonably assumed that no such instances exist in the wild
        # anymore, the try/except/finally should be removed,
        # and ignore_errors should be set back to False (the default) so
        # that problems throw errors, like they should.
        if root_disk.exists():
            try:
                root_disk.rollback_to_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME)
            except exception.SnapshotNotFound:
                LOG.warning("Failed to rollback snapshot (%s)",
                            libvirt_utils.RESIZE_SNAPSHOT_NAME)
            finally:
                root_disk.remove_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME,
                                      ignore_errors=True)

        disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
                                            instance,
                                            instance.image_meta,
                                            block_device_info)
        xml = self._get_guest_xml(context, instance, network_info, disk_info,
                                  instance.image_meta,
                                  block_device_info=block_device_info)
        self._create_domain_and_network(context, xml, instance, network_info,
                                        block_device_info=block_device_info,
                                        power_on=power_on,
                                        vifs_already_plugged=True)

        if power_on:
            timer = loopingcall.FixedIntervalLoopingCall(
                                                    self._wait_for_running,
                                                    instance)
            timer.start(interval=0.5).wait()

        LOG.debug("finish_revert_migration finished successfully.",
                  instance=instance)

    def confirm_migration(self, context, migration, instance, network_info):
        """Confirms a resize, destroying the source VM."""
        self._cleanup_resize(context, instance, network_info)

    @staticmethod
    def _get_io_devices(xml_doc):
        """get the list of io devices from the xml document."""
        result = {"volumes": [], "ifaces": []}
        try:
            doc = etree.fromstring(xml_doc)
        except Exception:
            return result
        blocks = [('./devices/disk', 'volumes'),
            ('./devices/interface', 'ifaces')]
        for block, key in blocks:
            section = doc.findall(block)
            for node in section:
                for child in node.getchildren():
                    if child.tag == 'target' and child.get('dev'):
                        result[key].append(child.get('dev'))
        return result

    def get_diagnostics(self, instance):
        guest = self._host.get_guest(instance)

        # TODO(sahid): We are converting all calls from a
        # virDomain object to use nova.virt.libvirt.Guest.
        # We should be able to remove domain at the end.
        domain = guest._domain
        output = {}
        # get cpu time, might launch an exception if the method
        # is not supported by the underlying hypervisor being
        # used by libvirt
        try:
            for vcpu in guest.get_vcpus_info():
                output["cpu" + str(vcpu.id) + "_time"] = vcpu.time
        except libvirt.libvirtError:
            pass
        # get io status
        xml = guest.get_xml_desc()
        dom_io = LibvirtDriver._get_io_devices(xml)
        for guest_disk in dom_io["volumes"]:
            try:
                # blockStats might launch an exception if the method
                # is not supported by the underlying hypervisor being
                # used by libvirt
                stats = domain.blockStats(guest_disk)
                output[guest_disk + "_read_req"] = stats[0]
                output[guest_disk + "_read"] = stats[1]
                output[guest_disk + "_write_req"] = stats[2]
                output[guest_disk + "_write"] = stats[3]
                output[guest_disk + "_errors"] = stats[4]
            except libvirt.libvirtError:
                pass
        for interface in dom_io["ifaces"]:
            try:
                # interfaceStats might launch an exception if the method
                # is not supported by the underlying hypervisor being
                # used by libvirt
                stats = domain.interfaceStats(interface)
                output[interface + "_rx"] = stats[0]
                output[interface + "_rx_packets"] = stats[1]
                output[interface + "_rx_errors"] = stats[2]
                output[interface + "_rx_drop"] = stats[3]
                output[interface + "_tx"] = stats[4]
                output[interface + "_tx_packets"] = stats[5]
                output[interface + "_tx_errors"] = stats[6]
                output[interface + "_tx_drop"] = stats[7]
            except libvirt.libvirtError:
                pass
        output["memory"] = domain.maxMemory()
        # memoryStats might launch an exception if the method
        # is not supported by the underlying hypervisor being
        # used by libvirt
        try:
            mem = domain.memoryStats()
            for key in mem.keys():
                output["memory-" + key] = mem[key]
        except (libvirt.libvirtError, AttributeError):
            pass
        return output

    def get_instance_diagnostics(self, instance):
        guest = self._host.get_guest(instance)

        # TODO(sahid): We are converting all calls from a
        # virDomain object to use nova.virt.libvirt.Guest.
        # We should be able to remove domain at the end.
        domain = guest._domain

        xml = guest.get_xml_desc()
        xml_doc = etree.fromstring(xml)

        # TODO(sahid): Needs to use get_info but more changes have to
        # be done since a mapping STATE_MAP LIBVIRT_POWER_STATE is
        # needed.
        (state, max_mem, mem, num_cpu, cpu_time) = \
            guest._get_domain_info(self._host)
        config_drive = configdrive.required_by(instance)
        launched_at = timeutils.normalize_time(instance.launched_at)
        uptime = timeutils.delta_seconds(launched_at,
                                         timeutils.utcnow())
        diags = diagnostics_obj.Diagnostics(state=power_state.STATE_MAP[state],
                                        driver='libvirt',
                                        config_drive=config_drive,
                                        hypervisor=CONF.libvirt.virt_type,
                                        hypervisor_os='linux',
                                        uptime=uptime)
        diags.memory_details = diagnostics_obj.MemoryDiagnostics(
            maximum=max_mem / units.Mi,
            used=mem / units.Mi)

        # get cpu time, might launch an exception if the method
        # is not supported by the underlying hypervisor being
        # used by libvirt
        try:
            for vcpu in guest.get_vcpus_info():
                diags.add_cpu(id=vcpu.id, time=vcpu.time)
        except libvirt.libvirtError:
            pass
        # get io status
        dom_io = LibvirtDriver._get_io_devices(xml)
        for guest_disk in dom_io["volumes"]:
            try:
                # blockStats might launch an exception if the method
                # is not supported by the underlying hypervisor being
                # used by libvirt
                stats = domain.blockStats(guest_disk)
                diags.add_disk(read_bytes=stats[1],
                               read_requests=stats[0],
                               write_bytes=stats[3],
                               write_requests=stats[2],
                               errors_count=stats[4])
            except libvirt.libvirtError:
                pass
        for interface in dom_io["ifaces"]:
            try:
                # interfaceStats might launch an exception if the method
                # is not supported by the underlying hypervisor being
                # used by libvirt
                stats = domain.interfaceStats(interface)
                diags.add_nic(rx_octets=stats[0],
                              rx_errors=stats[2],
                              rx_drop=stats[3],
                              rx_packets=stats[1],
                              tx_octets=stats[4],
                              tx_errors=stats[6],
                              tx_drop=stats[7],
                              tx_packets=stats[5])
            except libvirt.libvirtError:
                pass

        # Update mac addresses of interface if stats have been reported
        if diags.nic_details:
            nodes = xml_doc.findall('./devices/interface/mac')
            for index, node in enumerate(nodes):
                diags.nic_details[index].mac_address = node.get('address')
        return diags

    @staticmethod
    def _prepare_device_bus(dev):
        """Determines the device bus and its hypervisor assigned address
        """
        bus = None
        address = (dev.device_addr.format_address() if
                   dev.device_addr else None)
        if isinstance(dev.device_addr,
                      vconfig.LibvirtConfigGuestDeviceAddressPCI):
            bus = objects.PCIDeviceBus()
        elif isinstance(dev, vconfig.LibvirtConfigGuestDisk):
            if dev.target_bus == 'scsi':
                bus = objects.SCSIDeviceBus()
            elif dev.target_bus == 'ide':
                bus = objects.IDEDeviceBus()
            elif dev.target_bus == 'usb':
                bus = objects.USBDeviceBus()
        if address is not None and bus is not None:
            bus.address = address
        return bus

    def _build_device_metadata(self, context, instance):
        """Builds a metadata object for instance devices, that maps the user
           provided tag to the hypervisor assigned device address.
        """
        def _get_device_name(bdm):
            return block_device.strip_dev(bdm.device_name)

        network_info = instance.info_cache.network_info
        vlans_by_mac = netutils.get_cached_vifs_with_vlan(network_info)
        vifs = objects.VirtualInterfaceList.get_by_instance_uuid(context,
                                                                 instance.uuid)
        vifs_to_expose = {vif.address: vif for vif in vifs
                          if ('tag' in vif and vif.tag) or
                             vlans_by_mac.get(vif.address)}
        # TODO(mriedem): We should be able to avoid the DB query here by using
        # block_device_info['block_device_mapping'] which is passed into most
        # methods that call this function.
        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
            context, instance.uuid)
        tagged_bdms = {_get_device_name(bdm): bdm for bdm in bdms if bdm.tag}

        devices = []
        guest = self._host.get_guest(instance)
        xml = guest.get_xml_desc()
        xml_dom = etree.fromstring(xml)
        guest_config = vconfig.LibvirtConfigGuest()
        guest_config.parse_dom(xml_dom)

        for dev in guest_config.devices:
            # Build network interfaces related metadata
            if isinstance(dev, vconfig.LibvirtConfigGuestInterface):
                vif = vifs_to_expose.get(dev.mac_addr)
                if not vif:
                    continue
                bus = self._prepare_device_bus(dev)
                device = objects.NetworkInterfaceMetadata(mac=vif.address)
                if 'tag' in vif and vif.tag:
                    device.tags = [vif.tag]
                if bus:
                    device.bus = bus
                vlan = vlans_by_mac.get(vif.address)
                if vlan:
                    device.vlan = int(vlan)
                devices.append(device)

            # Build disks related metadata
            if isinstance(dev, vconfig.LibvirtConfigGuestDisk):
                bdm = tagged_bdms.get(dev.target_dev)
                if not bdm:
                    continue
                bus = self._prepare_device_bus(dev)
                device = objects.DiskMetadata(tags=[bdm.tag])
                # NOTE(artom) Setting the serial (which corresponds to
                # volume_id in BlockDeviceMapping) in DiskMetadata allows us to
                # find the disks's BlockDeviceMapping object when we detach the
                # volume and want to clean up its metadata.
                device.serial = bdm.volume_id
                if bus:
                    device.bus = bus
                devices.append(device)
        if devices:
            dev_meta = objects.InstanceDeviceMetadata(devices=devices)
            return dev_meta

    def instance_on_disk(self, instance):
        # ensure directories exist and are writable
        instance_path = libvirt_utils.get_instance_path(instance)
        LOG.debug('Checking instance files accessibility %s', instance_path,
                  instance=instance)
        shared_instance_path = os.access(instance_path, os.W_OK)
        # NOTE(flwang): For shared block storage scenario, the file system is
        # not really shared by the two hosts, but the volume of evacuated
        # instance is reachable.
        shared_block_storage = (self.image_backend.backend().
                                is_shared_block_storage())
        return shared_instance_path or shared_block_storage

    def inject_network_info(self, instance, nw_info):
        self.firewall_driver.setup_basic_filtering(instance, nw_info)

    def delete_instance_files(self, instance):
        target = libvirt_utils.get_instance_path(instance)
        # A resize may be in progress
        target_resize = target + '_resize'
        # Other threads may attempt to rename the path, so renaming the path
        # to target + '_del' (because it is atomic) and iterating through
        # twice in the unlikely event that a concurrent rename occurs between
        # the two rename attempts in this method. In general this method
        # should be fairly thread-safe without these additional checks, since
        # other operations involving renames are not permitted when the task
        # state is not None and the task state should be set to something
        # other than None by the time this method is invoked.
        target_del = target + '_del'
        for i in range(2):
            try:
                utils.execute('mv', target, target_del)
                break
            except Exception:
                pass
            try:
                utils.execute('mv', target_resize, target_del)
                break
            except Exception:
                pass
        # Either the target or target_resize path may still exist if all
        # rename attempts failed.
        remaining_path = None
        for p in (target, target_resize):
            if os.path.exists(p):
                remaining_path = p
                break

        # A previous delete attempt may have been interrupted, so target_del
        # may exist even if all rename attempts during the present method
        # invocation failed due to the absence of both target and
        # target_resize.
        if not remaining_path and os.path.exists(target_del):
            self.job_tracker.terminate_jobs(instance)

            LOG.info('Deleting instance files %s', target_del,
                     instance=instance)
            remaining_path = target_del
            try:
                shutil.rmtree(target_del)
            except OSError as e:
                LOG.error('Failed to cleanup directory %(target)s: %(e)s',
                          {'target': target_del, 'e': e}, instance=instance)

        # It is possible that the delete failed, if so don't mark the instance
        # as cleaned.
        if remaining_path and os.path.exists(remaining_path):
            LOG.info('Deletion of %s failed', remaining_path,
                     instance=instance)
            return False

        LOG.info('Deletion of %s complete', target_del, instance=instance)
        return True

    @property
    def need_legacy_block_device_info(self):
        return False

    def default_root_device_name(self, instance, image_meta, root_bdm):
        disk_bus = blockinfo.get_disk_bus_for_device_type(
            instance, CONF.libvirt.virt_type, image_meta, "disk")
        cdrom_bus = blockinfo.get_disk_bus_for_device_type(
            instance, CONF.libvirt.virt_type, image_meta, "cdrom")
        root_info = blockinfo.get_root_info(
            instance, CONF.libvirt.virt_type, image_meta,
            root_bdm, disk_bus, cdrom_bus)
        return block_device.prepend_dev(root_info['dev'])

    def default_device_names_for_instance(self, instance, root_device_name,
                                          *block_device_lists):
        block_device_mapping = list(itertools.chain(*block_device_lists))
        # NOTE(ndipanov): Null out the device names so that blockinfo code
        #                 will assign them
        for bdm in block_device_mapping:
            if bdm.device_name is not None:
                LOG.warning(
                    "Ignoring supplied device name: %(device_name)s. "
                    "Libvirt can't honour user-supplied dev names",
                    {'device_name': bdm.device_name}, instance=instance)
                bdm.device_name = None
        block_device_info = driver.get_block_device_info(instance,
                                                         block_device_mapping)

        blockinfo.default_device_names(CONF.libvirt.virt_type,
                                       nova_context.get_admin_context(),
                                       instance,
                                       block_device_info,
                                       instance.image_meta)

    def get_device_name_for_instance(self, instance, bdms, block_device_obj):
        block_device_info = driver.get_block_device_info(instance, bdms)
        instance_info = blockinfo.get_disk_info(
                CONF.libvirt.virt_type, instance,
                instance.image_meta, block_device_info=block_device_info)

        suggested_dev_name = block_device_obj.device_name
        if suggested_dev_name is not None:
            LOG.warning(
                'Ignoring supplied device name: %(suggested_dev)s',
                {'suggested_dev': suggested_dev_name}, instance=instance)

        # NOTE(ndipanov): get_info_from_bdm will generate the new device name
        #                 only when it's actually not set on the bd object
        block_device_obj.device_name = None
        disk_info = blockinfo.get_info_from_bdm(
            instance, CONF.libvirt.virt_type, instance.image_meta,
            block_device_obj, mapping=instance_info['mapping'])
        return block_device.prepend_dev(disk_info['dev'])

    def is_supported_fs_format(self, fs_type):
        return fs_type in [disk_api.FS_FORMAT_EXT2, disk_api.FS_FORMAT_EXT3,
                           disk_api.FS_FORMAT_EXT4, disk_api.FS_FORMAT_XFS]