summaryrefslogtreecommitdiff
path: root/nova/compute/manager.py
blob: f25d037c504349ab314cee094832231058ffdaa0 (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
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
#    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.

"""Handles all processes relating to instances (guest vms).

The :py:class:`ComputeManager` class is a :py:class:`nova.manager.Manager` that
handles RPC calls relating to creating instances.  It is responsible for
building a disk image, launching it via the underlying virtualization driver,
responding to calls to check its state, attaching persistent storage, and
terminating it.

"""

import base64
import binascii
import contextlib
import copy
import functools
import inspect
import math
import sys
import time
import traceback
import typing as ty

from cinderclient import exceptions as cinder_exception
from cursive import exception as cursive_exception
import eventlet.event
from eventlet import greenthread
import eventlet.semaphore
import eventlet.timeout
import futurist
from keystoneauth1 import exceptions as keystone_exception
import os_traits
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_serialization import jsonutils
from oslo_service import loopingcall
from oslo_service import periodic_task
from oslo_utils import excutils
from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import units

from nova.accelerator import cyborg
from nova import block_device
from nova.compute import api as compute
from nova.compute import build_results
from nova.compute import claims
from nova.compute import power_state
from nova.compute import resource_tracker
from nova.compute import rpcapi as compute_rpcapi
from nova.compute import task_states
from nova.compute import utils as compute_utils
from nova.compute.utils import wrap_instance_event
from nova.compute import vm_states
from nova import conductor
import nova.conf
import nova.context
from nova import exception
from nova import exception_wrapper
from nova.i18n import _
from nova.image import glance
from nova import manager
from nova.network import model as network_model
from nova.network import neutron
from nova import objects
from nova.objects import base as obj_base
from nova.objects import external_event as external_event_obj
from nova.objects import fields
from nova.objects import instance as obj_instance
from nova.objects import migrate_data as migrate_data_obj
from nova.pci import request as pci_req_module
from nova.pci import whitelist
from nova import safe_utils
from nova.scheduler.client import query
from nova.scheduler.client import report
from nova.scheduler import utils as scheduler_utils
from nova import utils
from nova.virt import block_device as driver_block_device
from nova.virt import configdrive
from nova.virt import driver
from nova.virt import event as virtevent
from nova.virt import hardware
from nova.virt import storage_users
from nova.virt import virtapi
from nova.volume import cinder

CONF = nova.conf.CONF

LOG = logging.getLogger(__name__)

wrap_exception = functools.partial(
    exception_wrapper.wrap_exception, service='compute', binary='nova-compute')


@contextlib.contextmanager
def errors_out_migration_ctxt(migration):
    """Context manager to error out migration on failure."""

    try:
        yield
    except Exception:
        with excutils.save_and_reraise_exception():
            if migration:
                # We may have been passed None for our migration if we're
                # receiving from an older client. The migration will be
                # errored via the legacy path.
                migration.status = 'error'
                try:
                    migration.save()
                except Exception:
                    LOG.debug(
                        'Error setting migration status for instance %s.',
                        migration.instance_uuid, exc_info=True)


@utils.expects_func_args('migration')
def errors_out_migration(function):
    """Decorator to error out migration on failure."""

    @functools.wraps(function)
    def decorated_function(self, context, *args, **kwargs):
        wrapped_func = safe_utils.get_wrapped_function(function)
        keyed_args = inspect.getcallargs(wrapped_func, self, context,
                                         *args, **kwargs)
        migration = keyed_args['migration']
        with errors_out_migration_ctxt(migration):
            return function(self, context, *args, **kwargs)

    return decorated_function


@utils.expects_func_args('instance')
def reverts_task_state(function):
    """Decorator to revert task_state on failure."""

    @functools.wraps(function)
    def decorated_function(self, context, *args, **kwargs):
        try:
            return function(self, context, *args, **kwargs)
        except exception.UnexpectedTaskStateError as e:
            # Note(maoy): unexpected task state means the current
            # task is preempted. Do not clear task state in this
            # case.
            with excutils.save_and_reraise_exception():
                LOG.info("Task possibly preempted: %s",
                         e.format_message())
        except Exception:
            with excutils.save_and_reraise_exception():
                wrapped_func = safe_utils.get_wrapped_function(function)
                keyed_args = inspect.getcallargs(wrapped_func, self, context,
                                                 *args, **kwargs)
                # NOTE(mriedem): 'instance' must be in keyed_args because we
                # have utils.expects_func_args('instance') decorating this
                # method.
                instance = keyed_args['instance']
                original_task_state = instance.task_state
                try:
                    self._instance_update(context, instance, task_state=None)
                    LOG.info("Successfully reverted task state from %s on "
                             "failure for instance.",
                             original_task_state, instance=instance)
                except exception.InstanceNotFound:
                    # We might delete an instance that failed to build shortly
                    # after it errored out this is an expected case and we
                    # should not trace on it.
                    pass
                except Exception as e:
                    LOG.warning("Failed to revert task state for instance. "
                                "Error: %s", e, instance=instance)

    return decorated_function


@utils.expects_func_args('instance')
def wrap_instance_fault(function):
    """Wraps a method to catch exceptions related to instances.

    This decorator wraps a method to catch any exceptions having to do with
    an instance that may get thrown. It then logs an instance fault in the db.
    """

    @functools.wraps(function)
    def decorated_function(self, context, *args, **kwargs):
        try:
            return function(self, context, *args, **kwargs)
        except exception.InstanceNotFound:
            raise
        except Exception as e:
            # NOTE(gtt): If argument 'instance' is in args rather than kwargs,
            # we will get a KeyError exception which will cover up the real
            # exception. So, we update kwargs with the values from args first.
            # then, we can get 'instance' from kwargs easily.
            kwargs.update(dict(zip(function.__code__.co_varnames[2:], args)))

            with excutils.save_and_reraise_exception():
                compute_utils.add_instance_fault_from_exc(context,
                        kwargs['instance'], e, sys.exc_info())

    return decorated_function


@utils.expects_func_args('image_id', 'instance')
def delete_image_on_error(function):
    """Used for snapshot related method to ensure the image created in
    compute.api is deleted when an error occurs.
    """

    @functools.wraps(function)
    def decorated_function(self, context, image_id, instance,
                           *args, **kwargs):
        try:
            return function(self, context, image_id, instance,
                            *args, **kwargs)
        except Exception:
            with excutils.save_and_reraise_exception():
                compute_utils.delete_image(
                    context, instance, self.image_api, image_id,
                    log_exc_info=True)

    return decorated_function


# Each collection of events is a dict of eventlet Events keyed by a tuple of
# event name and associated tag
_InstanceEvents = ty.Dict[ty.Tuple[str, str], eventlet.event.Event]


class InstanceEvents(object):
    def __init__(self):
        self._events: ty.Optional[ty.Dict[str, _InstanceEvents]] = {}

    @staticmethod
    def _lock_name(instance) -> str:
        return '%s-%s' % (instance.uuid, 'events')

    def prepare_for_instance_event(
        self,
        instance: 'objects.Instance',
        name: str,
        tag: str,
    ) -> eventlet.event.Event:
        """Prepare to receive an event for an instance.

        This will register an event for the given instance that we will
        wait on later. This should be called before initiating whatever
        action will trigger the event. The resulting eventlet.event.Event
        object should be wait()'d on to ensure completion.

        :param instance: the instance for which the event will be generated
        :param name: the name of the event we're expecting
        :param tag: the tag associated with the event we're expecting
        :returns: an event object that should be wait()'d on
        """
        @utils.synchronized(self._lock_name(instance))
        def _create_or_get_event():
            if self._events is None:
                # NOTE(danms): We really should have a more specific error
                # here, but this is what we use for our default error case
                raise exception.NovaException(
                    'In shutdown, no new events can be scheduled')

            instance_events = self._events.setdefault(instance.uuid, {})
            return instance_events.setdefault((name, tag),
                                              eventlet.event.Event())
        LOG.debug('Preparing to wait for external event %(name)s-%(tag)s',
                  {'name': name, 'tag': tag}, instance=instance)
        return _create_or_get_event()

    def pop_instance_event(self, instance, event):
        """Remove a pending event from the wait list.

        This will remove a pending event from the wait list so that it
        can be used to signal the waiters to wake up.

        :param instance: the instance for which the event was generated
        :param event: the nova.objects.external_event.InstanceExternalEvent
                      that describes the event
        :returns: the eventlet.event.Event object on which the waiters
                  are blocked
        """
        no_events_sentinel = object()
        no_matching_event_sentinel = object()

        @utils.synchronized(self._lock_name(instance))
        def _pop_event():
            if self._events is None:
                LOG.debug('Unexpected attempt to pop events during shutdown',
                          instance=instance)
                return no_events_sentinel
            events = self._events.get(instance.uuid)
            if not events:
                return no_events_sentinel
            _event = events.pop((event.name, event.tag), None)
            if not events:
                del self._events[instance.uuid]
            if _event is None:
                return no_matching_event_sentinel
            return _event

        result = _pop_event()
        if result is no_events_sentinel:
            LOG.debug('No waiting events found dispatching %(event)s',
                      {'event': event.key},
                      instance=instance)
            return None
        elif result is no_matching_event_sentinel:
            LOG.debug(
                'No event matching %(event)s in %(events)s',
                {
                    'event': event.key,
                    # mypy can't identify the none check in _pop_event
                    'events': self._events.get(  # type: ignore
                        instance.uuid, {}).keys(),
                },
                instance=instance,
            )
            return None
        else:
            return result

    def clear_events_for_instance(self, instance):
        """Remove all pending events for an instance.

        This will remove all events currently pending for an instance
        and return them (indexed by event name).

        :param instance: the instance for which events should be purged
        :returns: a dictionary of {event_name: eventlet.event.Event}
        """
        @utils.synchronized(self._lock_name(instance))
        def _clear_events():
            if self._events is None:
                LOG.debug('Unexpected attempt to clear events during shutdown',
                          instance=instance)
                return dict()
            # NOTE(danms): We have historically returned the raw internal
            # format here, which is {event.key: [events, ...])} so just
            # trivially convert it here.
            return {'%s-%s' % k: e
                    for k, e in self._events.pop(instance.uuid, {}).items()}
        return _clear_events()

    def cancel_all_events(self):
        if self._events is None:
            LOG.debug('Unexpected attempt to cancel events during shutdown.')
            return
        our_events = self._events
        # NOTE(danms): Block new events
        self._events = None

        for instance_uuid, events in our_events.items():
            for (name, tag), eventlet_event in events.items():
                LOG.debug('Canceling in-flight event %(name)s-%(tag)s for '
                          'instance %(instance_uuid)s',
                          {'name': name,
                           'tag': tag,
                           'instance_uuid': instance_uuid})
                event = objects.InstanceExternalEvent(
                    instance_uuid=instance_uuid,
                    name=name, status='failed',
                    tag=tag, data={})
                eventlet_event.send(event)


class ComputeVirtAPI(virtapi.VirtAPI):
    def __init__(self, compute):
        super(ComputeVirtAPI, self).__init__()
        self._compute = compute
        self.reportclient = compute.reportclient

        class ExitEarly(Exception):
            def __init__(self, events):
                super(Exception, self).__init__()
                self.events = events

        self._exit_early_exc = ExitEarly

    def exit_wait_early(self, events):
        """Exit a wait_for_instance_event() immediately and avoid
        waiting for some events.

        :param: events: A list of (name, tag) tuples for events that we should
                        skip waiting for during a wait_for_instance_event().
        """
        raise self._exit_early_exc(events=events)

    def _default_error_callback(self, event_name, instance):
        raise exception.NovaException(_('Instance event failed'))

    class _InstanceEvent:
        EXPECTED = "expected"
        WAITING = "waiting"
        RECEIVED = "received"
        RECEIVED_EARLY = "received early"
        TIMED_OUT = "timed out"
        RECEIVED_NOT_PROCESSED = "received but not processed"

        def __init__(self, name: str, event: eventlet.event.Event) -> None:
            self.name = name
            self.event = event
            self.status = self.EXPECTED
            self.wait_time = None

        def mark_as_received_early(self) -> None:
            self.status = self.RECEIVED_EARLY

        def is_received_early(self) -> bool:
            return self.status == self.RECEIVED_EARLY

        def _update_status_no_wait(self):
            if self.status == self.EXPECTED and self.event.ready():
                self.status = self.RECEIVED_NOT_PROCESSED

        def wait(self) -> 'objects.InstanceExternalEvent':
            self.status = self.WAITING
            try:
                with timeutils.StopWatch() as sw:
                    instance_event = self.event.wait()
            except eventlet.timeout.Timeout:
                self.status = self.TIMED_OUT
                self.wait_time = sw.elapsed()

                raise

            self.status = self.RECEIVED
            self.wait_time = sw.elapsed()
            return instance_event

        def __str__(self) -> str:
            self._update_status_no_wait()
            if self.status == self.EXPECTED:
                return f"{self.name}: expected but not received"
            if self.status == self.RECEIVED:
                return (
                    f"{self.name}: received after waiting "
                    f"{self.wait_time:.2f} seconds")
            if self.status == self.TIMED_OUT:
                return (
                    f"{self.name}: timed out after "
                    f"{self.wait_time:.2f} seconds")
            return f"{self.name}: {self.status}"

    @staticmethod
    def _wait_for_instance_events(
        instance: 'objects.Instance',
        events: dict,
        error_callback: ty.Callable,
    ) -> None:
        for event_name, event in events.items():
            if event.is_received_early():
                continue
            else:
                actual_event = event.wait()
                if actual_event.status == 'completed':
                    continue
            # If we get here, we have an event that was not completed,
            # nor skipped via exit_wait_early(). Decide whether to
            # keep waiting by calling the error_callback() hook.
            decision = error_callback(event_name, instance)
            if decision is False:
                break

    @contextlib.contextmanager
    def wait_for_instance_event(self, instance, event_names, deadline=300,
                                error_callback=None):
        """Plan to wait for some events, run some code, then wait.

        This context manager will first create plans to wait for the
        provided event_names, yield, and then wait for all the scheduled
        events to complete.

        Note that this uses an eventlet.timeout.Timeout to bound the
        operation, so callers should be prepared to catch that
        failure and handle that situation appropriately.

        If the event is not received by the specified timeout deadline,
        eventlet.timeout.Timeout is raised.

        If the event is received but did not have a 'completed'
        status, a NovaException is raised.  If an error_callback is
        provided, instead of raising an exception as detailed above
        for the failure case, the callback will be called with the
        event_name and instance, and can return True to continue
        waiting for the rest of the events, False to stop processing,
        or raise an exception which will bubble up to the waiter.

        If the inner code wishes to abort waiting for one or more
        events because it knows some state to be finished or condition
        to be satisfied, it can use VirtAPI.exit_wait_early() with a
        list of event (name,tag) items to avoid waiting for those
        events upon context exit. Note that exit_wait_early() exits
        the context immediately and should be used to signal that all
        work has been completed and provide the unified list of events
        that need not be waited for. Waiting for the remaining events
        will begin immediately upon early exit as if the context was
        exited normally.

        :param instance: The instance for which an event is expected
        :param event_names: A list of event names. Each element is a
                            tuple of strings to indicate (name, tag),
                            where name is required, but tag may be None.
        :param deadline: Maximum number of seconds we should wait for all
                         of the specified events to arrive.
        :param error_callback: A function to be called if an event arrives

        """

        if error_callback is None:
            error_callback = self._default_error_callback
        events = {}
        for event_name in event_names:
            name, tag = event_name
            event_name = objects.InstanceExternalEvent.make_key(name, tag)
            try:
                event = (
                    self._compute.instance_events.prepare_for_instance_event(
                        instance, name, tag))
                events[event_name] = self._InstanceEvent(event_name, event)
            except exception.NovaException:
                error_callback(event_name, instance)
                # NOTE(danms): Don't wait for any of the events. They
                # should all be canceled and fired immediately below,
                # but don't stick around if not.
                deadline = 0
        try:
            yield
        except self._exit_early_exc as e:
            early_events = set([objects.InstanceExternalEvent.make_key(n, t)
                                for n, t in e.events])

            # If there are expected events that received early, mark them,
            # so they won't be waited for later
            for early_event_name in early_events:
                if early_event_name in events:
                    events[early_event_name].mark_as_received_early()

        sw = timeutils.StopWatch()
        sw.start()
        try:
            with eventlet.timeout.Timeout(deadline):
                self._wait_for_instance_events(
                    instance, events, error_callback)
        except eventlet.timeout.Timeout:
            LOG.warning(
                'Timeout waiting for %(events)s for instance with '
                'vm_state %(vm_state)s and task_state %(task_state)s. '
                'Event states are: %(event_states)s',
                {
                    'events': list(events.keys()),
                    'vm_state': instance.vm_state,
                    'task_state': instance.task_state,
                    'event_states':
                        ', '.join([str(event) for event in events.values()]),
                },
                instance=instance)

            raise

        LOG.debug('Instance event wait completed in %i seconds for %s',
                  sw.elapsed(),
                  ','.join(x[0] for x in event_names),
                  instance=instance)

    def update_compute_provider_status(self, context, rp_uuid, enabled):
        """Used to add/remove the COMPUTE_STATUS_DISABLED trait on the provider

        :param context: nova auth RequestContext
        :param rp_uuid: UUID of a compute node resource provider in Placement
        :param enabled: True if the node is enabled in which case the trait
            would be removed, False if the node is disabled in which case
            the trait would be added.
        :raises: ResourceProviderTraitRetrievalFailed
        :raises: ResourceProviderUpdateConflict
        :raises: ResourceProviderUpdateFailed
        :raises: TraitRetrievalFailed
        :raises: keystoneauth1.exceptions.ClientException
        """
        trait_name = os_traits.COMPUTE_STATUS_DISABLED
        # Get the current traits (and generation) for the provider.
        # TODO(mriedem): Leverage the ProviderTree cache in get_provider_traits
        trait_info = self.reportclient.get_provider_traits(context, rp_uuid)
        # If the host is enabled, remove the trait (if set), else add
        # the trait if it doesn't already exist.
        original_traits = trait_info.traits
        new_traits = None
        if enabled and trait_name in original_traits:
            new_traits = original_traits - {trait_name}
            LOG.debug('Removing trait %s from compute node resource '
                      'provider %s in placement.', trait_name, rp_uuid)
        elif not enabled and trait_name not in original_traits:
            new_traits = original_traits | {trait_name}
            LOG.debug('Adding trait %s to compute node resource '
                      'provider %s in placement.', trait_name, rp_uuid)

        if new_traits is not None:
            self.reportclient.set_traits_for_provider(
                context, rp_uuid, new_traits, generation=trait_info.generation)


class ComputeManager(manager.Manager):
    """Manages the running instances from creation to destruction."""

    target = messaging.Target(version='6.1')

    def __init__(self, compute_driver=None, *args, **kwargs):
        """Load configuration options and connect to the hypervisor."""
        # We want the ComputeManager, ResourceTracker and ComputeVirtAPI all
        # using the same instance of SchedulerReportClient which has the
        # ProviderTree cache for this compute service.
        # NOTE(danms): We do not use the global placement client
        # singleton here, because the above-mentioned stack of objects
        # maintain local state in the client. Thus, keeping our own
        # private object for that stack avoids any potential conflict
        # with other users in our process outside of the above.
        self.reportclient = report.SchedulerReportClient()
        self.virtapi = ComputeVirtAPI(self)
        self.network_api = neutron.API()
        self.volume_api = cinder.API()
        self.image_api = glance.API()
        self._last_bw_usage_poll = 0.0
        self.compute_api = compute.API()
        self.compute_rpcapi = compute_rpcapi.ComputeAPI()
        self.compute_task_api = conductor.ComputeTaskAPI()
        self.query_client = query.SchedulerQueryClient()
        self.instance_events = InstanceEvents()
        self._sync_power_pool = eventlet.GreenPool(
            size=CONF.sync_power_state_pool_size)
        self._syncs_in_progress = {}
        self.send_instance_updates = (
            CONF.filter_scheduler.track_instance_changes)
        if CONF.max_concurrent_builds != 0:
            self._build_semaphore = eventlet.semaphore.Semaphore(
                CONF.max_concurrent_builds)
        else:
            self._build_semaphore = compute_utils.UnlimitedSemaphore()
        if CONF.max_concurrent_snapshots > 0:
            self._snapshot_semaphore = eventlet.semaphore.Semaphore(
                CONF.max_concurrent_snapshots)
        else:
            self._snapshot_semaphore = compute_utils.UnlimitedSemaphore()
        if CONF.max_concurrent_live_migrations > 0:
            self._live_migration_executor = futurist.GreenThreadPoolExecutor(
                max_workers=CONF.max_concurrent_live_migrations)
        else:
            # CONF.max_concurrent_live_migrations is 0 (unlimited)
            self._live_migration_executor = futurist.GreenThreadPoolExecutor()
        # This is a dict, keyed by instance uuid, to a two-item tuple of
        # migration object and Future for the queued live migration.
        self._waiting_live_migrations = {}

        super(ComputeManager, self).__init__(service_name="compute",
                                             *args, **kwargs)

        # TODO(sbauza): Remove this call once we delete the V5Proxy class
        self.additional_endpoints.append(_ComputeV5Proxy(self))

        # NOTE(russellb) Load the driver last.  It may call back into the
        # compute manager via the virtapi, so we want it to be fully
        # initialized before that happens.
        self.driver = driver.load_compute_driver(self.virtapi, compute_driver)
        self.rt = resource_tracker.ResourceTracker(
            self.host, self.driver, reportclient=self.reportclient)

    def reset(self):
        LOG.info('Reloading compute RPC API')
        compute_rpcapi.reset_globals()
        self.compute_rpcapi = compute_rpcapi.ComputeAPI()
        self.reportclient.clear_provider_cache()

    def _update_resource_tracker(self, context, instance):
        """Let the resource tracker know that an instance has changed state."""

        if instance.host == self.host:
            self.rt.update_usage(context, instance, instance.node)

    def _instance_update(self, context, instance, **kwargs):
        """Update an instance in the database using kwargs as value."""

        for k, v in kwargs.items():
            setattr(instance, k, v)
        instance.save()
        self._update_resource_tracker(context, instance)

    def _nil_out_instance_obj_host_and_node(self, instance):
        # NOTE(jwcroppe): We don't do instance.save() here for performance
        # reasons; a call to this is expected to be immediately followed by
        # another call that does instance.save(), thus avoiding two writes
        # to the database layer.
        instance.host = None
        instance.node = None
        # ResourceTracker._set_instance_host_and_node also sets launched_on
        # to the same value as host and is really only ever used by legacy
        # nova-network code, but we should also null it out to avoid confusion
        # if there is an instance in the database with no host set but
        # launched_on is set. Note that we do not care about using launched_on
        # as some kind of debug helper if diagnosing a build failure, that is
        # what instance action events are for.
        instance.launched_on = None
        # If the instance is not on a host, it's not in an aggregate and
        # therefore is not in an availability zone.
        instance.availability_zone = None

    def _set_instance_obj_error_state(self, instance, clean_task_state=False):
        try:
            instance.vm_state = vm_states.ERROR
            if clean_task_state:
                instance.task_state = None
            instance.save()
        except exception.InstanceNotFound:
            LOG.debug('Instance has been destroyed from under us while '
                      'trying to set it to ERROR', instance=instance)

    def _get_instances_on_driver(self, context, filters=None):
        """Return a list of instance records for the instances found
        on the hypervisor which satisfy the specified filters. If filters=None
        return a list of instance records for all the instances found on the
        hypervisor.
        """
        if not filters:
            filters = {}
        try:
            driver_uuids = self.driver.list_instance_uuids()
            if len(driver_uuids) == 0:
                # Short circuit, don't waste a DB call
                return objects.InstanceList()
            filters['uuid'] = driver_uuids
            local_instances = objects.InstanceList.get_by_filters(
                context, filters, use_slave=True)
            return local_instances
        except NotImplementedError:
            pass

        # The driver doesn't support uuids listing, so we'll have
        # to brute force.
        driver_instances = self.driver.list_instances()
        # NOTE(mjozefcz): In this case we need to apply host filter.
        # Without this all instance data would be fetched from db.
        filters['host'] = self.host
        instances = objects.InstanceList.get_by_filters(context, filters,
                                                        use_slave=True)
        name_map = {instance.name: instance for instance in instances}
        local_instances = []
        for driver_instance in driver_instances:
            instance = name_map.get(driver_instance)
            if not instance:
                continue
            local_instances.append(instance)
        return local_instances

    def _destroy_evacuated_instances(self, context, node_cache):
        """Destroys evacuated instances.

        While nova-compute was down, the instances running on it could be
        evacuated to another host. This method looks for evacuation migration
        records where this is the source host and which were either started
        (accepted), in-progress (pre-migrating) or migrated (done). From those
        migration records, local instances reported by the hypervisor are
        compared to the instances for the migration records and those local
        guests are destroyed, along with instance allocation records in
        Placement for this node.
        Then allocations are removed from Placement for every instance that is
        evacuated from this host regardless if the instance is reported by the
        hypervisor or not.

        :param context: The request context
        :param node_cache: A dict of ComputeNode objects keyed by the UUID of
            the compute node
        :return: A dict keyed by instance uuid mapped to Migration objects
            for instances that were migrated away from this host
        """
        filters = {
            'source_compute': self.host,
            # NOTE(mriedem): Migration records that have been accepted are
            # included in case the source node comes back up while instances
            # are being evacuated to another host. We don't want the same
            # instance being reported from multiple hosts.
            # NOTE(lyarwood): pre-migrating is also included here as the
            # source compute can come back online shortly after the RT
            # claims on the destination that in-turn moves the migration to
            # pre-migrating. If the evacuate fails on the destination host,
            # the user can rebuild the instance (in ERROR state) on the source
            # host.
            'status': ['accepted', 'pre-migrating', 'done'],
            'migration_type': fields.MigrationType.EVACUATION,
        }
        with utils.temporary_mutation(context, read_deleted='yes'):
            evacuations = objects.MigrationList.get_by_filters(context,
                                                               filters)
        if not evacuations:
            return {}
        evacuations = {mig.instance_uuid: mig for mig in evacuations}

        # TODO(mriedem): We could optimize by pre-loading the joined fields
        # we know we'll use, like info_cache and flavor.
        local_instances = self._get_instances_on_driver(context)
        evacuated_local_instances = {inst.uuid: inst
                                     for inst in local_instances
                                     if inst.uuid in evacuations}

        for instance in evacuated_local_instances.values():
            LOG.info('Destroying instance as it has been evacuated from '
                     'this host but still exists in the hypervisor',
                     instance=instance)
            try:
                network_info = self.network_api.get_instance_nw_info(
                    context, instance)
                bdi = self._get_instance_block_device_info(context,
                                                           instance)
                destroy_disks = not (self._is_instance_storage_shared(
                    context, instance))
            except exception.InstanceNotFound:
                network_info = network_model.NetworkInfo()
                bdi = {}
                LOG.info('Instance has been marked deleted already, '
                         'removing it from the hypervisor.',
                         instance=instance)
                # always destroy disks if the instance was deleted
                destroy_disks = True
            self.driver.destroy(context, instance,
                                network_info,
                                bdi, destroy_disks)

        hostname_to_cn_uuid = {
            cn.hypervisor_hostname: cn.uuid
            for cn in node_cache.values()}

        for instance_uuid, migration in evacuations.items():
            try:
                if instance_uuid in evacuated_local_instances:
                    # Avoid the db call if we already have the instance loaded
                    # above
                    instance = evacuated_local_instances[instance_uuid]
                else:
                    instance = objects.Instance.get_by_uuid(
                        context, instance_uuid)
            except exception.InstanceNotFound:
                # The instance already deleted so we expect that every
                # allocation of that instance has already been cleaned up
                continue

            LOG.info('Cleaning up allocations of the instance as it has been '
                     'evacuated from this host',
                     instance=instance)
            if migration.source_node not in hostname_to_cn_uuid:
                LOG.error("Failed to clean allocation of evacuated "
                          "instance as the source node %s is not found",
                          migration.source_node, instance=instance)
                continue
            cn_uuid = hostname_to_cn_uuid[migration.source_node]

            # If the instance was deleted in the interim, assume its
            # allocations were properly cleaned up (either by its hosting
            # compute service or the API).
            if (not instance.deleted and
                    not self.reportclient.
                        remove_provider_tree_from_instance_allocation(
                            context, instance.uuid, cn_uuid)):
                LOG.error("Failed to clean allocation of evacuated instance "
                          "on the source node %s",
                          cn_uuid, instance=instance)

            migration.status = 'completed'
            migration.save()
        return evacuations

    def _is_instance_storage_shared(self, context, instance, host=None):
        shared_storage = True
        data = None
        try:
            data = self.driver.check_instance_shared_storage_local(context,
                                                       instance)
            if data:
                shared_storage = (self.compute_rpcapi.
                                  check_instance_shared_storage(context,
                                  data, instance=instance, host=host))
        except NotImplementedError:
            LOG.debug('Hypervisor driver does not support '
                      'instance shared storage check, '
                      'assuming it\'s not on shared storage',
                      instance=instance)
            shared_storage = False
        except Exception:
            LOG.exception('Failed to check if instance shared',
                          instance=instance)
        finally:
            if data:
                self.driver.check_instance_shared_storage_cleanup(context,
                                                                  data)
        return shared_storage

    def _complete_partial_deletion(self, context, instance):
        """Complete deletion for instances in DELETED status but not marked as
        deleted in the DB
        """
        instance.destroy()
        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                context, instance.uuid)
        self._complete_deletion(context,
                                instance)
        self._notify_about_instance_usage(context, instance, "delete.end")
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.DELETE,
                phase=fields.NotificationPhase.END, bdms=bdms)

    def _complete_deletion(self, context, instance):
        self._update_resource_tracker(context, instance)

        # If we're configured to do deferred deletes, don't force deletion of
        # allocations if there's a conflict.
        force = False if CONF.reclaim_instance_interval > 0 else True

        self.reportclient.delete_allocation_for_instance(context,
                                                         instance.uuid,
                                                         force=force)

        self._clean_instance_console_tokens(context, instance)
        self._delete_scheduler_instance_info(context, instance.uuid)

    def _validate_pinning_configuration(self, instances):
        if not self.driver.capabilities.get('supports_pcpus', False):
            return

        for instance in instances:
            # ignore deleted instances
            if instance.deleted:
                continue

            # if this is an unpinned instance and the host only has
            # 'cpu_dedicated_set' configured, we need to tell the operator to
            # correct their configuration
            if not instance.numa_topology or (
                instance.numa_topology.cpu_policy in (
                    None, fields.CPUAllocationPolicy.SHARED
                )
            ):
                # we don't need to check 'vcpu_pin_set' since it can't coexist
                # alongside 'cpu_dedicated_set'
                if (CONF.compute.cpu_dedicated_set and
                        not CONF.compute.cpu_shared_set):
                    msg = _("This host has unpinned instances but has no CPUs "
                            "set aside for this purpose; configure '[compute] "
                            "cpu_shared_set' instead of, or in addition to, "
                            "'[compute] cpu_dedicated_set'")
                    raise exception.InvalidConfiguration(msg)

                continue

            # ditto for pinned instances if only 'cpu_shared_set' is configured
            if (CONF.compute.cpu_shared_set and
                    not CONF.compute.cpu_dedicated_set and
                    not CONF.vcpu_pin_set):
                msg = _("This host has pinned instances but has no CPUs "
                        "set aside for this purpose; configure '[compute] "
                        "cpu_dedicated_set' instead of, or in addition to, "
                        "'[compute] cpu_shared_set'.")
                raise exception.InvalidConfiguration(msg)

            # if this is a mixed instance with both pinned and unpinned CPUs,
            # the host must have both 'cpu_dedicated_set' and 'cpu_shared_set'
            # configured. check if 'cpu_shared_set' is set.
            if (instance.numa_topology.cpu_policy ==
                    fields.CPUAllocationPolicy.MIXED and
                    not CONF.compute.cpu_shared_set):
                msg = _("This host has mixed instance requesting both pinned "
                        "and unpinned CPUs but hasn't set aside unpinned CPUs "
                        "for this purpose; Configure "
                        "'[compute] cpu_shared_set'.")
                raise exception.InvalidConfiguration(msg)

            # for mixed instance check if 'cpu_dedicated_set' is set.
            if (instance.numa_topology.cpu_policy ==
                    fields.CPUAllocationPolicy.MIXED and
                    not CONF.compute.cpu_dedicated_set):
                msg = _("This host has mixed instance requesting both pinned "
                        "and unpinned CPUs but hasn't set aside pinned CPUs "
                        "for this purpose; Configure "
                        "'[compute] cpu_dedicated_set'")
                raise exception.InvalidConfiguration(msg)

            # also check to make sure the operator hasn't accidentally
            # dropped some cores that instances are currently using
            available_dedicated_cpus = (hardware.get_vcpu_pin_set() or
                                        hardware.get_cpu_dedicated_set())
            pinned_cpus = instance.numa_topology.cpu_pinning
            if available_dedicated_cpus and (
                    pinned_cpus - available_dedicated_cpus):
                # we can't raise an exception because of bug #1289064,
                # which meant we didn't recalculate CPU pinning information
                # when we live migrated a pinned instance
                LOG.warning(
                    "Instance is pinned to host CPUs %(cpus)s "
                    "but one or more of these CPUs are not included in "
                    "either '[compute] cpu_dedicated_set' or "
                    "'vcpu_pin_set'; you should update these "
                    "configuration options to include the missing CPUs "
                    "or rebuild or cold migrate this instance.",
                    {'cpus': list(pinned_cpus)},
                    instance=instance)

    def _validate_vtpm_configuration(self, instances):
        if self.driver.capabilities.get('supports_vtpm', False):
            return

        for instance in instances:
            if instance.deleted:
                continue

            # NOTE(stephenfin): We don't have an attribute on the instance to
            # check for this, so we need to inspect the flavor/image metadata
            if hardware.get_vtpm_constraint(
                instance.flavor, instance.image_meta,
            ):
                msg = _(
                    'This host has instances with the vTPM feature enabled, '
                    'but the host is not correctly configured; enable '
                    'vTPM support.'
                )
                raise exception.InvalidConfiguration(msg)

    def _reset_live_migration(self, context, instance):
        migration = None
        try:
            migration = objects.Migration.get_by_instance_and_status(
                                      context, instance.uuid, 'running')
            if migration:
                self.live_migration_abort(context, instance, migration.id)
        except Exception:
            LOG.exception('Failed to abort live-migration',
                          instance=instance)
        finally:
            if migration:
                self._set_migration_status(migration, 'error')
            LOG.info('Instance found in migrating state during '
                     'startup. Resetting task_state',
                     instance=instance)
            instance.task_state = None
            instance.save(expected_task_state=[task_states.MIGRATING])

    def _init_instance(self, context, instance):
        """Initialize this instance during service init."""

        # NOTE(danms): If the instance appears to not be owned by this
        # host, it may have been evacuated away, but skipped by the
        # evacuation cleanup code due to configuration. Thus, if that
        # is a possibility, don't touch the instance in any way, but
        # log the concern. This will help avoid potential issues on
        # startup due to misconfiguration.
        if instance.host != self.host:
            LOG.warning('Instance %(uuid)s appears to not be owned '
                        'by this host, but by %(host)s. Startup '
                        'processing is being skipped.',
                        {'uuid': instance.uuid,
                         'host': instance.host})
            return

        # Instances that are shut down, or in an error state can not be
        # initialized and are not attempted to be recovered. The exception
        # to this are instances that are in RESIZE_MIGRATING or DELETING,
        # which are dealt with further down.
        if (instance.vm_state == vm_states.SOFT_DELETED or
            (instance.vm_state == vm_states.ERROR and
            instance.task_state not in
            (task_states.RESIZE_MIGRATING, task_states.DELETING))):
            LOG.debug("Instance is in %s state.",
                      instance.vm_state, instance=instance)
            return

        if instance.vm_state == vm_states.DELETED:
            try:
                self._complete_partial_deletion(context, instance)
            except Exception:
                # we don't want that an exception blocks the init_host
                LOG.exception('Failed to complete a deletion',
                              instance=instance)
            return

        if (instance.vm_state == vm_states.BUILDING or
            instance.task_state in [task_states.SCHEDULING,
                                    task_states.BLOCK_DEVICE_MAPPING,
                                    task_states.NETWORKING,
                                    task_states.SPAWNING]):
            # NOTE(dave-mcnally) compute stopped before instance was fully
            # spawned so set to ERROR state. This is safe to do as the state
            # may be set by the api but the host is not so if we get here the
            # instance has already been scheduled to this particular host.
            LOG.debug("Instance failed to spawn correctly, "
                      "setting to ERROR state", instance=instance)
            self._set_instance_obj_error_state(instance, clean_task_state=True)
            return

        if (instance.vm_state in [vm_states.ACTIVE, vm_states.STOPPED] and
            instance.task_state in [task_states.REBUILDING,
                                    task_states.REBUILD_BLOCK_DEVICE_MAPPING,
                                    task_states.REBUILD_SPAWNING]):
            # NOTE(jichenjc) compute stopped before instance was fully
            # spawned so set to ERROR state. This is consistent to BUILD
            LOG.debug("Instance failed to rebuild correctly, "
                      "setting to ERROR state", instance=instance)
            self._set_instance_obj_error_state(instance, clean_task_state=True)
            return

        if (instance.vm_state != vm_states.ERROR and
            instance.task_state in [task_states.IMAGE_SNAPSHOT_PENDING,
                                    task_states.IMAGE_PENDING_UPLOAD,
                                    task_states.IMAGE_UPLOADING,
                                    task_states.IMAGE_SNAPSHOT]):
            LOG.debug("Instance in transitional state %s at start-up "
                      "clearing task state",
                      instance.task_state, instance=instance)
            instance.task_state = None
            instance.save()

        if (instance.vm_state != vm_states.ERROR and
            instance.task_state in [task_states.RESIZE_PREP]):
            LOG.debug("Instance in transitional state %s at start-up "
                      "clearing task state",
                      instance['task_state'], instance=instance)
            instance.task_state = None
            instance.save()

        if instance.task_state == task_states.DELETING:
            try:
                LOG.info('Service started deleting the instance during '
                         'the previous run, but did not finish. Restarting'
                         ' the deletion now.', instance=instance)
                instance.obj_load_attr('metadata')
                instance.obj_load_attr('system_metadata')
                bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                        context, instance.uuid)
                self._delete_instance(context, instance, bdms)
            except Exception:
                # we don't want that an exception blocks the init_host
                LOG.exception('Failed to complete a deletion',
                              instance=instance)
                self._set_instance_obj_error_state(instance)
            return

        current_power_state = self._get_power_state(instance)
        try_reboot, reboot_type = self._retry_reboot(
            instance, current_power_state)

        if try_reboot:
            LOG.debug("Instance in transitional state (%(task_state)s) at "
                      "start-up and power state is (%(power_state)s), "
                      "triggering reboot",
                      {'task_state': instance.task_state,
                       'power_state': current_power_state},
                      instance=instance)

            # NOTE(mikal): if the instance was doing a soft reboot that got as
            # far as shutting down the instance but not as far as starting it
            # again, then we've just become a hard reboot. That means the
            # task state for the instance needs to change so that we're in one
            # of the expected task states for a hard reboot.
            if (instance.task_state in task_states.soft_reboot_states and
                reboot_type == 'HARD'):
                instance.task_state = task_states.REBOOT_PENDING_HARD
                instance.save()

            self.reboot_instance(context, instance, block_device_info=None,
                                 reboot_type=reboot_type)
            return

        elif (current_power_state == power_state.RUNNING and
              instance.task_state in [task_states.REBOOT_STARTED,
                                      task_states.REBOOT_STARTED_HARD,
                                      task_states.PAUSING,
                                      task_states.UNPAUSING]):
            LOG.warning("Instance in transitional state "
                        "(%(task_state)s) at start-up and power state "
                        "is (%(power_state)s), clearing task state",
                        {'task_state': instance.task_state,
                         'power_state': current_power_state},
                        instance=instance)
            instance.task_state = None
            instance.vm_state = vm_states.ACTIVE
            instance.save()
        elif (current_power_state == power_state.PAUSED and
              instance.task_state == task_states.UNPAUSING):
            LOG.warning("Instance in transitional state "
                        "(%(task_state)s) at start-up and power state "
                        "is (%(power_state)s), clearing task state "
                        "and unpausing the instance",
                        {'task_state': instance.task_state,
                         'power_state': current_power_state},
                        instance=instance)
            try:
                self.unpause_instance(context, instance)
            except NotImplementedError:
                # Some virt driver didn't support pause and unpause
                pass
            except Exception:
                LOG.exception('Failed to unpause instance', instance=instance)
            return

        if instance.task_state == task_states.POWERING_OFF:
            try:
                LOG.debug("Instance in transitional state %s at start-up "
                          "retrying stop request",
                          instance.task_state, instance=instance)
                self.stop_instance(context, instance, True)
            except Exception:
                # we don't want that an exception blocks the init_host
                LOG.exception('Failed to stop instance', instance=instance)
            return

        if instance.task_state == task_states.POWERING_ON:
            try:
                LOG.debug("Instance in transitional state %s at start-up "
                          "retrying start request",
                          instance.task_state, instance=instance)
                self.start_instance(context, instance)
            except Exception:
                # we don't want that an exception blocks the init_host
                LOG.exception('Failed to start instance', instance=instance)
            return

        net_info = instance.get_network_info()
        try:
            self.driver.plug_vifs(instance, net_info)
        except NotImplementedError as e:
            LOG.debug(e, instance=instance)
        except exception.VirtualInterfacePlugException:
            # NOTE(mriedem): If we get here, it could be because the vif_type
            # in the cache is "binding_failed" or "unbound".
            # The periodic task _heal_instance_info_cache checks for this
            # condition. It should fix this by binding the ports again when
            # it gets to this instance.
            LOG.exception('Virtual interface plugging failed for instance. '
                          'The port binding:host_id may need to be manually '
                          'updated.', instance=instance)
            self._set_instance_obj_error_state(instance)
            return
        except exception.PciDeviceNotFoundById:
            # This is bug 1981813 where the bound port vnic_type has changed
            # from direct to macvtap. Nova does not support that and it
            # already printed an ERROR when the change is detected during
            # _heal_instance_info_cache. Now we print an ERROR again and skip
            # plugging the vifs but let the service startup continue to init
            # the other instances
            LOG.exception(
                'Virtual interface plugging failed for instance. Probably the '
                'vnic_type of the bound port has been changed. Nova does not '
                'support such change.',
                instance=instance
            )
            return

        if instance.task_state == task_states.RESIZE_MIGRATING:
            # We crashed during resize/migration, so roll back for safety
            try:
                # NOTE(mriedem): check old_vm_state for STOPPED here, if it's
                # not in system_metadata we default to True for backwards
                # compatibility
                power_on = (instance.system_metadata.get('old_vm_state') !=
                            vm_states.STOPPED)

                block_dev_info = self._get_instance_block_device_info(context,
                                                                      instance)

                migration = objects.Migration.get_by_id_and_instance(
                    context, instance.migration_context.migration_id,
                    instance.uuid)
                self.driver.finish_revert_migration(context, instance,
                    net_info, migration, block_dev_info, power_on)

            except Exception:
                LOG.exception('Failed to revert crashed migration',
                              instance=instance)
            finally:
                LOG.info('Instance found in migrating state during '
                         'startup. Resetting task_state',
                         instance=instance)
                instance.task_state = None
                instance.save()
        if instance.task_state == task_states.MIGRATING:
            # Live migration did not complete, but instance is on this
            # host. Abort ongoing migration if still running and reset state.
            self._reset_live_migration(context, instance)

        db_state = instance.power_state
        drv_state = self._get_power_state(instance)
        expect_running = (db_state == power_state.RUNNING and
                          drv_state != db_state)

        LOG.debug('Current state is %(drv_state)s, state in DB is '
                  '%(db_state)s.',
                  {'drv_state': drv_state, 'db_state': db_state},
                  instance=instance)

        if expect_running and CONF.resume_guests_state_on_host_boot:
            self._resume_guests_state(context, instance, net_info)

    def _resume_guests_state(self, context, instance, net_info):
        LOG.info('Rebooting instance after nova-compute restart.',
                 instance=instance)
        block_device_info = \
            self._get_instance_block_device_info(context, instance)

        try:
            self.driver.resume_state_on_host_boot(
                context, instance, net_info, block_device_info)
        except NotImplementedError:
            LOG.warning('Hypervisor driver does not support '
                        'resume guests', instance=instance)
        except Exception:
            # NOTE(vish): The instance failed to resume, so we set the
            #             instance to error and attempt to continue.
            LOG.warning('Failed to resume instance',
                        instance=instance)
            self._set_instance_obj_error_state(instance)

    def _retry_reboot(self, instance, current_power_state):
        current_task_state = instance.task_state
        retry_reboot = False
        reboot_type = compute_utils.get_reboot_type(current_task_state,
                                                    current_power_state)

        pending_soft = (
            current_task_state == task_states.REBOOT_PENDING and
            instance.vm_state in vm_states.ALLOW_SOFT_REBOOT)
        pending_hard = (
            current_task_state == task_states.REBOOT_PENDING_HARD and
            instance.vm_state in vm_states.ALLOW_HARD_REBOOT)
        started_not_running = (current_task_state in
                               [task_states.REBOOT_STARTED,
                                task_states.REBOOT_STARTED_HARD] and
                               current_power_state != power_state.RUNNING)

        if pending_soft or pending_hard or started_not_running:
            retry_reboot = True

        return retry_reboot, reboot_type

    def handle_lifecycle_event(self, event):
        LOG.info("VM %(state)s (Lifecycle Event)",
                 {'state': event.get_name()},
                 instance_uuid=event.get_instance_uuid())
        context = nova.context.get_admin_context(read_deleted='yes')
        vm_power_state = None
        event_transition = event.get_transition()
        if event_transition == virtevent.EVENT_LIFECYCLE_STOPPED:
            vm_power_state = power_state.SHUTDOWN
        elif event_transition == virtevent.EVENT_LIFECYCLE_STARTED:
            vm_power_state = power_state.RUNNING
        elif event_transition in (
                virtevent.EVENT_LIFECYCLE_PAUSED,
                virtevent.EVENT_LIFECYCLE_POSTCOPY_STARTED,
                virtevent.EVENT_LIFECYCLE_MIGRATION_COMPLETED):
            vm_power_state = power_state.PAUSED
        elif event_transition == virtevent.EVENT_LIFECYCLE_RESUMED:
            vm_power_state = power_state.RUNNING
        elif event_transition == virtevent.EVENT_LIFECYCLE_SUSPENDED:
            vm_power_state = power_state.SUSPENDED
        else:
            LOG.warning("Unexpected lifecycle event: %d", event_transition)

        migrate_finish_statuses = {
            # This happens on the source node and indicates live migration
            # entered post-copy mode.
            virtevent.EVENT_LIFECYCLE_POSTCOPY_STARTED: 'running (post-copy)',
            # Suspended for offline migration.
            virtevent.EVENT_LIFECYCLE_MIGRATION_COMPLETED: 'running'
        }

        expected_attrs = []
        if event_transition in migrate_finish_statuses:
            # Join on info_cache since that's needed in migrate_instance_start.
            expected_attrs.append('info_cache')
        instance = objects.Instance.get_by_uuid(context,
                                                event.get_instance_uuid(),
                                                expected_attrs=expected_attrs)

        # Note(lpetrut): The event may be delayed, thus not reflecting
        # the current instance power state. In that case, ignore the event.
        current_power_state = self._get_power_state(instance)
        if current_power_state == vm_power_state:
            LOG.debug('Synchronizing instance power state after lifecycle '
                      'event "%(event)s"; current vm_state: %(vm_state)s, '
                      'current task_state: %(task_state)s, current DB '
                      'power_state: %(db_power_state)s, VM power_state: '
                      '%(vm_power_state)s',
                      {'event': event.get_name(),
                       'vm_state': instance.vm_state,
                       'task_state': instance.task_state,
                       'db_power_state': instance.power_state,
                       'vm_power_state': vm_power_state},
                      instance_uuid=instance.uuid)
            self._sync_instance_power_state(context,
                                            instance,
                                            vm_power_state)

        # The following checks are for live migration. We want to activate
        # the port binding for the destination host before the live migration
        # is resumed on the destination host in order to reduce network
        # downtime. Otherwise the ports are bound to the destination host
        # in post_live_migration_at_destination.
        # TODO(danms): Explore options for using a different live migration
        # specific callback for this instead of piggy-backing on the
        # handle_lifecycle_event callback.
        if (instance.task_state == task_states.MIGRATING and
                event_transition in migrate_finish_statuses):
            status = migrate_finish_statuses[event_transition]
            try:
                migration = objects.Migration.get_by_instance_and_status(
                            context, instance.uuid, status)
                LOG.debug('Binding ports to destination host: %s',
                          migration.dest_compute, instance=instance)
                # For neutron, migrate_instance_start will activate the
                # destination host port bindings, if there are any created by
                # conductor before live migration started.
                self.network_api.migrate_instance_start(
                    context, instance, migration)
            except exception.MigrationNotFoundByStatus:
                LOG.warning("Unable to find migration record with status "
                            "'%s' for instance. Port binding will happen in "
                            "post live migration.", status, instance=instance)

    def handle_events(self, event):
        if isinstance(event, virtevent.LifecycleEvent):
            try:
                self.handle_lifecycle_event(event)
            except exception.InstanceNotFound:
                LOG.debug("Event %s arrived for non-existent instance. The "
                          "instance was probably deleted.", event)
        else:
            LOG.debug("Ignoring event %s", event)

    def init_virt_events(self):
        if CONF.workarounds.handle_virt_lifecycle_events:
            self.driver.register_event_listener(self.handle_events)
        else:
            # NOTE(mriedem): If the _sync_power_states periodic task is
            # disabled we should emit a warning in the logs.
            if CONF.sync_power_state_interval < 0:
                LOG.warning('Instance lifecycle events from the compute '
                            'driver have been disabled. Note that lifecycle '
                            'changes to an instance outside of the compute '
                            'service will not be synchronized '
                            'automatically since the _sync_power_states '
                            'periodic task is also disabled.')
            else:
                LOG.info('Instance lifecycle events from the compute '
                         'driver have been disabled. Note that lifecycle '
                         'changes to an instance outside of the compute '
                         'service will only be synchronized by the '
                         '_sync_power_states periodic task.')

    def _get_nodes(self, context):
        """Queried the ComputeNode objects from the DB that are reported by the
        hypervisor.

        :param context: the request context
        :return: a dict of ComputeNode objects keyed by the UUID of the given
            node.
        """
        nodes_by_uuid = {}
        try:
            node_names = self.driver.get_available_nodes()
        except exception.VirtDriverNotReady:
            LOG.warning(
                "Virt driver is not ready. If this is the first time this "
                "service is starting on this host, then you can ignore this "
                "warning.")
            return {}

        for node_name in node_names:
            try:
                node = objects.ComputeNode.get_by_host_and_nodename(
                    context, self.host, node_name)
                nodes_by_uuid[node.uuid] = node
            except exception.ComputeHostNotFound:
                LOG.warning(
                    "Compute node %s not found in the database. If this is "
                    "the first time this service is starting on this host, "
                    "then you can ignore this warning.", node_name)
        return nodes_by_uuid

    def init_host(self):
        """Initialization for a standalone compute service."""

        if CONF.pci.device_spec:
            # Simply loading the PCI passthrough spec will do a bunch of
            # validation that would otherwise wait until the PciDevTracker is
            # constructed when updating available resources for the compute
            # node(s) in the resource tracker, effectively killing that task.
            # So load up the spec when starting the compute service to
            # flush any invalid configuration early, so we can kill the service
            # if the configuration is wrong.
            whitelist.Whitelist(CONF.pci.device_spec)

        nova.conf.neutron.register_dynamic_opts(CONF)
        # Even if only libvirt uses them, make it available for all drivers
        nova.conf.devices.register_dynamic_opts(CONF)

        # Override the number of concurrent disk operations allowed if the
        # user has specified a limit.
        if CONF.compute.max_concurrent_disk_ops != 0:
            compute_utils.disk_ops_semaphore = \
                eventlet.semaphore.BoundedSemaphore(
                    CONF.compute.max_concurrent_disk_ops)

        if CONF.compute.max_disk_devices_to_attach == 0:
            msg = _('[compute]max_disk_devices_to_attach has been set to 0, '
                    'which will prevent instances from being able to boot. '
                    'Set -1 for unlimited or set >= 1 to limit the maximum '
                    'number of disk devices.')
            raise exception.InvalidConfiguration(msg)

        self.driver.init_host(host=self.host)
        context = nova.context.get_admin_context()
        instances = objects.InstanceList.get_by_host(
            context, self.host,
            expected_attrs=['info_cache', 'metadata', 'numa_topology'])

        self.init_virt_events()

        self._validate_pinning_configuration(instances)
        self._validate_vtpm_configuration(instances)

        # NOTE(gibi): At this point the compute_nodes of the resource tracker
        # has not been populated yet so we cannot rely on the resource tracker
        # here.
        # NOTE(gibi): If ironic and vcenter virt driver slow start time
        # becomes problematic here then we should consider adding a config
        # option or a driver flag to tell us if we should thread
        # _destroy_evacuated_instances and
        # _error_out_instances_whose_build_was_interrupted out in the
        # background on startup
        nodes_by_uuid = self._get_nodes(context)

        try:
            # checking that instance was not already evacuated to other host
            evacuated_instances = self._destroy_evacuated_instances(
                context, nodes_by_uuid)

            # Initialise instances on the host that are not evacuating
            for instance in instances:
                if instance.uuid not in evacuated_instances:
                    self._init_instance(context, instance)

            # NOTE(gibi): collect all the instance uuids that is in some way
            # was already handled above. Either by init_instance or by
            # _destroy_evacuated_instances. This way we can limit the scope of
            # the _error_out_instances_whose_build_was_interrupted call to look
            # only for instances that have allocations on this node and not
            # handled by the above calls.
            already_handled = {instance.uuid for instance in instances}.union(
                evacuated_instances)
            self._error_out_instances_whose_build_was_interrupted(
                context, already_handled, nodes_by_uuid.keys())

        finally:
            if instances:
                # We only send the instance info to the scheduler on startup
                # if there is anything to send, otherwise this host might
                # not be mapped yet in a cell and the scheduler may have
                # issues dealing with the information. Later changes to
                # instances on this host will update the scheduler, or the
                # _sync_scheduler_instance_info periodic task will.
                self._update_scheduler_instance_info(context, instances)

    def _error_out_instances_whose_build_was_interrupted(
            self, context, already_handled_instances, node_uuids):
        """If there are instances in BUILDING state that are not
        assigned to this host but have allocations in placement towards
        this compute that means the nova-compute service was
        restarted while those instances waited for the resource claim
        to finish and the _set_instance_host_and_node() to update the
        instance.host field. We need to push them to ERROR state here to
        prevent keeping them in BUILDING state forever.

        :param context: The request context
        :param already_handled_instances: The set of instance UUIDs that the
            host initialization process already handled in some way.
        :param node_uuids: The list of compute node uuids handled by this
            service
        """

        # Strategy:
        # 1) Get the allocations from placement for our compute node(s)
        # 2) Remove the already handled instances from the consumer list;
        #    they are either already initialized or need to be skipped.
        # 3) Check which remaining consumer is an instance in BUILDING state
        #    and push it to ERROR state.

        LOG.info(
            "Looking for unclaimed instances stuck in BUILDING status for "
            "nodes managed by this host")
        for cn_uuid in node_uuids:
            try:
                f = self.reportclient.get_allocations_for_resource_provider
                allocations = f(context, cn_uuid).allocations
            except (exception.ResourceProviderAllocationRetrievalFailed,
                    keystone_exception.ClientException) as e:
                LOG.error(
                    "Could not retrieve compute node resource provider %s and "
                    "therefore unable to error out any instances stuck in "
                    "BUILDING state. Error: %s", cn_uuid, str(e))
                continue

            not_handled_consumers = (set(allocations) -
                                     already_handled_instances)

            if not not_handled_consumers:
                continue

            filters = {
                'vm_state': vm_states.BUILDING,
                'uuid': not_handled_consumers
            }

            instances = objects.InstanceList.get_by_filters(
                context, filters, expected_attrs=[])

            for instance in instances:
                LOG.debug(
                    "Instance spawn was interrupted before instance_claim, "
                    "setting instance to ERROR state", instance=instance)
                self._set_instance_obj_error_state(
                    instance, clean_task_state=True)

    def cleanup_host(self):
        self.driver.register_event_listener(None)
        self.instance_events.cancel_all_events()
        self.driver.cleanup_host(host=self.host)
        self._cleanup_live_migrations_in_pool()

    def _cleanup_live_migrations_in_pool(self):
        # Shutdown the pool so we don't get new requests.
        self._live_migration_executor.shutdown(wait=False)
        # For any queued migrations, cancel the migration and update
        # its status.
        for migration, future in self._waiting_live_migrations.values():
            # If we got here before the Future was submitted then we need
            # to move on since there isn't anything we can do.
            if future is None:
                continue
            if future.cancel():
                self._set_migration_status(migration, 'cancelled')
                LOG.info('Successfully cancelled queued live migration.',
                         instance_uuid=migration.instance_uuid)
            else:
                LOG.warning('Unable to cancel live migration.',
                            instance_uuid=migration.instance_uuid)
        self._waiting_live_migrations.clear()

    def pre_start_hook(self):
        """After the service is initialized, but before we fully bring
        the service up by listening on RPC queues, make sure to update
        our available resources (and indirectly our available nodes).
        """
        self.update_available_resource(nova.context.get_admin_context(),
                                       startup=True)

    def _get_power_state(self, instance):
        """Retrieve the power state for the given instance."""
        LOG.debug('Checking state', instance=instance)
        try:
            return self.driver.get_info(instance, use_cache=False).state
        except exception.InstanceNotFound:
            return power_state.NOSTATE

    def _await_block_device_map_created(self, context, vol_id):
        # TODO(yamahata): creating volume simultaneously
        #                 reduces creation time?
        # TODO(yamahata): eliminate dumb polling
        start = time.time()
        retries = CONF.block_device_allocate_retries
        # (1) if the configured value is 0, one attempt should be made
        # (2) if the configured value is > 0, then the total number attempts
        #      is (retries + 1)
        attempts = 1
        if retries >= 1:
            attempts = retries + 1
        for attempt in range(1, attempts + 1):
            volume = self.volume_api.get(context, vol_id)
            volume_status = volume['status']
            if volume_status not in ['creating', 'downloading']:
                if volume_status == 'available':
                    return attempt
                LOG.warning("Volume id: %(vol_id)s finished being "
                            "created but its status is %(vol_status)s.",
                            {'vol_id': vol_id,
                             'vol_status': volume_status})
                break
            greenthread.sleep(CONF.block_device_allocate_retries_interval)
        raise exception.VolumeNotCreated(volume_id=vol_id,
                                         seconds=int(time.time() - start),
                                         attempts=attempt,
                                         volume_status=volume_status)

    def _decode_files(self, injected_files):
        """Base64 decode the list of files to inject."""
        if not injected_files:
            return []

        def _decode(f):
            path, contents = f
            # Py3 raises binascii.Error instead of TypeError as in Py27
            try:
                decoded = base64.b64decode(contents)
                return path, decoded
            except (TypeError, binascii.Error):
                raise exception.Base64Exception(path=path)

        return [_decode(f) for f in injected_files]

    def _validate_instance_group_policy(self, context, instance,
                                        scheduler_hints=None):

        if CONF.workarounds.disable_group_policy_check_upcall:
            return

        # NOTE(russellb) Instance group policy is enforced by the scheduler.
        # However, there is a race condition with the enforcement of
        # the policy.  Since more than one instance may be scheduled at the
        # same time, it's possible that more than one instance with an
        # anti-affinity policy may end up here.  It's also possible that
        # multiple instances with an affinity policy could end up on different
        # hosts.  This is a validation step to make sure that starting the
        # instance here doesn't violate the policy.
        if scheduler_hints is not None:
            # only go through here if scheduler_hints is provided,
            # even if it is empty.
            group_hint = scheduler_hints.get('group')
            if not group_hint:
                return
            else:
                # The RequestSpec stores scheduler_hints as key=list pairs
                # so we need to check the type on the value and pull the
                # single entry out. The API request schema validates that
                # the 'group' hint is a single value.
                if isinstance(group_hint, list):
                    group_hint = group_hint[0]
                try:
                    group = objects.InstanceGroup.get_by_hint(
                        context, group_hint
                    )
                except exception.InstanceGroupNotFound:
                    return
        else:
            # TODO(ganso): a call to DB can be saved by adding request_spec
            # to rpcapi payload of live_migration, pre_live_migration and
            # check_can_live_migrate_destination
            try:
                group = objects.InstanceGroup.get_by_instance_uuid(
                    context, instance.uuid
                )
            except exception.InstanceGroupNotFound:
                return

        @utils.synchronized(group['uuid'])
        def _do_validation(context, instance, group):
            if group.policy and 'anti-affinity' == group.policy:

                # instances on host
                instances_uuids = objects.InstanceList.get_uuids_by_host(
                    context, self.host)
                ins_on_host = set(instances_uuids)

                # instance param is just for logging, the nodename obtained is
                # not actually related to the instance at all
                nodename = self._get_nodename(instance)

                # instances being migrated to host
                migrations = (
                    objects.MigrationList.get_in_progress_by_host_and_node(
                        context, self.host, nodename))
                migration_vm_uuids = {mig.instance_uuid for mig in migrations}

                total_instances = migration_vm_uuids | ins_on_host

                # refresh group to get updated members within locked block
                group = objects.InstanceGroup.get_by_uuid(context,
                                                          group['uuid'])
                members = set(group.members)
                # Determine the set of instance group members on this host
                # which are not the instance in question. This is used to
                # determine how many other members from the same anti-affinity
                # group can be on this host.
                members_on_host = (total_instances & members -
                                   set([instance.uuid]))
                rules = group.rules
                if rules and 'max_server_per_host' in rules:
                    max_server = rules['max_server_per_host']
                else:
                    max_server = 1
                if len(members_on_host) >= max_server:
                    msg = _("Anti-affinity instance group policy "
                            "was violated.")
                    raise exception.RescheduledException(
                            instance_uuid=instance.uuid,
                            reason=msg)

            # NOTE(ganso): The check for affinity below does not work and it
            # can easily be violated because the lock happens in different
            # compute hosts.
            # The only fix seems to be a DB lock to perform the check whenever
            # setting the host field to an instance.
            elif group.policy and 'affinity' == group.policy:
                group_hosts = group.get_hosts(exclude=[instance.uuid])
                if group_hosts and self.host not in group_hosts:
                    msg = _("Affinity instance group policy was violated.")
                    raise exception.RescheduledException(
                            instance_uuid=instance.uuid,
                            reason=msg)

        _do_validation(context, instance, group)

    def _log_original_error(self, exc_info, instance_uuid):
        LOG.error('Error: %s', exc_info[1], instance_uuid=instance_uuid,
                  exc_info=exc_info)

    @periodic_task.periodic_task
    def _check_instance_build_time(self, context):
        """Ensure that instances are not stuck in build."""
        timeout = CONF.instance_build_timeout
        if timeout == 0:
            return

        filters = {'vm_state': vm_states.BUILDING,
                   'host': self.host}

        building_insts = objects.InstanceList.get_by_filters(context,
                           filters, expected_attrs=[], use_slave=True)

        for instance in building_insts:
            if timeutils.is_older_than(instance.created_at, timeout):
                self._set_instance_obj_error_state(instance)
                LOG.warning("Instance build timed out. Set to error "
                            "state.", instance=instance)

    def _check_instance_exists(self, instance):
        """Ensure an instance with the same name is not already present."""
        if self.driver.instance_exists(instance):
            raise exception.InstanceExists(name=instance.name)

    def _allocate_network_async(self, context, instance, requested_networks,
                                security_groups, resource_provider_mapping,
                                network_arqs):
        """Method used to allocate networks in the background.

        Broken out for testing.
        """
        # First check to see if we're specifically not supposed to allocate
        # networks because if so, we can exit early.
        if requested_networks and requested_networks.no_allocate:
            LOG.debug("Not allocating networking since 'none' was specified.",
                      instance=instance)
            return network_model.NetworkInfo([])

        LOG.debug("Allocating IP information in the background.",
                  instance=instance)
        retries = CONF.network_allocate_retries
        attempts = retries + 1
        retry_time = 1
        bind_host_id = self.driver.network_binding_host_id(context, instance)
        for attempt in range(1, attempts + 1):
            try:
                nwinfo = self.network_api.allocate_for_instance(
                        context, instance,
                        requested_networks=requested_networks,
                        security_groups=security_groups,
                        bind_host_id=bind_host_id,
                        resource_provider_mapping=resource_provider_mapping,
                        network_arqs=network_arqs)
                LOG.debug('Instance network_info: |%s|', nwinfo,
                          instance=instance)
                instance.system_metadata['network_allocated'] = 'True'
                # NOTE(JoshNang) do not save the instance here, as it can cause
                # races. The caller shares a reference to instance and waits
                # for this async greenthread to finish before calling
                # instance.save().
                return nwinfo
            except Exception as e:
                log_info = {'attempt': attempt,
                            'attempts': attempts}
                if attempt == attempts:
                    LOG.exception('Instance failed network setup '
                                  'after %(attempts)d attempt(s)',
                                  log_info)
                    raise e
                LOG.warning('Instance failed network setup '
                            '(attempt %(attempt)d of %(attempts)d)',
                            log_info, instance=instance)
                time.sleep(retry_time)
                retry_time *= 2
                if retry_time > 30:
                    retry_time = 30
        # Not reached.

    def _build_networks_for_instance(self, context, instance,
            requested_networks, security_groups, resource_provider_mapping,
            network_arqs):

        # If we're here from a reschedule the network may already be allocated.
        if strutils.bool_from_string(
                instance.system_metadata.get('network_allocated', 'False')):
            # NOTE(alex_xu): The network_allocated is True means the network
            # resource already allocated at previous scheduling, and the
            # network setup is cleanup at previous. After rescheduling, the
            # network resource need setup on the new host.
            self.network_api.setup_instance_network_on_host(
                context, instance, instance.host)
            return self.network_api.get_instance_nw_info(context, instance)

        network_info = self._allocate_network(context, instance,
                requested_networks, security_groups,
                resource_provider_mapping,
                network_arqs)

        return network_info

    def _allocate_network(self, context, instance, requested_networks,
                          security_groups, resource_provider_mapping,
                          network_arqs):
        """Start network allocation asynchronously.  Return an instance
        of NetworkInfoAsyncWrapper that can be used to retrieve the
        allocated networks when the operation has finished.
        """
        # NOTE(comstud): Since we're allocating networks asynchronously,
        # this task state has little meaning, as we won't be in this
        # state for very long.
        instance.vm_state = vm_states.BUILDING
        instance.task_state = task_states.NETWORKING
        instance.save(expected_task_state=[None])

        return network_model.NetworkInfoAsyncWrapper(
                self._allocate_network_async, context, instance,
                requested_networks, security_groups, resource_provider_mapping,
                network_arqs)

    def _default_root_device_name(self, instance, image_meta, root_bdm):
        """Gets a default root device name from the driver.

        :param nova.objects.Instance instance:
            The instance for which to get the root device name.
        :param nova.objects.ImageMeta image_meta:
            The metadata of the image of the instance.
        :param nova.objects.BlockDeviceMapping root_bdm:
            The description of the root device.
        :returns: str -- The default root device name.
        :raises: InternalError, TooManyDiskDevices
        """
        try:
            return self.driver.default_root_device_name(instance,
                                                        image_meta,
                                                        root_bdm)
        except NotImplementedError:
            return compute_utils.get_next_device_name(instance, [])

    def _default_device_names_for_instance(self, instance,
                                           root_device_name,
                                           *block_device_lists):
        """Default the missing device names in the BDM from the driver.

        :param nova.objects.Instance instance:
            The instance for which to get default device names.
        :param str root_device_name: The root device name.
        :param list block_device_lists: List of block device mappings.
        :returns: None
        :raises: InternalError, TooManyDiskDevices
        """
        try:
            self.driver.default_device_names_for_instance(instance,
                                                          root_device_name,
                                                          *block_device_lists)
        except NotImplementedError:
            compute_utils.default_device_names_for_instance(
                instance, root_device_name, *block_device_lists)

    def _get_device_name_for_instance(self, instance, bdms, block_device_obj):
        """Get the next device name from the driver, based on the BDM.

        :param nova.objects.Instance instance:
            The instance whose volume is requesting a device name.
        :param nova.objects.BlockDeviceMappingList bdms:
            The block device mappings for the instance.
        :param nova.objects.BlockDeviceMapping block_device_obj:
            A block device mapping containing info about the requested block
            device.
        :returns: The next device name.
        :raises: InternalError, TooManyDiskDevices
        """
        # NOTE(ndipanov): Copy obj to avoid changing the original
        block_device_obj = block_device_obj.obj_clone()
        try:
            return self.driver.get_device_name_for_instance(
                instance, bdms, block_device_obj)
        except NotImplementedError:
            return compute_utils.get_device_name_for_instance(
                instance, bdms, block_device_obj.get("device_name"))

    def _default_block_device_names(self, instance, image_meta, block_devices):
        """Verify that all the devices have the device_name set. If not,
        provide a default name.

        It also ensures that there is a root_device_name and is set to the
        first block device in the boot sequence (boot_index=0).
        """
        root_bdm = block_device.get_root_bdm(block_devices)
        if not root_bdm:
            return

        # Get the root_device_name from the root BDM or the instance
        root_device_name = None
        update_root_bdm = False

        if root_bdm.device_name:
            root_device_name = root_bdm.device_name
            instance.root_device_name = root_device_name
        elif instance.root_device_name:
            root_device_name = instance.root_device_name
            root_bdm.device_name = root_device_name
            update_root_bdm = True
        else:
            root_device_name = self._default_root_device_name(instance,
                                                              image_meta,
                                                              root_bdm)

            instance.root_device_name = root_device_name
            root_bdm.device_name = root_device_name
            update_root_bdm = True

        if update_root_bdm:
            root_bdm.save()

        ephemerals = []
        swap = []
        block_device_mapping = []
        image = []

        for device in block_devices:
            if block_device.new_format_is_ephemeral(device):
                ephemerals.append(device)

            if block_device.new_format_is_swap(device):
                swap.append(device)

            if driver_block_device.is_block_device_mapping(device):
                block_device_mapping.append(device)

            if driver_block_device.is_local_image(device):
                image.append(device)

        self._default_device_names_for_instance(instance,
                                                root_device_name,
                                                image,
                                                ephemerals,
                                                swap,
                                                block_device_mapping)

    def _add_missing_dev_names(self, bdms, instance):
        for bdm in bdms:
            if bdm.device_name is not None:
                continue

            device_name = self._get_device_name_for_instance(instance,
                                                             bdms, bdm)
            values = {'device_name': device_name}
            bdm.update(values)
            bdm.save()

    def _prep_block_device(self, context, instance, bdms):
        """Set up the block device for an instance with error logging."""
        try:
            self._add_missing_dev_names(bdms, instance)
            block_device_info = driver.get_block_device_info(instance, bdms)
            mapping = driver.block_device_info_get_mapping(block_device_info)
            driver_block_device.attach_block_devices(
                mapping, context, instance, self.volume_api, self.driver,
                wait_func=self._await_block_device_map_created)

            return block_device_info

        except exception.OverQuota as e:
            LOG.warning('Failed to create block device for instance due'
                        ' to exceeding volume related resource quota.'
                        ' Error: %s', e.message, instance=instance)
            raise

        except Exception as ex:
            LOG.exception('Instance failed block device setup',
                          instance=instance)
            # InvalidBDM will eventually result in a BuildAbortException when
            # booting from volume, and will be recorded as an instance fault.
            # Maintain the original exception message which most likely has
            # useful details which the standard InvalidBDM error message lacks.
            raise exception.InvalidBDM(str(ex))

    def _update_instance_after_spawn(self, instance,
                                     vm_state=vm_states.ACTIVE):
        instance.power_state = self._get_power_state(instance)
        instance.vm_state = vm_state
        instance.task_state = None
        # NOTE(sean-k-mooney): configdrive.update_instance checks
        # instance.launched_at to determine if it is the first or
        # subsequent spawn of an instance. We need to call update_instance
        # first before setting instance.launched_at or instance.config_drive
        # will never be set to true based on the value of force_config_drive.
        # As a result the config drive will be lost on a hard reboot of the
        # instance even when force_config_drive=true. see bug #1835822.
        configdrive.update_instance(instance)
        instance.launched_at = timeutils.utcnow()

    def _update_scheduler_instance_info(self, context, instance):
        """Sends an InstanceList with created or updated Instance objects to
        the Scheduler client.

        In the case of init_host, the value passed will already be an
        InstanceList. Other calls will send individual Instance objects that
        have been created or resized. In this case, we create an InstanceList
        object containing that Instance.
        """
        if not self.send_instance_updates:
            return
        if isinstance(instance, obj_instance.Instance):
            instance = objects.InstanceList(objects=[instance])
        context = context.elevated()
        self.query_client.update_instance_info(context, self.host,
                                               instance)

    def _delete_scheduler_instance_info(self, context, instance_uuid):
        """Sends the uuid of the deleted Instance to the Scheduler client."""
        if not self.send_instance_updates:
            return
        context = context.elevated()
        self.query_client.delete_instance_info(context, self.host,
                                               instance_uuid)

    @periodic_task.periodic_task(spacing=CONF.scheduler_instance_sync_interval)
    def _sync_scheduler_instance_info(self, context):
        if not self.send_instance_updates:
            return
        context = context.elevated()
        instances = objects.InstanceList.get_by_host(context, self.host,
                                                     expected_attrs=[],
                                                     use_slave=True)
        uuids = [instance.uuid for instance in instances]
        self.query_client.sync_instance_info(context, self.host, uuids)

    def _notify_about_instance_usage(self, context, instance, event_suffix,
                                     network_info=None, extra_usage_info=None,
                                     fault=None):
        compute_utils.notify_about_instance_usage(
            self.notifier, context, instance, event_suffix,
            network_info=network_info,
            extra_usage_info=extra_usage_info, fault=fault)

    def _deallocate_network(self, context, instance,
                            requested_networks=None):
        # If we were told not to allocate networks let's save ourselves
        # the trouble of calling the network API.
        if requested_networks and requested_networks.no_allocate:
            LOG.debug("Skipping network deallocation for instance since "
                      "networking was not requested.", instance=instance)
            return

        LOG.debug('Deallocating network for instance', instance=instance)
        with timeutils.StopWatch() as timer:
            self.network_api.deallocate_for_instance(
                context, instance, requested_networks=requested_networks)
        # nova-network does an rpc call so we're OK tracking time spent here
        LOG.info('Took %0.2f seconds to deallocate network for instance.',
                 timer.elapsed(), instance=instance)

    def _get_instance_block_device_info(self, context, instance,
                                        refresh_conn_info=False,
                                        bdms=None):
        """Transform block devices to the driver block_device format."""

        if bdms is None:
            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                    context, instance.uuid)
        block_device_info = driver.get_block_device_info(instance, bdms)

        if not refresh_conn_info:
            # if the block_device_mapping has no value in connection_info
            # (returned as None), don't include in the mapping
            block_device_info['block_device_mapping'] = [
                bdm for bdm in driver.block_device_info_get_mapping(
                                    block_device_info)
                if bdm.get('connection_info')]
        else:
            driver_block_device.refresh_conn_infos(
                driver.block_device_info_get_mapping(block_device_info),
                context, instance, self.volume_api, self.driver)

        return block_device_info

    def _build_failed(self, node):
        if CONF.compute.consecutive_build_service_disable_threshold:
            # NOTE(danms): Update our counter, but wait for the next
            # update_available_resource() periodic to flush it to the DB
            self.rt.build_failed(node)

    def _build_succeeded(self, node):
        self.rt.build_succeeded(node)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_fault
    def build_and_run_instance(self, context, instance, image, request_spec,
                     filter_properties, accel_uuids, admin_password=None,
                     injected_files=None, requested_networks=None,
                     security_groups=None, block_device_mapping=None,
                     node=None, limits=None, host_list=None):

        @utils.synchronized(instance.uuid)
        def _locked_do_build_and_run_instance(*args, **kwargs):
            # NOTE(danms): We grab the semaphore with the instance uuid
            # locked because we could wait in line to build this instance
            # for a while and we want to make sure that nothing else tries
            # to do anything with this instance while we wait.
            with self._build_semaphore:
                try:
                    result = self._do_build_and_run_instance(*args, **kwargs)
                except Exception:
                    # NOTE(mriedem): This should really only happen if
                    # _decode_files in _do_build_and_run_instance fails, and
                    # that's before a guest is spawned so it's OK to remove
                    # allocations for the instance for this node from Placement
                    # below as there is no guest consuming resources anyway.
                    # The _decode_files case could be handled more specifically
                    # but that's left for another day.
                    result = build_results.FAILED
                    raise
                finally:
                    if result == build_results.FAILED:
                        # Remove the allocation records from Placement for the
                        # instance if the build failed. The instance.host is
                        # likely set to None in _do_build_and_run_instance
                        # which means if the user deletes the instance, it
                        # will be deleted in the API, not the compute service.
                        # Setting the instance.host to None in
                        # _do_build_and_run_instance means that the
                        # ResourceTracker will no longer consider this instance
                        # to be claiming resources against it, so we want to
                        # reflect that same thing in Placement.  No need to
                        # call this for a reschedule, as the allocations will
                        # have already been removed in
                        # self._do_build_and_run_instance().
                        self.reportclient.delete_allocation_for_instance(
                            context, instance.uuid, force=True)

                    if result in (build_results.FAILED,
                                  build_results.RESCHEDULED):
                        self._build_failed(node)
                    else:
                        self._build_succeeded(node)

        # NOTE(danms): We spawn here to return the RPC worker thread back to
        # the pool. Since what follows could take a really long time, we don't
        # want to tie up RPC workers.
        utils.spawn_n(_locked_do_build_and_run_instance,
                      context, instance, image, request_spec,
                      filter_properties, admin_password, injected_files,
                      requested_networks, security_groups,
                      block_device_mapping, node, limits, host_list,
                      accel_uuids)

    def _check_device_tagging(self, requested_networks, block_device_mapping):
        tagging_requested = False
        if requested_networks:
            for net in requested_networks:
                if 'tag' in net and net.tag is not None:
                    tagging_requested = True
                    break
        if block_device_mapping and not tagging_requested:
            for bdm in block_device_mapping:
                if 'tag' in bdm and bdm.tag is not None:
                    tagging_requested = True
                    break
        if (tagging_requested and
                not self.driver.capabilities.get('supports_device_tagging',
                                                 False)):
            raise exception.BuildAbortException('Attempt to boot guest with '
                                                'tagged devices on host that '
                                                'does not support tagging.')

    def _check_trusted_certs(self, instance):
        if (instance.trusted_certs and
                not self.driver.capabilities.get('supports_trusted_certs',
                                                 False)):
            raise exception.BuildAbortException(
                'Trusted image certificates provided on host that does not '
                'support certificate validation.')

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def _do_build_and_run_instance(self, context, instance, image,
            request_spec, filter_properties, admin_password, injected_files,
            requested_networks, security_groups, block_device_mapping,
            node=None, limits=None, host_list=None, accel_uuids=None):

        try:
            LOG.debug('Starting instance...', instance=instance)
            instance.vm_state = vm_states.BUILDING
            instance.task_state = None
            instance.save(expected_task_state=
                    (task_states.SCHEDULING, None))
        except exception.InstanceNotFound:
            msg = 'Instance disappeared before build.'
            LOG.debug(msg, instance=instance)
            return build_results.FAILED
        except exception.UnexpectedTaskStateError as e:
            LOG.debug(e.format_message(), instance=instance)
            return build_results.FAILED

        # b64 decode the files to inject:
        decoded_files = self._decode_files(injected_files)

        if limits is None:
            limits = {}

        if node is None:
            node = self._get_nodename(instance, refresh=True)

        try:
            with timeutils.StopWatch() as timer:
                self._build_and_run_instance(context, instance, image,
                        decoded_files, admin_password, requested_networks,
                        security_groups, block_device_mapping, node, limits,
                        filter_properties, request_spec, accel_uuids)
            LOG.info('Took %0.2f seconds to build instance.',
                     timer.elapsed(), instance=instance)
            return build_results.ACTIVE
        except exception.RescheduledException as e:
            retry = filter_properties.get('retry')
            if not retry:
                # no retry information, do not reschedule.
                LOG.debug("Retry info not present, will not reschedule",
                    instance=instance)
                self._cleanup_allocated_networks(context, instance,
                    requested_networks)
                compute_utils.add_instance_fault_from_exc(context,
                        instance, e, sys.exc_info(),
                        fault_message=e.kwargs['reason'])
                self._nil_out_instance_obj_host_and_node(instance)
                self._set_instance_obj_error_state(instance,
                                                   clean_task_state=True)
                return build_results.FAILED
            LOG.debug(e.format_message(), instance=instance)
            # This will be used for logging the exception
            retry['exc'] = traceback.format_exception(*sys.exc_info())
            # This will be used for setting the instance fault message
            retry['exc_reason'] = e.kwargs['reason']

            self._cleanup_allocated_networks(context, instance,
                                             requested_networks)

            self._nil_out_instance_obj_host_and_node(instance)
            instance.task_state = task_states.SCHEDULING
            instance.save()
            # The instance will have already claimed resources from this host
            # before this build was attempted. Now that it has failed, we need
            # to unclaim those resources before casting to the conductor, so
            # that if there are alternate hosts available for a retry, it can
            # claim resources on that new host for the instance.
            self.reportclient.delete_allocation_for_instance(
                context, instance.uuid, force=True)

            self.compute_task_api.build_instances(context, [instance],
                    image, filter_properties, admin_password,
                    injected_files, requested_networks, security_groups,
                    block_device_mapping, request_spec=request_spec,
                    host_lists=[host_list])
            return build_results.RESCHEDULED
        except (exception.InstanceNotFound,
                exception.UnexpectedDeletingTaskStateError):
            msg = 'Instance disappeared during build.'
            LOG.debug(msg, instance=instance)
            self._cleanup_allocated_networks(context, instance,
                    requested_networks)
            return build_results.FAILED
        except Exception as e:
            if isinstance(e, exception.BuildAbortException):
                LOG.error(e.format_message(), instance=instance)
            else:
                # Should not reach here.
                LOG.exception('Unexpected build failure, not rescheduling '
                              'build.', instance=instance)
            self._cleanup_allocated_networks(context, instance,
                    requested_networks)
            self._cleanup_volumes(context, instance,
                    block_device_mapping, raise_exc=False)
            compute_utils.add_instance_fault_from_exc(context, instance,
                    e, sys.exc_info())
            self._nil_out_instance_obj_host_and_node(instance)
            self._set_instance_obj_error_state(instance, clean_task_state=True)
            return build_results.FAILED

    @staticmethod
    def _get_scheduler_hints(filter_properties, request_spec=None):
        """Helper method to get scheduler hints.

        This method prefers to get the hints out of the request spec, but that
        might not be provided. Conductor will pass request_spec down to the
        first compute chosen for a build but older computes will not pass
        the request_spec to conductor's build_instances method for a
        a reschedule, so if we're on a host via a retry, request_spec may not
        be provided so we need to fallback to use the filter_properties
        to get scheduler hints.
        """
        hints = {}
        if request_spec is not None and 'scheduler_hints' in request_spec:
            hints = request_spec.scheduler_hints
        if not hints:
            hints = filter_properties.get('scheduler_hints') or {}
        return hints

    @staticmethod
    def _get_request_group_mapping(request_spec):
        """Return request group resource - provider mapping. This is currently
        used for Neutron ports that have resource request due to the port
        having QoS minimum bandwidth policy rule attached.

        :param request_spec: A RequestSpec object or None
        :returns: A dict keyed by RequestGroup requester_id, currently Neutron
        port_id, to resource provider UUID that provides resource for that
        RequestGroup. Or None if the request_spec was None.
        """
        # TODO(sbauza): Remove this conditional once we only support
        # RPC API 6.0
        if request_spec:
            return request_spec.get_request_group_mapping()
        else:
            return None

    def _build_and_run_instance(self, context, instance, image, injected_files,
            admin_password, requested_networks, security_groups,
            block_device_mapping, node, limits, filter_properties,
            request_spec=None, accel_uuids=None):

        image_name = image.get('name')
        self._notify_about_instance_usage(context, instance, 'create.start',
                extra_usage_info={'image_name': image_name})
        compute_utils.notify_about_instance_create(
            context, instance, self.host,
            phase=fields.NotificationPhase.START,
            bdms=block_device_mapping)

        # NOTE(mikal): cache the keystone roles associated with the instance
        # at boot time for later reference
        instance.system_metadata.update(
            {'boot_roles': ','.join(context.roles)})

        self._check_device_tagging(requested_networks, block_device_mapping)
        self._check_trusted_certs(instance)

        provider_mapping = self._get_request_group_mapping(request_spec)

        if provider_mapping:
            try:
                compute_utils\
                    .update_pci_request_spec_with_allocated_interface_name(
                        context, self.reportclient,
                        instance.pci_requests.requests, provider_mapping)
            except (exception.AmbiguousResourceProviderForPCIRequest,
                    exception.UnexpectedResourceProviderNameForPCIRequest
                    ) as e:
                raise exception.BuildAbortException(
                    reason=str(e), instance_uuid=instance.uuid)

        # TODO(Luyao) cut over to get_allocs_for_consumer
        allocs = self.reportclient.get_allocations_for_consumer(
                context, instance.uuid)

        try:
            scheduler_hints = self._get_scheduler_hints(filter_properties,
                                                        request_spec)
            with self.rt.instance_claim(context, instance, node, allocs,
                                        limits):
                # NOTE(russellb) It's important that this validation be done
                # *after* the resource tracker instance claim, as that is where
                # the host is set on the instance.
                self._validate_instance_group_policy(context, instance,
                                                     scheduler_hints)
                image_meta = objects.ImageMeta.from_dict(image)

                with self._build_resources(context, instance,
                        requested_networks, security_groups, image_meta,
                        block_device_mapping, provider_mapping,
                        accel_uuids) as resources:
                    instance.vm_state = vm_states.BUILDING
                    instance.task_state = task_states.SPAWNING
                    # NOTE(JoshNang) This also saves the changes to the
                    # instance from _allocate_network_async, as they aren't
                    # saved in that function to prevent races.
                    instance.save(expected_task_state=
                            task_states.BLOCK_DEVICE_MAPPING)
                    block_device_info = resources['block_device_info']
                    network_info = resources['network_info']
                    accel_info = resources['accel_info']
                    LOG.debug('Start spawning the instance on the hypervisor.',
                              instance=instance)
                    with timeutils.StopWatch() as timer:
                        self.driver.spawn(context, instance, image_meta,
                                          injected_files, admin_password,
                                          allocs, network_info=network_info,
                                          block_device_info=block_device_info,
                                          accel_info=accel_info)
                    LOG.info('Took %0.2f seconds to spawn the instance on '
                             'the hypervisor.', timer.elapsed(),
                             instance=instance)
        except (exception.InstanceNotFound,
                exception.UnexpectedDeletingTaskStateError) as e:
            with excutils.save_and_reraise_exception():
                self._notify_about_instance_usage(context, instance,
                    'create.error', fault=e)
                compute_utils.notify_about_instance_create(
                    context, instance, self.host,
                    phase=fields.NotificationPhase.ERROR, exception=e,
                    bdms=block_device_mapping)
        except exception.ComputeResourcesUnavailable as e:
            LOG.debug(e.format_message(), instance=instance)
            self._notify_about_instance_usage(context, instance,
                    'create.error', fault=e)
            compute_utils.notify_about_instance_create(
                    context, instance, self.host,
                    phase=fields.NotificationPhase.ERROR, exception=e,
                    bdms=block_device_mapping)
            raise exception.RescheduledException(
                    instance_uuid=instance.uuid, reason=e.format_message())
        except exception.BuildAbortException as e:
            with excutils.save_and_reraise_exception():
                LOG.debug(e.format_message(), instance=instance)
                self._notify_about_instance_usage(context, instance,
                    'create.error', fault=e)
                compute_utils.notify_about_instance_create(
                    context, instance, self.host,
                    phase=fields.NotificationPhase.ERROR, exception=e,
                    bdms=block_device_mapping)
        except exception.NoMoreFixedIps as e:
            LOG.warning('No more fixed IP to be allocated',
                        instance=instance)
            self._notify_about_instance_usage(context, instance,
                    'create.error', fault=e)
            compute_utils.notify_about_instance_create(
                    context, instance, self.host,
                    phase=fields.NotificationPhase.ERROR, exception=e,
                    bdms=block_device_mapping)
            msg = _('Failed to allocate the network(s) with error %s, '
                    'not rescheduling.') % e.format_message()
            raise exception.BuildAbortException(instance_uuid=instance.uuid,
                    reason=msg)
        except (exception.ExternalNetworkAttachForbidden,
                exception.VirtualInterfaceCreateException,
                exception.VirtualInterfaceMacAddressException,
                exception.FixedIpInvalidOnHost,
                exception.UnableToAutoAllocateNetwork,
                exception.NetworksWithQoSPolicyNotSupported) as e:
            LOG.exception('Failed to allocate network(s)',
                          instance=instance)
            self._notify_about_instance_usage(context, instance,
                    'create.error', fault=e)
            compute_utils.notify_about_instance_create(
                    context, instance, self.host,
                    phase=fields.NotificationPhase.ERROR, exception=e,
                    bdms=block_device_mapping)
            msg = _('Failed to allocate the network(s), not rescheduling.')
            raise exception.BuildAbortException(instance_uuid=instance.uuid,
                    reason=msg)
        except (exception.FlavorDiskTooSmall,
                exception.FlavorMemoryTooSmall,
                exception.ImageNotActive,
                exception.ImageUnacceptable,
                exception.InvalidDiskInfo,
                exception.InvalidDiskFormat,
                cursive_exception.SignatureVerificationError,
                exception.CertificateValidationFailed,
                exception.VolumeEncryptionNotSupported,
                exception.InvalidInput,
                # TODO(mriedem): We should be validating RequestedVRamTooHigh
                # in the API during server create and rebuild.
                exception.RequestedVRamTooHigh) as e:
            self._notify_about_instance_usage(context, instance,
                    'create.error', fault=e)
            compute_utils.notify_about_instance_create(
                    context, instance, self.host,
                    phase=fields.NotificationPhase.ERROR, exception=e,
                    bdms=block_device_mapping)
            raise exception.BuildAbortException(instance_uuid=instance.uuid,
                    reason=e.format_message())
        except Exception as e:
            LOG.exception('Failed to build and run instance',
                          instance=instance)
            self._notify_about_instance_usage(context, instance,
                    'create.error', fault=e)
            compute_utils.notify_about_instance_create(
                    context, instance, self.host,
                    phase=fields.NotificationPhase.ERROR, exception=e,
                    bdms=block_device_mapping)
            raise exception.RescheduledException(
                    instance_uuid=instance.uuid, reason=str(e))

        # NOTE(alaski): This is only useful during reschedules, remove it now.
        instance.system_metadata.pop('network_allocated', None)

        # If CONF.default_access_ip_network_name is set, grab the
        # corresponding network and set the access ip values accordingly.
        network_name = CONF.default_access_ip_network_name
        if (network_name and not instance.access_ip_v4 and
                not instance.access_ip_v6):
            # Note that when there are multiple ips to choose from, an
            # arbitrary one will be chosen.
            for vif in network_info:
                if vif['network']['label'] == network_name:
                    for ip in vif.fixed_ips():
                        if not instance.access_ip_v4 and ip['version'] == 4:
                            instance.access_ip_v4 = ip['address']
                        if not instance.access_ip_v6 and ip['version'] == 6:
                            instance.access_ip_v6 = ip['address']
                    break

        self._update_instance_after_spawn(instance)

        try:
            instance.save(expected_task_state=task_states.SPAWNING)
        except (exception.InstanceNotFound,
                exception.UnexpectedDeletingTaskStateError) as e:
            with excutils.save_and_reraise_exception():
                self._notify_about_instance_usage(context, instance,
                    'create.error', fault=e)
                compute_utils.notify_about_instance_create(
                    context, instance, self.host,
                    phase=fields.NotificationPhase.ERROR, exception=e,
                    bdms=block_device_mapping)

        self._update_scheduler_instance_info(context, instance)
        self._notify_about_instance_usage(context, instance, 'create.end',
                extra_usage_info={'message': _('Success')},
                network_info=network_info)
        compute_utils.notify_about_instance_create(context, instance,
                self.host, phase=fields.NotificationPhase.END,
                bdms=block_device_mapping)

    def _build_resources_cleanup(self, instance, network_info):
        # Make sure the async call finishes
        if network_info is not None:
            network_info.wait(do_raise=False)
            self.driver.clean_networks_preparation(instance,
                                                   network_info)
        self.driver.failed_spawn_cleanup(instance)

    @contextlib.contextmanager
    def _build_resources(self, context, instance, requested_networks,
                         security_groups, image_meta, block_device_mapping,
                         resource_provider_mapping, accel_uuids):
        resources = {}
        network_info = None
        spec_arqs = {}
        network_arqs = {}

        try:
            if accel_uuids:
                arqs = self._get_bound_arq_resources(
                    context, instance, accel_uuids)
                spec_arqs, network_arqs = self._split_network_arqs(
                    arqs, requested_networks)
                LOG.debug("ARQs for spec:%s, ARQs for network:%s",
                    spec_arqs, network_arqs)
        except (Exception, eventlet.timeout.Timeout) as exc:
            LOG.exception(exc)
            # ARQs created for instance or ports.
            # The port binding isn't done yet.
            # Unbind port won't clean port ARQs.
            compute_utils.delete_arqs_if_needed(
                context, instance, accel_uuids)
            msg = _('Failure getting accelerator requests.')
            raise exception.BuildAbortException(
                    reason=msg, instance_uuid=instance.uuid)

        try:
            LOG.debug('Start building networks asynchronously for instance.',
                      instance=instance)
            network_info = self._build_networks_for_instance(context, instance,
                    requested_networks, security_groups,
                    resource_provider_mapping, network_arqs)
            resources['network_info'] = network_info
        except (exception.InstanceNotFound,
                exception.UnexpectedDeletingTaskStateError):
            raise
        except exception.UnexpectedTaskStateError as e:
            raise exception.BuildAbortException(instance_uuid=instance.uuid,
                    reason=e.format_message())
        except Exception:
            # Because this allocation is async any failures are likely to occur
            # when the driver accesses network_info during spawn().
            LOG.exception('Failed to allocate network(s)',
                          instance=instance)
            msg = _('Failed to allocate the network(s), not rescheduling.')
            raise exception.BuildAbortException(instance_uuid=instance.uuid,
                    reason=msg)

        try:
            # Perform any driver preparation work for the driver.
            self.driver.prepare_for_spawn(instance)

            # Depending on a virt driver, some network configuration is
            # necessary before preparing block devices.
            self.driver.prepare_networks_before_block_device_mapping(
                instance, network_info)

            # Verify that all the BDMs have a device_name set and assign a
            # default to the ones missing it with the help of the driver.
            self._default_block_device_names(instance, image_meta,
                                             block_device_mapping)

            LOG.debug('Start building block device mappings for instance.',
                      instance=instance)
            instance.vm_state = vm_states.BUILDING
            instance.task_state = task_states.BLOCK_DEVICE_MAPPING
            instance.save()

            block_device_info = self._prep_block_device(context, instance,
                    block_device_mapping)
            resources['block_device_info'] = block_device_info
        except (exception.InstanceNotFound,
                exception.UnexpectedDeletingTaskStateError):
            with excutils.save_and_reraise_exception():
                self._build_resources_cleanup(instance, network_info)
        except (exception.UnexpectedTaskStateError,
                exception.InstanceUnacceptable,
                exception.OverQuota, exception.InvalidBDM) as e:
            self._build_resources_cleanup(instance, network_info)
            raise exception.BuildAbortException(instance_uuid=instance.uuid,
                    reason=e.format_message())
        except Exception:
            LOG.exception('Failure prepping block device',
                          instance=instance)
            self._build_resources_cleanup(instance, network_info)
            msg = _('Failure prepping block device.')
            raise exception.BuildAbortException(instance_uuid=instance.uuid,
                    reason=msg)

        resources['accel_info'] = list(spec_arqs.values())
        try:
            yield resources
        except Exception as exc:
            with excutils.save_and_reraise_exception() as ctxt:
                if not isinstance(exc, (
                        exception.InstanceNotFound,
                        exception.UnexpectedDeletingTaskStateError)):
                    LOG.exception('Instance failed to spawn',
                                  instance=instance)
                # Make sure the async call finishes
                if network_info is not None:
                    network_info.wait(do_raise=False)
                # if network_info is empty we're likely here because of
                # network allocation failure. Since nothing can be reused on
                # rescheduling it's better to deallocate network to eliminate
                # the chance of orphaned ports in neutron
                deallocate_networks = False if network_info else True
                try:
                    self._shutdown_instance(context, instance,
                            block_device_mapping, requested_networks,
                            try_deallocate_networks=deallocate_networks)
                except Exception as exc2:
                    ctxt.reraise = False
                    LOG.warning('Could not clean up failed build,'
                                ' not rescheduling. Error: %s',
                                str(exc2))
                    raise exception.BuildAbortException(
                            instance_uuid=instance.uuid,
                            reason=str(exc))
                finally:
                    # Call Cyborg to delete accelerator requests
                    if accel_uuids:
                        # ARQs created for instance or ports.
                        # Port bind may not successful.
                        # unbind port won't clean port ARQs.
                        compute_utils.delete_arqs_if_needed(
                            context, instance, accel_uuids)

    def _get_bound_arq_resources(self, context, instance, arq_uuids):
        """Get bound accelerator requests.

        The ARQ binding was kicked off in the conductor as an async
        operation. Here we wait for the notification from Cyborg.

        If the notification arrived before this point, which can happen
        in many/most cases (see [1]), it will be lost. To handle that,
        we use exit_wait_early.
        [1] https://review.opendev.org/#/c/631244/46/nova/compute/
            manager.py@2627

        :param instance: instance object
        :param arq_uuids: List of accelerator request (ARQ) UUIDs.
        :returns: List of ARQs for which bindings have completed,
                  successfully or otherwise
        """

        cyclient = cyborg.get_client(context)
        if arq_uuids is None:
            arqs = cyclient.get_arqs_for_instance(instance.uuid)
            arq_uuids = [arq['uuid'] for arq in arqs]
        events = [('accelerator-request-bound', arq_uuid)
                  for arq_uuid in arq_uuids]

        timeout = CONF.arq_binding_timeout
        with self.virtapi.wait_for_instance_event(
                instance, events, deadline=timeout):
            resolved_arqs = cyclient.get_arqs_for_instance(
                    instance.uuid, only_resolved=True)
            # Events for these resolved ARQs may have already arrived.
            # Such 'early' events need to be ignored.
            early_events = [('accelerator-request-bound', arq['uuid'])
                             for arq in resolved_arqs]
            if early_events:
                self.virtapi.exit_wait_early(early_events)

        # Since a timeout in wait_for_instance_event will raise, we get
        # here only if all binding events have been received.
        resolved_uuids = [arq['uuid'] for arq in resolved_arqs]
        if sorted(resolved_uuids) != sorted(arq_uuids):
            # Query Cyborg to get all.
            arqs = cyclient.get_arqs_for_instance(instance.uuid)
        else:
            arqs = resolved_arqs
        return arqs

    def _split_network_arqs(self, arqs, requested_networks):
        """splif arq request by exra spec from ARQ requested by port.

        Return ARQ groups tuple:(spec_arqs, port_arqs)
        Each item in the tuple is a dict like:
            {
                arq1_uuid: arq1
            }
        """
        port_arqs = {}
        spec_arqs = {}
        port_arqs_uuids = [req_net.arq_uuid for req_net in requested_networks]
        for arq in arqs:
            if arq['uuid'] in port_arqs_uuids:
                port_arqs.update({arq['uuid']: arq})
            else:
                spec_arqs.update({arq['uuid']: arq})

        return spec_arqs, port_arqs

    def _cleanup_allocated_networks(self, context, instance,
            requested_networks):
        """Cleanup networks allocated for instance.

        :param context: nova request context
        :param instance: nova.objects.instance.Instance object
        :param requested_networks: nova.objects.NetworkRequestList
        """
        LOG.debug('Unplugging VIFs for instance', instance=instance)

        network_info = instance.get_network_info()

        # NOTE(stephenfin) to avoid nova destroying the instance without
        # unplugging the interface, refresh network_info if it is empty.
        if not network_info:
            try:
                network_info = self.network_api.get_instance_nw_info(
                    context, instance,
                )
            except Exception as exc:
                LOG.warning(
                    'Failed to update network info cache when cleaning up '
                    'allocated networks. Stale VIFs may be left on this host.'
                    'Error: %s', str(exc)
                )
                return

        try:
            self.driver.unplug_vifs(instance, network_info)
        except NotImplementedError:
            # This is an optional method so ignore things if it doesn't exist
            LOG.debug(
                'Virt driver does not provide unplug_vifs method, so it '
                'is not possible determine if VIFs should be unplugged.'
            )
        except exception.NovaException as exc:
            # It's possible that the instance never got as far as plugging
            # VIFs, in which case we would see an exception which can be
            # mostly ignored
            LOG.warning(
                'Cleaning up VIFs failed for instance. Error: %s',
                str(exc), instance=instance,
            )
        else:
            LOG.debug('Unplugged VIFs for instance', instance=instance)

        try:
            self._deallocate_network(context, instance, requested_networks)
        except Exception:
            LOG.exception('Failed to deallocate networks', instance=instance)
            return

        instance.system_metadata['network_allocated'] = 'False'
        try:
            instance.save()
        except exception.InstanceNotFound:
            # NOTE(alaski): It's possible that we're cleaning up the networks
            # because the instance was deleted.  If that's the case then this
            # exception will be raised by instance.save()
            pass

    def _try_deallocate_network(self, context, instance,
                                requested_networks=None):

        # During auto-scale cleanup, we could be deleting a large number
        # of servers at the same time and overloading parts of the system,
        # so we retry a few times in case of connection failures to the
        # networking service.
        @loopingcall.RetryDecorator(
            max_retry_count=3, inc_sleep_time=2, max_sleep_time=12,
            exceptions=(keystone_exception.connection.ConnectFailure,))
        def _deallocate_network_with_retries():
            try:
                self._deallocate_network(
                    context, instance, requested_networks)
            except keystone_exception.connection.ConnectFailure as e:
                # Provide a warning that something is amiss.
                with excutils.save_and_reraise_exception():
                    LOG.warning('Failed to deallocate network for instance; '
                                'retrying. Error: %s', str(e),
                                instance=instance)

        try:
            # tear down allocated network structure
            _deallocate_network_with_retries()
        except Exception as ex:
            with excutils.save_and_reraise_exception():
                LOG.error('Failed to deallocate network for instance. '
                          'Error: %s', ex, instance=instance)
                self._set_instance_obj_error_state(instance)

    def _get_power_off_values(self, instance, clean_shutdown):
        """Get the timing configuration for powering down this instance."""
        if clean_shutdown:
            timeout = compute_utils.get_value_from_system_metadata(instance,
                          key='image_os_shutdown_timeout', type=int,
                          default=CONF.shutdown_timeout)
            retry_interval = CONF.compute.shutdown_retry_interval
        else:
            timeout = 0
            retry_interval = 0

        return timeout, retry_interval

    def _power_off_instance(self, instance, clean_shutdown=True):
        """Power off an instance on this host."""
        timeout, retry_interval = self._get_power_off_values(
            instance, clean_shutdown)
        self.driver.power_off(instance, timeout, retry_interval)

    def _shutdown_instance(self, context, instance,
                           bdms, requested_networks=None, notify=True,
                           try_deallocate_networks=True):
        """Shutdown an instance on this host.

        :param:context: security context
        :param:instance: a nova.objects.Instance object
        :param:bdms: the block devices for the instance to be torn
                     down
        :param:requested_networks: the networks on which the instance
                                   has ports
        :param:notify: true if a final usage notification should be
                       emitted
        :param:try_deallocate_networks: false if we should avoid
                                        trying to teardown networking
        """
        context = context.elevated()
        LOG.info('Terminating instance', instance=instance)

        if notify:
            self._notify_about_instance_usage(context, instance,
                                              "shutdown.start")
            compute_utils.notify_about_instance_action(context, instance,
                    self.host, action=fields.NotificationAction.SHUTDOWN,
                    phase=fields.NotificationPhase.START, bdms=bdms)

        network_info = instance.get_network_info()

        # NOTE(arnaudmorin) to avoid nova destroying the instance without
        # unplugging the interface, refresh network_info if it is empty.
        if not network_info:
            network_info = self.network_api.get_instance_nw_info(
                context, instance)

        # NOTE(vish) get bdms before destroying the instance
        vol_bdms = [bdm for bdm in bdms if bdm.is_volume]
        block_device_info = self._get_instance_block_device_info(
            context, instance, bdms=bdms)

        # NOTE(melwitt): attempt driver destroy before releasing ip, may
        #                want to keep ip allocated for certain failures
        try:
            LOG.debug('Start destroying the instance on the hypervisor.',
                      instance=instance)
            with timeutils.StopWatch() as timer:
                self.driver.destroy(context, instance, network_info,
                                    block_device_info)
            LOG.info('Took %0.2f seconds to destroy the instance on the '
                     'hypervisor.', timer.elapsed(), instance=instance)
        except exception.InstancePowerOffFailure:
            # if the instance can't power off, don't release the ip
            with excutils.save_and_reraise_exception():
                pass
        except Exception:
            with excutils.save_and_reraise_exception():
                # deallocate ip and fail without proceeding to
                # volume api calls, preserving current behavior
                if try_deallocate_networks:
                    self._try_deallocate_network(context, instance,
                                                 requested_networks)

        if try_deallocate_networks:
            self._try_deallocate_network(context, instance, requested_networks)

        timer.restart()
        connector = None
        for bdm in vol_bdms:
            try:
                if bdm.attachment_id:
                    self.volume_api.attachment_delete(context,
                                                      bdm.attachment_id)
                else:
                    # NOTE(vish): actual driver detach done in driver.destroy,
                    #             so just tell cinder that we are done with it.
                    if connector is None:
                        connector = self.driver.get_volume_connector(instance)
                    self.volume_api.terminate_connection(context,
                                                         bdm.volume_id,
                                                         connector)
                    self.volume_api.detach(context, bdm.volume_id,
                                           instance.uuid)

            except exception.VolumeAttachmentNotFound as exc:
                LOG.debug('Ignoring VolumeAttachmentNotFound: %s', exc,
                          instance=instance)
            except exception.DiskNotFound as exc:
                LOG.debug('Ignoring DiskNotFound: %s', exc,
                          instance=instance)
            except exception.VolumeNotFound as exc:
                LOG.debug('Ignoring VolumeNotFound: %s', exc,
                          instance=instance)
            except (cinder_exception.EndpointNotFound,
                    keystone_exception.EndpointNotFound) as exc:
                LOG.warning('Ignoring EndpointNotFound for '
                            'volume %(volume_id)s: %(exc)s',
                            {'exc': exc, 'volume_id': bdm.volume_id},
                            instance=instance)
            except cinder_exception.ClientException as exc:
                LOG.warning('Ignoring unknown cinder exception for '
                            'volume %(volume_id)s: %(exc)s',
                            {'exc': exc, 'volume_id': bdm.volume_id},
                            instance=instance)
            except Exception as exc:
                LOG.warning('Ignoring unknown exception for '
                            'volume %(volume_id)s: %(exc)s',
                            {'exc': exc, 'volume_id': bdm.volume_id},
                            instance=instance)
        if vol_bdms:
            LOG.info('Took %(time).2f seconds to detach %(num)s volumes '
                     'for instance.',
                     {'time': timer.elapsed(), 'num': len(vol_bdms)},
                     instance=instance)

        if notify:
            self._notify_about_instance_usage(context, instance,
                                              "shutdown.end")
            compute_utils.notify_about_instance_action(context, instance,
                    self.host, action=fields.NotificationAction.SHUTDOWN,
                    phase=fields.NotificationPhase.END, bdms=bdms)

    def _cleanup_volumes(self, context, instance, bdms, raise_exc=True,
                         detach=True):
        original_exception = None
        for bdm in bdms:
            if detach and bdm.volume_id:
                try:
                    LOG.debug("Detaching volume: %s", bdm.volume_id,
                              instance_uuid=instance.uuid)
                    destroy = bdm.delete_on_termination
                    self._detach_volume(context, bdm, instance,
                                        destroy_bdm=destroy)
                except Exception as exc:
                    original_exception = exc
                    LOG.warning('Failed to detach volume: %(volume_id)s '
                                'due to %(exc)s',
                                {'volume_id': bdm.volume_id, 'exc': exc})

            if bdm.volume_id and bdm.delete_on_termination:
                try:
                    LOG.debug("Deleting volume: %s", bdm.volume_id,
                              instance_uuid=instance.uuid)
                    self.volume_api.delete(context, bdm.volume_id)
                except Exception as exc:
                    original_exception = exc
                    LOG.warning('Failed to delete volume: %(volume_id)s '
                                'due to %(exc)s',
                                {'volume_id': bdm.volume_id, 'exc': exc})
        if original_exception is not None and raise_exc:
            raise original_exception

    def _delete_instance(self, context, instance, bdms):
        """Delete an instance on this host.

        :param context: nova request context
        :param instance: nova.objects.instance.Instance object
        :param bdms: nova.objects.block_device.BlockDeviceMappingList object
        """
        events = self.instance_events.clear_events_for_instance(instance)
        if events:
            LOG.debug('Events pending at deletion: %(events)s',
                      {'events': ','.join(events.keys())},
                      instance=instance)
        self._notify_about_instance_usage(context, instance,
                                          "delete.start")
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.DELETE,
                phase=fields.NotificationPhase.START, bdms=bdms)

        self._shutdown_instance(context, instance, bdms)

        # NOTE(vish): We have already deleted the instance, so we have
        #             to ignore problems cleaning up the volumes. It
        #             would be nice to let the user know somehow that
        #             the volume deletion failed, but it is not
        #             acceptable to have an instance that can not be
        #             deleted. Perhaps this could be reworked in the
        #             future to set an instance fault the first time
        #             and to only ignore the failure if the instance
        #             is already in ERROR.

        # NOTE(ameeda): The volumes have already been detached during
        #               the above _shutdown_instance() call and this is
        #               why detach is not requested from
        #               _cleanup_volumes() in this case

        self._cleanup_volumes(context, instance, bdms,
                raise_exc=False, detach=False)
        # Delete Cyborg ARQs if the instance has a device profile.
        compute_utils.delete_arqs_if_needed(context, instance)
        # if a delete task succeeded, always update vm state and task
        # state without expecting task state to be DELETING
        instance.vm_state = vm_states.DELETED
        instance.task_state = None
        instance.power_state = power_state.NOSTATE
        instance.terminated_at = timeutils.utcnow()
        instance.save()

        self._complete_deletion(context, instance)
        # only destroy the instance in the db if the _complete_deletion
        # doesn't raise and therefore allocation is successfully
        # deleted in placement
        instance.destroy()

        self._notify_about_instance_usage(context, instance, "delete.end")
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.DELETE,
                phase=fields.NotificationPhase.END, bdms=bdms)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def terminate_instance(self, context, instance, bdms):
        """Terminate an instance on this host."""
        @utils.synchronized(instance.uuid)
        def do_terminate_instance(instance, bdms):
            # NOTE(mriedem): If we are deleting the instance while it was
            # booting from volume, we could be racing with a database update of
            # the BDM volume_id. Since the compute API passes the BDMs over RPC
            # to compute here, the BDMs may be stale at this point. So check
            # for any volume BDMs that don't have volume_id set and if we
            # detect that, we need to refresh the BDM list before proceeding.
            # TODO(mriedem): Move this into _delete_instance and make the bdms
            # parameter optional.
            for bdm in list(bdms):
                if bdm.is_volume and not bdm.volume_id:
                    LOG.debug('There are potentially stale BDMs during '
                              'delete, refreshing the BlockDeviceMappingList.',
                              instance=instance)
                    bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                        context, instance.uuid)
                    break
            try:
                self._delete_instance(context, instance, bdms)
            except exception.InstanceNotFound:
                LOG.info("Instance disappeared during terminate",
                         instance=instance)
            except Exception:
                # As we're trying to delete always go to Error if something
                # goes wrong that _delete_instance can't handle.
                with excutils.save_and_reraise_exception():
                    LOG.exception('Setting instance vm_state to ERROR',
                                  instance=instance)
                    self._set_instance_obj_error_state(instance)

        do_terminate_instance(instance, bdms)

    # NOTE(johannes): This is probably better named power_off_instance
    # so it matches the driver method, but because of other issues, we
    # can't use that name in grizzly.
    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def stop_instance(self, context, instance, clean_shutdown):
        """Stopping an instance on this host."""

        @utils.synchronized(instance.uuid)
        def do_stop_instance():
            current_power_state = self._get_power_state(instance)
            LOG.debug('Stopping instance; current vm_state: %(vm_state)s, '
                      'current task_state: %(task_state)s, current DB '
                      'power_state: %(db_power_state)s, current VM '
                      'power_state: %(current_power_state)s',
                      {'vm_state': instance.vm_state,
                       'task_state': instance.task_state,
                       'db_power_state': instance.power_state,
                       'current_power_state': current_power_state},
                      instance_uuid=instance.uuid)

            # NOTE(mriedem): If the instance is already powered off, we are
            # possibly tearing down and racing with other operations, so we can
            # expect the task_state to be None if something else updates the
            # instance and we're not locking it.
            expected_task_state = [task_states.POWERING_OFF]
            # The list of power states is from _sync_instance_power_state.
            if current_power_state in (power_state.NOSTATE,
                                       power_state.SHUTDOWN,
                                       power_state.CRASHED):
                LOG.info('Instance is already powered off in the '
                         'hypervisor when stop is called.',
                         instance=instance)
                expected_task_state.append(None)

            self._notify_about_instance_usage(context, instance,
                                              "power_off.start")

            compute_utils.notify_about_instance_action(context, instance,
                        self.host, action=fields.NotificationAction.POWER_OFF,
                        phase=fields.NotificationPhase.START)

            self._power_off_instance(instance, clean_shutdown)
            instance.power_state = self._get_power_state(instance)
            instance.vm_state = vm_states.STOPPED
            instance.task_state = None
            instance.save(expected_task_state=expected_task_state)
            self._notify_about_instance_usage(context, instance,
                                              "power_off.end")

            compute_utils.notify_about_instance_action(context, instance,
                        self.host, action=fields.NotificationAction.POWER_OFF,
                        phase=fields.NotificationPhase.END)

        do_stop_instance()

    def _power_on(self, context, instance):
        network_info = self.network_api.get_instance_nw_info(context, instance)
        block_device_info = self._get_instance_block_device_info(context,
                                                                 instance)
        accel_info = self._get_accel_info(context, instance)
        self.driver.power_on(context, instance,
                             network_info,
                             block_device_info, accel_info)

    def _delete_snapshot_of_shelved_instance(self, context, instance,
                                             snapshot_id):
        """Delete snapshot of shelved instance."""
        try:
            self.image_api.delete(context, snapshot_id)
        except (exception.ImageNotFound,
                exception.ImageNotAuthorized) as exc:
            LOG.warning("Failed to delete snapshot "
                        "from shelved instance (%s).",
                        exc.format_message(), instance=instance)
        except Exception:
            LOG.exception("Something wrong happened when trying to "
                          "delete snapshot from shelved instance.",
                          instance=instance)

    # NOTE(johannes): This is probably better named power_on_instance
    # so it matches the driver method, but because of other issues, we
    # can't use that name in grizzly.
    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def start_instance(self, context, instance):
        """Starting an instance on this host."""
        self._notify_about_instance_usage(context, instance, "power_on.start")
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.POWER_ON,
            phase=fields.NotificationPhase.START)
        self._power_on(context, instance)
        instance.power_state = self._get_power_state(instance)
        instance.vm_state = vm_states.ACTIVE
        instance.task_state = None

        # Delete an image(VM snapshot) for a shelved instance
        snapshot_id = instance.system_metadata.get('shelved_image_id')
        if snapshot_id:
            self._delete_snapshot_of_shelved_instance(context, instance,
                                                      snapshot_id)

        # Delete system_metadata for a shelved instance
        compute_utils.remove_shelved_keys_from_system_metadata(instance)

        instance.save(expected_task_state=task_states.POWERING_ON)
        self._notify_about_instance_usage(context, instance, "power_on.end")
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.POWER_ON,
            phase=fields.NotificationPhase.END)

    @messaging.expected_exceptions(NotImplementedError,
                                   exception.TriggerCrashDumpNotSupported,
                                   exception.InstanceNotRunning)
    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def trigger_crash_dump(self, context, instance):
        """Trigger crash dump in an instance."""

        self._notify_about_instance_usage(context, instance,
                                          "trigger_crash_dump.start")
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.TRIGGER_CRASH_DUMP,
                phase=fields.NotificationPhase.START)

        # This method does not change task_state and power_state because the
        # effect of a trigger depends on user's configuration.
        self.driver.trigger_crash_dump(instance)

        self._notify_about_instance_usage(context, instance,
                                          "trigger_crash_dump.end")
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.TRIGGER_CRASH_DUMP,
                phase=fields.NotificationPhase.END)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def soft_delete_instance(self, context, instance):
        """Soft delete an instance on this host."""
        with compute_utils.notify_about_instance_delete(
                self.notifier, context, instance, 'soft_delete',
                source=fields.NotificationSource.COMPUTE):
            try:
                self.driver.soft_delete(instance)
            except NotImplementedError:
                # Fallback to just powering off the instance if the
                # hypervisor doesn't implement the soft_delete method
                self.driver.power_off(instance)
            instance.power_state = self._get_power_state(instance)
            instance.vm_state = vm_states.SOFT_DELETED
            instance.task_state = None
            instance.save(expected_task_state=[task_states.SOFT_DELETING])

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def restore_instance(self, context, instance):
        """Restore a soft-deleted instance on this host."""
        self._notify_about_instance_usage(context, instance, "restore.start")
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.RESTORE,
            phase=fields.NotificationPhase.START)
        try:
            self.driver.restore(instance)
        except NotImplementedError:
            # Fallback to just powering on the instance if the hypervisor
            # doesn't implement the restore method
            self._power_on(context, instance)
        instance.power_state = self._get_power_state(instance)
        instance.vm_state = vm_states.ACTIVE
        instance.task_state = None
        instance.save(expected_task_state=task_states.RESTORING)
        self._notify_about_instance_usage(context, instance, "restore.end")
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.RESTORE,
            phase=fields.NotificationPhase.END)

    @staticmethod
    def _set_migration_status(migration, status):
        """Set the status, and guard against a None being passed in.

        This is useful as some of the compute RPC calls will not pass
        a migration object in older versions. The check can be removed when
        we move past 4.x major version of the RPC API.
        """
        if migration:
            migration.status = status
            migration.save()

    @staticmethod
    def _reimage_failed_callback(event_name, instance):
        msg = ('Cinder reported failure during reimaging '
               'with %(event)s for instance %(uuid)s')
        msg_args = {'event': event_name, 'uuid': instance.uuid}
        LOG.error(msg, msg_args)
        raise exception.ReimageException(msg % msg_args)

    def _detach_root_volume(self, context, instance, root_bdm):
        volume_id = root_bdm.volume_id
        mp = root_bdm.device_name
        old_connection_info = jsonutils.loads(root_bdm.connection_info)
        try:
            self.driver.detach_volume(context, old_connection_info,
                                      instance, root_bdm.device_name)
        except exception.DiskNotFound as err:
            LOG.warning('Ignoring DiskNotFound exception while '
                        'detaching volume %(volume_id)s from '
                        '%(mp)s : %(err)s',
                        {'volume_id': volume_id, 'mp': mp,
                         'err': err}, instance=instance)
        except exception.DeviceDetachFailed:
            with excutils.save_and_reraise_exception():
                LOG.warning('Guest refused to detach volume %(vol)s',
                            {'vol': volume_id}, instance=instance)
                self.volume_api.roll_detaching(context, volume_id)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception('Failed to detach volume '
                              '%(volume_id)s from %(mp)s',
                              {'volume_id': volume_id, 'mp': mp},
                              instance=instance)
                self.volume_api.roll_detaching(context, volume_id)

    def _rebuild_volume_backed_instance(self, context, instance, bdms,
                                        image_id):
        # Get root bdm and attachment ID associated to it
        root_bdm = compute_utils.get_root_bdm(context, instance, bdms)
        old_attachment_id = root_bdm.attachment_id

        # Create a new attachment and delete the previous attachment
        # We create a new attachment first to keep the volume in
        # reserved state after old attachment is deleted and avoid any
        # races in between the attachment create and delete.
        attachment_id = None
        try:
            attachment_id = self.volume_api.attachment_create(
                context, root_bdm.volume_id, instance.uuid)['id']
            self._detach_root_volume(context, instance, root_bdm)
            root_bdm.attachment_id = attachment_id
            root_bdm.save()
            self.volume_api.attachment_delete(context,
                                              old_attachment_id)
        except exception.InstanceNotFound:
            # This means we failed to save the new attachment because
            # the instance is deleted, so (try to) delete it and abort.
            try:
                self.volume_api.attachment_delete(context,
                                                  attachment_id)
            except cinder_exception.ClientException:
                LOG.error('Failed to delete new attachment %s',
                          attachment_id)
            msg = _('Failed to rebuild volume backed instance.')
            raise exception.BuildAbortException(
                instance_uuid=instance.uuid, reason=msg)
        except cinder_exception.ClientException:
            if attachment_id:
                LOG.error('Failed to delete old attachment %s',
                          old_attachment_id)
            else:
                LOG.error('Failed to create new attachment')
            msg = _('Failed to rebuild volume backed instance.')
            raise exception.BuildAbortException(
                instance_uuid=instance.uuid, reason=msg)
        events = [('volume-reimaged', root_bdm.volume_id)]

        # Get the image requested for rebuild
        try:
            image = self.image_api.get(context, image_id)
        except exception.ImageNotFound:
            msg = _('Image %s not found.') % image_id
            LOG.error(msg)
            raise exception.BuildAbortException(
                instance_uuid=instance.uuid, reason=msg)
        image_size = int(math.ceil(float(image.get('size')) / units.Gi))
        deadline = CONF.reimage_timeout_per_gb * image_size
        error_cb = self._reimage_failed_callback

        # Call cinder to perform reimage operation and wait until an
        # external event is triggered.
        try:
            with self.virtapi.wait_for_instance_event(instance, events,
                                                      deadline=deadline,
                                                      error_callback=error_cb):
                self.volume_api.reimage_volume(
                    context, root_bdm.volume_id, image_id,
                    reimage_reserved=True)

        except Exception as ex:
            LOG.error('Failed to rebuild volume backed instance: %s',
                      str(ex), instance=instance)
            msg = _('Failed to rebuild volume backed instance.')
            raise exception.BuildAbortException(
                instance_uuid=instance.uuid, reason=msg)

    def _rebuild_default_impl(
            self, context, instance, image_meta, injected_files,
            admin_password, allocations, bdms, detach_block_devices,
            attach_block_devices, network_info=None, evacuate=False,
            block_device_info=None, preserve_ephemeral=False,
            accel_uuids=None, reimage_boot_volume=False):
        if preserve_ephemeral:
            # The default code path does not support preserving ephemeral
            # partitions.
            raise exception.PreserveEphemeralNotSupported()

        accel_info = []
        detach_root_bdm = not reimage_boot_volume
        if evacuate:
            if instance.flavor.extra_specs.get('accel:device_profile'):
                try:
                    accel_info = self._get_bound_arq_resources(
                        context, instance, accel_uuids or [])
                except (Exception, eventlet.timeout.Timeout) as exc:
                    LOG.exception(exc)
                    self._build_resources_cleanup(instance, network_info)
                    msg = _('Failure getting accelerator resources.')
                    raise exception.BuildAbortException(
                        instance_uuid=instance.uuid, reason=msg)
            detach_block_devices(context, bdms,
                                 detach_root_bdm=detach_root_bdm)
        else:
            self._power_off_instance(instance, clean_shutdown=True)
            detach_block_devices(context, bdms,
                                 detach_root_bdm=detach_root_bdm)
            if reimage_boot_volume:
                # Previously, the calls reaching here were for image
                # backed instance rebuild and didn't have a root bdm
                # so now we need to handle the case for root bdm.
                # For the root BDM, we are doing attach/detach operations
                # manually as we want to maintain a 'reserved' state
                # throughout the reimage process from the cinder side so
                # we are excluding the root BDM from certain operations
                # here i.e. deleteing it's mapping before the destroy call.
                block_device_info_copy = copy.deepcopy(block_device_info)
                root_bdm = compute_utils.get_root_bdm(context, instance, bdms)
                mapping = block_device_info_copy["block_device_mapping"]
                # drop root bdm from the mapping
                mapping = [
                  bdm for bdm in mapping
                  if bdm["volume_id"] != root_bdm.volume_id
                ]
                self.driver.destroy(context, instance,
                                    network_info=network_info,
                                    block_device_info=block_device_info_copy)
            else:
                self.driver.destroy(context, instance,
                    network_info=network_info,
                    block_device_info=block_device_info)
            try:
                accel_info = self._get_accel_info(context, instance)
            except Exception as exc:
                LOG.exception(exc)
                self._build_resources_cleanup(instance, network_info)
                msg = _('Failure getting accelerator resources.')
                raise exception.BuildAbortException(
                    instance_uuid=instance.uuid, reason=msg)
            if reimage_boot_volume:
                is_volume_backed = compute_utils.is_volume_backed_instance(
                    context, instance, bdms)
                if is_volume_backed:
                    self._rebuild_volume_backed_instance(
                        context, instance, bdms, image_meta.id)

        instance.task_state = task_states.REBUILD_BLOCK_DEVICE_MAPPING
        instance.save(expected_task_state=[task_states.REBUILDING])

        new_block_device_info = attach_block_devices(context, instance, bdms)

        instance.task_state = task_states.REBUILD_SPAWNING
        instance.save(
            expected_task_state=[task_states.REBUILD_BLOCK_DEVICE_MAPPING])

        with instance.mutated_migration_context():
            self.driver.spawn(context, instance, image_meta, injected_files,
                              admin_password, allocations,
                              network_info=network_info,
                              block_device_info=new_block_device_info,
                              accel_info=accel_info)

    def _notify_instance_rebuild_error(self, context, instance, error, bdms):
        self._notify_about_instance_usage(context, instance,
                                          'rebuild.error', fault=error)
        compute_utils.notify_about_instance_rebuild(
            context, instance, self.host,
            phase=fields.NotificationPhase.ERROR, exception=error, bdms=bdms)

    @messaging.expected_exceptions(exception.PreserveEphemeralNotSupported,
                                   exception.BuildAbortException)
    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def rebuild_instance(self, context, instance, orig_image_ref, image_ref,
                         injected_files, new_pass, orig_sys_metadata,
                         bdms, recreate, on_shared_storage,
                         preserve_ephemeral, migration,
                         scheduled_node, limits, request_spec, accel_uuids,
                         reimage_boot_volume):
        """Destroy and re-make this instance.

        A 'rebuild' effectively purges all existing data from the system and
        remakes the VM with given 'metadata' and 'personalities'.

        :param context: `nova.RequestContext` object
        :param instance: Instance object
        :param orig_image_ref: Original image_ref before rebuild
        :param image_ref: New image_ref for rebuild
        :param injected_files: Files to inject
        :param new_pass: password to set on rebuilt instance
        :param orig_sys_metadata: instance system metadata from pre-rebuild
        :param bdms: block-device-mappings to use for rebuild
        :param recreate: True if the instance is being evacuated (e.g. the
            hypervisor it was on failed) - cleanup of old state will be
            skipped.
        :param on_shared_storage: True if instance files on shared storage.
                                  If not provided then information from the
                                  driver will be used to decide if the instance
                                  files are available or not on the target host
        :param preserve_ephemeral: True if the default ephemeral storage
                                   partition must be preserved on rebuild
        :param migration: a Migration object if one was created for this
                          rebuild operation (if it's a part of evacuate)
        :param scheduled_node: A node of the host chosen by the scheduler. If a
                               host was specified by the user, this will be
                               None
        :param limits: Overcommit limits set by the scheduler. If a host was
                       specified by the user, this will be None
        :param request_spec: a RequestSpec object used to schedule the instance
        :param accel_uuids: a list of cyborg ARQ uuids
        :param reimage_boot_volume: Boolean to specify whether the user has
                                    explicitly requested to rebuild a boot
                                    volume

        """
        # recreate=True means the instance is being evacuated from a failed
        # host to a new destination host (this host). The 'recreate' variable
        # name is confusing, so rename it to evacuate here at the top, which
        # is simpler than renaming a parameter in an RPC versioned method.
        evacuate = recreate
        context = context.elevated()

        if evacuate:
            LOG.info("Evacuating instance", instance=instance)
        else:
            LOG.info("Rebuilding instance", instance=instance)

        if evacuate:
            # This is an evacuation to a new host, so we need to perform a
            # resource claim.
            rebuild_claim = self.rt.rebuild_claim
        else:
            # This is a rebuild to the same host, so we don't need to make
            # a claim since the instance is already on this host.
            rebuild_claim = claims.NopClaim

        if image_ref:
            image_meta = objects.ImageMeta.from_image_ref(
                context, self.image_api, image_ref)
        elif evacuate:
            # For evacuate the API does not send down the image_ref since the
            # image does not change so just get it from what was stashed in
            # the instance system_metadata when the instance was created (or
            # last rebuilt). This also works for volume-backed instances.
            image_meta = instance.image_meta
        else:
            image_meta = objects.ImageMeta()

        # NOTE(mriedem): On an evacuate, we need to update
        # the instance's host and node properties to reflect it's
        # destination node for the evacuate.
        if not scheduled_node:
            if evacuate:
                try:
                    compute_node = self._get_compute_info(context, self.host)
                    scheduled_node = compute_node.hypervisor_hostname
                except exception.ComputeHostNotFound:
                    LOG.exception('Failed to get compute_info for %s',
                                  self.host)
            else:
                scheduled_node = instance.node

        allocs = self.reportclient.get_allocations_for_consumer(
                    context, instance.uuid)

        # If the resource claim or group policy validation fails before we
        # do anything to the guest or its networking/volumes we want to keep
        # the current status rather than put the instance into ERROR status.
        instance_state = instance.vm_state
        with self._error_out_instance_on_exception(
                context, instance, instance_state=instance_state):
            try:
                self._do_rebuild_instance_with_claim(
                    context, instance, orig_image_ref,
                    image_meta, injected_files, new_pass, orig_sys_metadata,
                    bdms, evacuate, on_shared_storage, preserve_ephemeral,
                    migration, request_spec, allocs, rebuild_claim,
                    scheduled_node, limits, accel_uuids, reimage_boot_volume)
            except (exception.ComputeResourcesUnavailable,
                    exception.RescheduledException) as e:
                if isinstance(e, exception.ComputeResourcesUnavailable):
                    LOG.debug("Could not rebuild instance on this host, not "
                              "enough resources available.", instance=instance)
                else:
                    # RescheduledException is raised by the late server group
                    # policy check during evacuation if a parallel scheduling
                    # violated the policy.
                    # We catch the RescheduledException here but we don't have
                    # the plumbing to do an actual reschedule so we abort the
                    # operation.
                    LOG.debug("Could not rebuild instance on this host, "
                              "late server group check failed.",
                              instance=instance)
                # NOTE(ndipanov): We just abort the build for now and leave a
                # migration record for potential cleanup later
                self._set_migration_status(migration, 'failed')
                # Since the claim failed, we need to remove the allocation
                # created against the destination node. Note that we can only
                # get here when evacuating to a destination node. Rebuilding
                # on the same host (not evacuate) uses the NopClaim which will
                # not raise ComputeResourcesUnavailable.
                self.rt.delete_allocation_for_evacuated_instance(
                    context, instance, scheduled_node, node_type='destination')
                self._notify_instance_rebuild_error(context, instance, e, bdms)
                # Wrap this in InstanceFaultRollback so that the
                # _error_out_instance_on_exception context manager keeps the
                # vm_state unchanged.
                raise exception.InstanceFaultRollback(
                    inner_exception=exception.BuildAbortException(
                        instance_uuid=instance.uuid,
                        reason=e.format_message()))
            except (exception.InstanceNotFound,
                    exception.UnexpectedDeletingTaskStateError) as e:
                LOG.debug('Instance was deleted while rebuilding',
                          instance=instance)
                self._set_migration_status(migration, 'failed')
                self._notify_instance_rebuild_error(context, instance, e, bdms)
            except Exception as e:
                self._set_migration_status(migration, 'failed')
                if evacuate or scheduled_node is not None:
                    self.rt.delete_allocation_for_evacuated_instance(
                        context, instance, scheduled_node,
                        node_type='destination')
                self._notify_instance_rebuild_error(context, instance, e, bdms)
                raise
            else:
                # NOTE(gibi): Let the resource tracker set the instance
                # host and drop the migration context as we need to hold the
                # COMPUTE_RESOURCE_SEMAPHORE to avoid the race with
                # _update_available_resources. See bug 1896463.
                self.rt.finish_evacuation(instance, scheduled_node, migration)

    def _do_rebuild_instance_with_claim(
            self, context, instance, orig_image_ref, image_meta,
            injected_files, new_pass, orig_sys_metadata, bdms, evacuate,
            on_shared_storage, preserve_ephemeral, migration, request_spec,
            allocations, rebuild_claim, scheduled_node, limits, accel_uuids,
            reimage_boot_volume):
        """Helper to avoid deep nesting in the top-level method."""

        provider_mapping = None
        if evacuate:
            provider_mapping = self._get_request_group_mapping(request_spec)

            if provider_mapping:
                compute_utils.\
                    update_pci_request_spec_with_allocated_interface_name(
                        context, self.reportclient,
                        instance.pci_requests.requests, provider_mapping)

        claim_context = rebuild_claim(
            context, instance, scheduled_node, allocations,
            limits=limits, image_meta=image_meta, migration=migration)

        with claim_context:
            self._do_rebuild_instance(
                context, instance, orig_image_ref, image_meta, injected_files,
                new_pass, orig_sys_metadata, bdms, evacuate, on_shared_storage,
                preserve_ephemeral, migration, request_spec, allocations,
                provider_mapping, accel_uuids, reimage_boot_volume)

    @staticmethod
    def _get_image_name(image_meta):
        if image_meta.obj_attr_is_set("name"):
            return image_meta.name
        else:
            return ''

    def _do_rebuild_instance(
            self, context, instance, orig_image_ref, image_meta,
            injected_files, new_pass, orig_sys_metadata, bdms, evacuate,
            on_shared_storage, preserve_ephemeral, migration, request_spec,
            allocations, request_group_resource_providers_mapping,
            accel_uuids, reimage_boot_volume):
        orig_vm_state = instance.vm_state

        if evacuate:
            if request_spec:
                # NOTE(gibi): Do a late check of server group policy as
                # parallel scheduling could violate such policy. This will
                # cause the evacuate to fail as rebuild does not implement
                # reschedule.
                hints = self._get_scheduler_hints({}, request_spec)
                self._validate_instance_group_policy(context, instance, hints)

            if not self.driver.capabilities.get("supports_evacuate", False):
                raise exception.InstanceEvacuateNotSupported

            self._check_instance_exists(instance)

            if on_shared_storage is None:
                LOG.debug('on_shared_storage is not provided, using driver '
                          'information to decide if the instance needs to '
                          'be evacuated')
                on_shared_storage = self.driver.instance_on_disk(instance)

            elif (on_shared_storage !=
                    self.driver.instance_on_disk(instance)):
                # To cover case when admin expects that instance files are
                # on shared storage, but not accessible and vice versa
                raise exception.InvalidSharedStorage(
                        _("Invalid state of instance files on shared"
                            " storage"))

            if on_shared_storage:
                LOG.info('disk on shared storage, evacuating using'
                         ' existing disk')
            elif instance.image_ref:
                orig_image_ref = instance.image_ref
                LOG.info("disk not on shared storage, evacuating from "
                         "image: '%s'", str(orig_image_ref))
            else:
                LOG.info('disk on volume, evacuating using existing '
                         'volume')

        # We check trusted certs capabilities for both evacuate (rebuild on
        # another host) and rebuild (rebuild on the same host) because for
        # evacuate we need to make sure an instance with trusted certs can
        # have the image verified with those certs during rebuild, and for
        # rebuild we could be rebuilding a server that started out with no
        # trusted certs on this host, and then was rebuilt with trusted certs
        # for a new image, in which case we need to validate that new image
        # with the trusted certs during the rebuild.
        self._check_trusted_certs(instance)

        # This instance.exists message should contain the original
        # image_ref, not the new one.  Since the DB has been updated
        # to point to the new one... we have to override it.
        orig_image_ref_url = self.image_api.generate_image_url(orig_image_ref,
                                                               context)
        extra_usage_info = {'image_ref_url': orig_image_ref_url}
        compute_utils.notify_usage_exists(
                self.notifier, context, instance, self.host,
                current_period=True, system_metadata=orig_sys_metadata,
                extra_usage_info=extra_usage_info)

        # This message should contain the new image_ref
        extra_usage_info = {'image_name': self._get_image_name(image_meta)}
        self._notify_about_instance_usage(context, instance,
                "rebuild.start", extra_usage_info=extra_usage_info)
        # NOTE: image_name is not included in the versioned notification
        # because we already provide the image_uuid in the notification
        # payload and the image details can be looked up via the uuid.
        compute_utils.notify_about_instance_rebuild(
            context, instance, self.host,
            phase=fields.NotificationPhase.START,
            bdms=bdms)

        instance.power_state = self._get_power_state(instance)
        instance.task_state = task_states.REBUILDING
        instance.save(expected_task_state=[task_states.REBUILDING])

        if evacuate:
            self.network_api.setup_networks_on_host(
                    context, instance, self.host)
            # For nova-network this is needed to move floating IPs
            # For neutron this updates the host in the port binding
            # TODO(cfriesen): this network_api call and the one above
            # are so similar, we should really try to unify them.
            self.network_api.setup_instance_network_on_host(
                context, instance, self.host, migration,
                provider_mappings=request_group_resource_providers_mapping)
            # TODO(mriedem): Consider decorating setup_instance_network_on_host
            # with @api.refresh_cache and then we wouldn't need this explicit
            # call to get_instance_nw_info.
            network_info = self.network_api.get_instance_nw_info(context,
                                                                 instance)
        else:
            network_info = instance.get_network_info()

        if bdms is None:
            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                    context, instance.uuid)

        block_device_info = \
            self._get_instance_block_device_info(
                    context, instance, bdms=bdms)

        def detach_block_devices(context, bdms, detach_root_bdm=True):
            for bdm in bdms:
                # Previously, the calls made to this method by rebuild
                # instance operation were for image backed instances which
                # assumed we only had attached volumes and no root BDM.
                # Now we need to handle case for root BDM which we are
                # doing manually so skipping the attachment create/delete
                # calls from here.
                # The detach_root_bdm parameter is only passed while
                # rebuilding the volume backed instance so we don't have
                # to worry about other callers as they won't satisfy this
                # condition.
                # For evacuate case, we have detach_root_bdm always True
                # since we don't have reimage_boot_volume parameter in
                # this case so this will not be executed.
                if not detach_root_bdm and bdm.is_root:
                    continue
                if bdm.is_volume:
                    # NOTE (ildikov): Having the attachment_id set in the BDM
                    # means that it's the new Cinder attach/detach flow
                    # (available from v3.44). In that case we explicitly
                    # attach and detach the volumes through attachment level
                    # operations. In this scenario _detach_volume will delete
                    # the existing attachment which would make the volume
                    # status change to 'available' if we don't pre-create
                    # another empty attachment before deleting the old one.
                    attachment_id = None
                    if bdm.attachment_id:
                        attachment_id = self.volume_api.attachment_create(
                            context, bdm['volume_id'], instance.uuid)['id']
                    self._detach_volume(context, bdm, instance,
                                        destroy_bdm=False)
                    if attachment_id:
                        bdm.attachment_id = attachment_id
                        bdm.save()

        files = self._decode_files(injected_files)

        kwargs = dict(
            context=context,
            instance=instance,
            image_meta=image_meta,
            injected_files=files,
            admin_password=new_pass,
            allocations=allocations,
            bdms=bdms,
            detach_block_devices=detach_block_devices,
            attach_block_devices=self._prep_block_device,
            block_device_info=block_device_info,
            network_info=network_info,
            preserve_ephemeral=preserve_ephemeral,
            evacuate=evacuate,
            accel_uuids=accel_uuids,
            reimage_boot_volume=reimage_boot_volume)
        try:
            with instance.mutated_migration_context():
                self.driver.rebuild(**kwargs)
        except NotImplementedError:
            # NOTE(rpodolyaka): driver doesn't provide specialized version
            # of rebuild, fall back to the default implementation
            self._rebuild_default_impl(**kwargs)
        self._update_instance_after_spawn(instance)
        instance.save(expected_task_state=[task_states.REBUILD_SPAWNING])

        if orig_vm_state == vm_states.STOPPED:
            LOG.info("bringing vm to original state: '%s'",
                     orig_vm_state, instance=instance)
            instance.vm_state = vm_states.ACTIVE
            instance.task_state = task_states.POWERING_OFF
            instance.progress = 0
            instance.save()
            self.stop_instance(context, instance, False)
        # TODO(melwitt): We should clean up instance console tokens here in the
        # case of evacuate. The instance is on a new host and will need to
        # establish a new console connection.
        self._update_scheduler_instance_info(context, instance)
        self._notify_about_instance_usage(
                context, instance, "rebuild.end",
                network_info=network_info,
                extra_usage_info=extra_usage_info)
        compute_utils.notify_about_instance_rebuild(
            context, instance, self.host,
            phase=fields.NotificationPhase.END,
            bdms=bdms)

    def _handle_bad_volumes_detached(self, context, instance, bad_devices,
                                     block_device_info):
        """Handle cases where the virt-layer had to detach non-working volumes
        in order to complete an operation.
        """
        for bdm in block_device_info['block_device_mapping']:
            if bdm.get('mount_device') in bad_devices:
                try:
                    volume_id = bdm['connection_info']['data']['volume_id']
                except KeyError:
                    continue

                # NOTE(sirp): ideally we'd just call
                # `compute_api.detach_volume` here but since that hits the
                # DB directly, that's off limits from within the
                # compute-manager.
                #
                # API-detach
                LOG.info("Detaching from volume api: %s", volume_id)
                self.volume_api.begin_detaching(context, volume_id)

                # Manager-detach
                self.detach_volume(context, volume_id, instance)

    def _get_accel_info(self, context, instance):
        dp_name = instance.flavor.extra_specs.get('accel:device_profile')
        if dp_name:
            cyclient = cyborg.get_client(context)
            accel_info = cyclient.get_arqs_for_instance(instance.uuid)
        else:
            accel_info = []
        return accel_info

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def reboot_instance(self, context, instance, block_device_info,
                        reboot_type):
        @utils.synchronized(instance.uuid)
        def do_reboot_instance(context, instance, block_device_info,
                               reboot_type):
            self._reboot_instance(context, instance, block_device_info,
                                  reboot_type)
        do_reboot_instance(context, instance, block_device_info, reboot_type)

    def _reboot_instance(self, context, instance, block_device_info,
                         reboot_type):
        """Reboot an instance on this host."""
        # acknowledge the request made it to the manager
        if reboot_type == "SOFT":
            instance.task_state = task_states.REBOOT_PENDING
            expected_states = task_states.soft_reboot_states
        else:
            instance.task_state = task_states.REBOOT_PENDING_HARD
            expected_states = task_states.hard_reboot_states

        context = context.elevated()
        LOG.info("Rebooting instance", instance=instance)

        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
            context, instance.uuid)
        block_device_info = self._get_instance_block_device_info(
            context, instance, bdms=bdms)

        network_info = self.network_api.get_instance_nw_info(context, instance)

        accel_info = self._get_accel_info(context, instance)

        self._notify_about_instance_usage(context, instance, "reboot.start")
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.REBOOT,
            phase=fields.NotificationPhase.START,
            bdms=bdms
        )

        instance.power_state = self._get_power_state(instance)
        instance.save(expected_task_state=expected_states)

        if instance.power_state != power_state.RUNNING:
            state = instance.power_state
            running = power_state.RUNNING
            LOG.warning('trying to reboot a non-running instance:'
                        ' (state: %(state)s expected: %(running)s)',
                        {'state': state, 'running': running},
                        instance=instance)

        def bad_volumes_callback(bad_devices):
            self._handle_bad_volumes_detached(
                    context, instance, bad_devices, block_device_info)

        try:
            # Don't change it out of rescue mode
            if instance.vm_state == vm_states.RESCUED:
                new_vm_state = vm_states.RESCUED
            else:
                new_vm_state = vm_states.ACTIVE
            new_power_state = None
            if reboot_type == "SOFT":
                instance.task_state = task_states.REBOOT_STARTED
                expected_state = task_states.REBOOT_PENDING
            else:
                instance.task_state = task_states.REBOOT_STARTED_HARD
                expected_state = task_states.REBOOT_PENDING_HARD
            instance.save(expected_task_state=expected_state)
            self.driver.reboot(context, instance,
                               network_info,
                               reboot_type,
                               block_device_info=block_device_info,
                               accel_info=accel_info,
                               bad_volumes_callback=bad_volumes_callback)

        except Exception as error:
            with excutils.save_and_reraise_exception() as ctxt:
                exc_info = sys.exc_info()
                # if the reboot failed but the VM is running don't
                # put it into an error state
                new_power_state = self._get_power_state(instance)
                if new_power_state == power_state.RUNNING:
                    LOG.warning('Reboot failed but instance is running',
                                instance=instance)
                    compute_utils.add_instance_fault_from_exc(context,
                            instance, error, exc_info)
                    self._notify_about_instance_usage(context, instance,
                            'reboot.error', fault=error)
                    compute_utils.notify_about_instance_action(
                        context, instance, self.host,
                        action=fields.NotificationAction.REBOOT,
                        phase=fields.NotificationPhase.ERROR,
                        exception=error, bdms=bdms
                    )
                    ctxt.reraise = False
                else:
                    LOG.error('Cannot reboot instance: %s', error,
                              instance=instance)
                    self._set_instance_obj_error_state(instance)

        if not new_power_state:
            new_power_state = self._get_power_state(instance)
        try:
            instance.power_state = new_power_state
            instance.vm_state = new_vm_state
            instance.task_state = None
            instance.save()
        except exception.InstanceNotFound:
            LOG.warning("Instance disappeared during reboot",
                        instance=instance)

        self._notify_about_instance_usage(context, instance, "reboot.end")
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.REBOOT,
            phase=fields.NotificationPhase.END,
            bdms=bdms
        )

    @delete_image_on_error
    def _do_snapshot_instance(self, context, image_id, instance):
        self._snapshot_instance(context, image_id, instance,
                                task_states.IMAGE_BACKUP)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def backup_instance(self, context, image_id, instance, backup_type,
                        rotation):
        """Backup an instance on this host.

        :param backup_type: daily | weekly
        :param rotation: int representing how many backups to keep around
        """
        self._do_snapshot_instance(context, image_id, instance)
        self._rotate_backups(context, instance, backup_type, rotation)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    @delete_image_on_error
    def snapshot_instance(self, context, image_id, instance):
        """Snapshot an instance on this host.

        :param context: security context
        :param image_id: glance.db.sqlalchemy.models.Image.Id
        :param instance: a nova.objects.instance.Instance object
        """
        # NOTE(dave-mcnally) the task state will already be set by the api
        # but if the compute manager has crashed/been restarted prior to the
        # request getting here the task state may have been cleared so we set
        # it again and things continue normally
        try:
            instance.task_state = task_states.IMAGE_SNAPSHOT
            instance.save(
                        expected_task_state=task_states.IMAGE_SNAPSHOT_PENDING)
        except exception.InstanceNotFound:
            # possibility instance no longer exists, no point in continuing
            LOG.debug("Instance not found, could not set state %s "
                      "for instance.",
                      task_states.IMAGE_SNAPSHOT, instance=instance)
            return

        except exception.UnexpectedDeletingTaskStateError:
            LOG.debug("Instance being deleted, snapshot cannot continue",
                      instance=instance)
            return

        with self._snapshot_semaphore:
            self._snapshot_instance(context, image_id, instance,
                                    task_states.IMAGE_SNAPSHOT)

    def _snapshot_instance(self, context, image_id, instance,
                           expected_task_state):
        context = context.elevated()

        instance.power_state = self._get_power_state(instance)
        try:
            instance.save()

            LOG.info('instance snapshotting', instance=instance)

            if instance.power_state != power_state.RUNNING:
                state = instance.power_state
                running = power_state.RUNNING
                LOG.warning('trying to snapshot a non-running instance: '
                            '(state: %(state)s expected: %(running)s)',
                            {'state': state, 'running': running},
                            instance=instance)

            self._notify_about_instance_usage(
                context, instance, "snapshot.start")
            compute_utils.notify_about_instance_snapshot(context, instance,
                self.host, phase=fields.NotificationPhase.START,
                snapshot_image_id=image_id)

            def update_task_state(task_state,
                                  expected_state=expected_task_state):
                instance.task_state = task_state
                instance.save(expected_task_state=expected_state)

            with timeutils.StopWatch() as timer:
                self.driver.snapshot(context, instance, image_id,
                                     update_task_state)
            LOG.info('Took %0.2f seconds to snapshot the instance on '
                     'the hypervisor.', timer.elapsed(), instance=instance)

            instance.task_state = None
            instance.save(expected_task_state=task_states.IMAGE_UPLOADING)

            self._notify_about_instance_usage(context, instance,
                                              "snapshot.end")
            compute_utils.notify_about_instance_snapshot(context, instance,
                self.host, phase=fields.NotificationPhase.END,
                snapshot_image_id=image_id)
        except (exception.InstanceNotFound,
                exception.InstanceNotRunning,
                exception.UnexpectedDeletingTaskStateError):
            # the instance got deleted during the snapshot
            # Quickly bail out of here
            msg = 'Instance disappeared during snapshot'
            LOG.debug(msg, instance=instance)
            try:
                image = self.image_api.get(context, image_id)
                if image['status'] != 'active':
                    self.image_api.delete(context, image_id)
            except exception.ImageNotFound:
                LOG.debug('Image not found during clean up %s', image_id)
            except Exception:
                LOG.warning("Error while trying to clean up image %s",
                            image_id, instance=instance)
        except exception.ImageNotFound:
            instance.task_state = None
            instance.save()
            LOG.warning("Image not found during snapshot", instance=instance)

    @messaging.expected_exceptions(NotImplementedError)
    @wrap_exception()
    def volume_snapshot_create(self, context, instance, volume_id,
                               create_info):
        try:
            self.driver.volume_snapshot_create(context, instance, volume_id,
                                               create_info)
        except exception.InstanceNotRunning:
            # Libvirt driver can raise this exception
            LOG.debug('Instance disappeared during volume snapshot create',
                      instance=instance)

    @messaging.expected_exceptions(NotImplementedError)
    @wrap_exception()
    def volume_snapshot_delete(self, context, instance, volume_id,
                               snapshot_id, delete_info):
        try:
            self.driver.volume_snapshot_delete(context, instance, volume_id,
                                               snapshot_id, delete_info)
        except exception.InstanceNotRunning:
            # Libvirt driver can raise this exception
            LOG.debug('Instance disappeared during volume snapshot delete',
                      instance=instance)

    @wrap_instance_fault
    def _rotate_backups(self, context, instance, backup_type, rotation):
        """Delete excess backups associated to an instance.

        Instances are allowed a fixed number of backups (the rotation number);
        this method deletes the oldest backups that exceed the rotation
        threshold.

        :param context: security context
        :param instance: Instance dict
        :param backup_type: a user-defined type, like "daily" or "weekly" etc.
        :param rotation: int representing how many backups to keep around;
            None if rotation shouldn't be used (as in the case of snapshots)
        """
        filters = {'property-image_type': 'backup',
                   'property-backup_type': backup_type,
                   'property-instance_uuid': instance.uuid}

        images = self.image_api.get_all(context, filters=filters,
                                        sort_key='created_at', sort_dir='desc')
        num_images = len(images)
        LOG.debug("Found %(num_images)d images (rotation: %(rotation)d)",
                  {'num_images': num_images, 'rotation': rotation},
                  instance=instance)

        if num_images > rotation:
            # NOTE(sirp): this deletes all backups that exceed the rotation
            # limit
            excess = len(images) - rotation
            LOG.debug("Rotating out %d backups", excess,
                      instance=instance)
            for i in range(excess):
                image = images.pop()
                image_id = image['id']
                LOG.debug("Deleting image %s", image_id,
                          instance=instance)
                try:
                    self.image_api.delete(context, image_id)
                except exception.ImageNotFound:
                    LOG.info("Failed to find image %(image_id)s to "
                             "delete", {'image_id': image_id},
                             instance=instance)
                except (exception.ImageDeleteConflict, Exception) as exc:
                    LOG.info("Failed to delete image %(image_id)s during "
                             "deleting excess backups. "
                             "Continuing for next image.. %(exc)s",
                             {'image_id': image_id, 'exc': exc},
                             instance=instance)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def set_admin_password(self, context, instance, new_pass):
        """Set the root/admin password for an instance on this host.

        This is generally only called by API password resets after an
        image has been built.

        @param context: Nova auth context.
        @param instance: Nova instance object.
        @param new_pass: The admin password for the instance.
        """

        context = context.elevated()
        current_power_state = self._get_power_state(instance)
        expected_state = power_state.RUNNING

        if current_power_state != expected_state:
            instance.task_state = None
            instance.save(expected_task_state=task_states.UPDATING_PASSWORD)
            _msg = _('instance %s is not running') % instance.uuid
            raise exception.InstancePasswordSetFailed(
                instance=instance.uuid, reason=_msg)

        try:
            self.driver.set_admin_password(instance, new_pass)
            LOG.info("Admin password set", instance=instance)
            instance.task_state = None
            instance.save(
                expected_task_state=task_states.UPDATING_PASSWORD)
        except exception.InstanceAgentNotEnabled:
            with excutils.save_and_reraise_exception():
                LOG.debug('Guest agent is not enabled for the instance.',
                          instance=instance)
                instance.task_state = None
                instance.save(
                    expected_task_state=task_states.UPDATING_PASSWORD)
        except exception.SetAdminPasswdNotSupported:
            with excutils.save_and_reraise_exception():
                LOG.info('set_admin_password is not supported '
                         'by this driver or guest instance.',
                         instance=instance)
                instance.task_state = None
                instance.save(
                    expected_task_state=task_states.UPDATING_PASSWORD)
        except NotImplementedError:
            LOG.warning('set_admin_password is not implemented '
                        'by this driver or guest instance.',
                        instance=instance)
            instance.task_state = None
            instance.save(
                expected_task_state=task_states.UPDATING_PASSWORD)
            raise NotImplementedError(_('set_admin_password is not '
                                        'implemented by this driver or guest '
                                        'instance.'))
        except exception.UnexpectedTaskStateError:
            # interrupted by another (most likely delete) task
            # do not retry
            raise
        except Exception:
            # Catch all here because this could be anything.
            LOG.exception('set_admin_password failed', instance=instance)
            # We create a new exception here so that we won't
            # potentially reveal password information to the
            # API caller.  The real exception is logged above
            _msg = _('error setting admin password')
            raise exception.InstancePasswordSetFailed(
                instance=instance.uuid, reason=_msg)

    def _get_rescue_image(self, context, instance, rescue_image_ref=None):
        """Determine what image should be used to boot the rescue VM."""
        # 1. If rescue_image_ref is passed in, use that for rescue.
        # 2. Else, use the base image associated with instance's current image.
        #       The idea here is to provide the customer with a rescue
        #       environment which they are familiar with.
        #       So, if they built their instance off of a Debian image,
        #       their rescue VM will also be Debian.
        # 3. As a last resort, use instance's current image.
        if not rescue_image_ref:
            system_meta = utils.instance_sys_meta(instance)
            rescue_image_ref = system_meta.get('image_base_image_ref')

        if not rescue_image_ref:
            LOG.warning('Unable to find a different image to use for '
                        'rescue VM, using instance\'s current image',
                        instance=instance)
            rescue_image_ref = instance.image_ref

        return objects.ImageMeta.from_image_ref(
            context, self.image_api, rescue_image_ref)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def rescue_instance(self, context, instance, rescue_password,
                        rescue_image_ref, clean_shutdown):
        context = context.elevated()
        LOG.info('Rescuing', instance=instance)

        admin_password = (rescue_password if rescue_password else
                      utils.generate_password())

        network_info = self.network_api.get_instance_nw_info(context, instance)

        rescue_image_meta = self._get_rescue_image(context, instance,
                                                   rescue_image_ref)

        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                                              context, instance.uuid)
        block_device_info = self._get_instance_block_device_info(
                                context, instance, bdms=bdms)

        extra_usage_info = {'rescue_image_name':
                            self._get_image_name(rescue_image_meta)}
        self._notify_about_instance_usage(context, instance,
                "rescue.start", extra_usage_info=extra_usage_info,
                network_info=network_info)
        compute_utils.notify_about_instance_rescue_action(
            context, instance, self.host, rescue_image_ref,
            phase=fields.NotificationPhase.START)

        try:
            self._power_off_instance(instance, clean_shutdown)

            self.driver.rescue(context, instance, network_info,
                               rescue_image_meta, admin_password,
                               block_device_info)
        except Exception as e:
            LOG.exception("Error trying to Rescue Instance",
                          instance=instance)
            self._set_instance_obj_error_state(instance)
            raise exception.InstanceNotRescuable(
                instance_id=instance.uuid,
                reason=_("Driver Error: %s") % e)

        compute_utils.notify_usage_exists(self.notifier, context, instance,
                                          self.host, current_period=True)

        instance.vm_state = vm_states.RESCUED
        instance.task_state = None
        instance.power_state = self._get_power_state(instance)
        instance.launched_at = timeutils.utcnow()
        instance.save(expected_task_state=task_states.RESCUING)

        self._notify_about_instance_usage(context, instance,
                "rescue.end", extra_usage_info=extra_usage_info,
                network_info=network_info)
        compute_utils.notify_about_instance_rescue_action(
            context, instance, self.host, rescue_image_ref,
            phase=fields.NotificationPhase.END)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def unrescue_instance(self, context, instance):
        orig_context = context
        context = context.elevated()
        LOG.info('Unrescuing', instance=instance)

        network_info = self.network_api.get_instance_nw_info(context, instance)
        self._notify_about_instance_usage(context, instance,
                "unrescue.start", network_info=network_info)
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.UNRESCUE,
            phase=fields.NotificationPhase.START)

        with self._error_out_instance_on_exception(context, instance):
            self.driver.unrescue(orig_context, instance)

        instance.vm_state = vm_states.ACTIVE
        instance.task_state = None
        instance.power_state = self._get_power_state(instance)
        instance.save(expected_task_state=task_states.UNRESCUING)

        self._notify_about_instance_usage(context,
                                          instance,
                                          "unrescue.end",
                                          network_info=network_info)
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.UNRESCUE,
            phase=fields.NotificationPhase.END)

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def confirm_resize(self, context, instance, migration):
        """Confirms a migration/resize and deletes the 'old' instance.

        This is called from the API and runs on the source host.

        Nothing needs to happen on the destination host at this point since
        the instance is already running there. This routine just cleans up the
        source host.
        """
        @utils.synchronized(instance.uuid)
        def do_confirm_resize(context, instance, migration):
            LOG.debug("Going to confirm migration %s", migration.id,
                      instance=instance)

            if migration.status == 'confirmed':
                LOG.info("Migration %s is already confirmed",
                         migration.id, instance=instance)
                return

            if migration.status not in ('finished', 'confirming'):
                LOG.warning("Unexpected confirmation status '%(status)s' "
                            "of migration %(id)s, exit confirmation process",
                            {"status": migration.status, "id": migration.id},
                            instance=instance)
                return

            # NOTE(wangpan): Get the instance from db, if it has been
            #                deleted, we do nothing and return here
            expected_attrs = ['metadata', 'system_metadata', 'flavor']
            try:
                instance = objects.Instance.get_by_uuid(
                        context, instance.uuid,
                        expected_attrs=expected_attrs)
            except exception.InstanceNotFound:
                LOG.info("Instance is not found during confirmation",
                         instance=instance)
                return

            with self._error_out_instance_on_exception(context, instance):
                try:
                    self._confirm_resize(
                        context, instance, migration=migration)
                except Exception:
                    # Something failed when cleaning up the source host so
                    # log a traceback and leave a hint about hard rebooting
                    # the server to correct its state in the DB.
                    with excutils.save_and_reraise_exception(logger=LOG):
                        LOG.exception(
                            'Confirm resize failed on source host %s. '
                            'Resource allocations in the placement service '
                            'will be removed regardless because the instance '
                            'is now on the destination host %s. You can try '
                            'hard rebooting the instance to correct its '
                            'state.', self.host, migration.dest_compute,
                            instance=instance)
                finally:
                    # Whether an error occurred or not, at this point the
                    # instance is on the dest host. Avoid leaking allocations
                    # in placement by deleting them here...
                    self._delete_allocation_after_move(
                        context, instance, migration)
                    # ...inform the scheduler about the move...
                    self._delete_scheduler_instance_info(
                        context, instance.uuid)
                    # ...and unset the cached flavor information (this is done
                    # last since the resource tracker relies on it for its
                    # periodic tasks)
                    self._delete_stashed_flavor_info(instance)

        do_confirm_resize(context, instance, migration)

    def _get_updated_nw_info_with_pci_mapping(self, nw_info, pci_mapping):
        # NOTE(adrianc): This method returns a copy of nw_info if modifications
        # are made else it returns the original nw_info.
        updated_nw_info = nw_info
        if nw_info and pci_mapping:
            updated_nw_info = copy.deepcopy(nw_info)
            for vif in updated_nw_info:
                if vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV:
                    try:
                        vif_pci_addr = vif['profile']['pci_slot']
                        new_addr = pci_mapping[vif_pci_addr].address
                        vif['profile']['pci_slot'] = new_addr
                        LOG.debug("Updating VIF's PCI address for VIF %(id)s. "
                                  "Original value %(orig_val)s, "
                                  "new value %(new_val)s",
                                  {'id': vif['id'],
                                   'orig_val': vif_pci_addr,
                                   'new_val': new_addr})
                    except (KeyError, AttributeError):
                        with excutils.save_and_reraise_exception():
                            # NOTE(adrianc): This should never happen. If we
                            # get here it means there is some inconsistency
                            # with either 'nw_info' or 'pci_mapping'.
                            LOG.error("Unexpected error when updating network "
                                      "information with PCI mapping.")
        return updated_nw_info

    def _confirm_resize(self, context, instance, migration=None):
        """Destroys the source instance."""
        self._notify_about_instance_usage(context, instance,
                                          "resize.confirm.start")
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.RESIZE_CONFIRM,
            phase=fields.NotificationPhase.START)

        # NOTE(tr3buchet): tear down networks on source host
        self.network_api.setup_networks_on_host(context, instance,
                           migration.source_compute, teardown=True)

        # TODO(stephenfin): These next three calls should be bundled
        network_info = self.network_api.get_instance_nw_info(context,
                                                             instance)

        # NOTE(adrianc): Populate old PCI device in VIF profile
        # to allow virt driver to properly unplug it from Hypervisor.
        pci_mapping = (instance.migration_context.
                       get_pci_mapping_for_migration(True))
        network_info = self._get_updated_nw_info_with_pci_mapping(
            network_info, pci_mapping)

        self.driver.confirm_migration(context, migration, instance,
                                      network_info)

        # Free up the old_flavor usage from the resource tracker for this host.
        self.rt.drop_move_claim_at_source(context, instance, migration)

        # NOTE(mriedem): The old_vm_state could be STOPPED but the user
        # might have manually powered up the instance to confirm the
        # resize/migrate, so we need to check the current power state
        # on the instance and set the vm_state appropriately. We default
        # to ACTIVE because if the power state is not SHUTDOWN, we
        # assume _sync_instance_power_state will clean it up.
        p_state = instance.power_state
        vm_state = None
        if p_state == power_state.SHUTDOWN:
            vm_state = vm_states.STOPPED
            LOG.debug("Resized/migrated instance is powered off. "
                      "Setting vm_state to '%s'.", vm_state,
                      instance=instance)
        else:
            vm_state = vm_states.ACTIVE

        instance.vm_state = vm_state
        instance.task_state = None
        instance.save(expected_task_state=[None, task_states.DELETING,
                                           task_states.SOFT_DELETING])

        self._notify_about_instance_usage(
            context, instance, "resize.confirm.end",
            network_info=network_info)
        compute_utils.notify_about_instance_action(context, instance,
               self.host, action=fields.NotificationAction.RESIZE_CONFIRM,
               phase=fields.NotificationPhase.END)

    def _delete_allocation_after_move(self, context, instance, migration):
        """Deletes resource allocations held by the migration record against
        the source compute node resource provider after a confirmed cold /
        successful live migration.
        """
        try:
            # NOTE(danms): We're finishing on the source node, so try
            # to delete the allocation based on the migration uuid
            self.reportclient.delete_allocation_for_instance(
                context, migration.uuid, consumer_type='migration',
                force=False)
        except exception.AllocationDeleteFailed:
            LOG.error('Deleting allocation in placement for migration '
                      '%(migration_uuid)s failed. The instance '
                      '%(instance_uuid)s will be put to ERROR state '
                      'but the allocation held by the migration is '
                      'leaked.',
                      {'instance_uuid': instance.uuid,
                       'migration_uuid': migration.uuid})
            raise

    def _delete_stashed_flavor_info(self, instance):
        """Remove information about the flavor change after a resize."""
        instance.old_flavor = None
        instance.new_flavor = None
        instance.system_metadata.pop('old_vm_state', None)
        instance.save()

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def confirm_snapshot_based_resize_at_source(
            self, ctxt, instance, migration):
        """Confirms a snapshot-based resize on the source host.

        Cleans the guest from the source hypervisor including disks and drops
        the MoveClaim which will free up "old_flavor" usage from the
        ResourceTracker.

        Deletes the allocations held by the migration consumer against the
        source compute node resource provider.

        :param ctxt: nova auth request context targeted at the source cell
        :param instance: Instance object being resized which should have the
            "old_flavor" attribute set
        :param migration: Migration object for the resize operation
        """

        @utils.synchronized(instance.uuid)
        def do_confirm():
            LOG.info('Confirming resize on source host.', instance=instance)
            with self._error_out_instance_on_exception(ctxt, instance):
                # TODO(mriedem): Could probably make this try/except/finally
                # a context manager to share with confirm_resize().
                try:
                    self._confirm_snapshot_based_resize_at_source(
                        ctxt, instance, migration)
                except Exception:
                    # Something failed when cleaning up the source host so
                    # log a traceback and leave a hint about hard rebooting
                    # the server to correct its state in the DB.
                    with excutils.save_and_reraise_exception(logger=LOG):
                        LOG.exception(
                            'Confirm resize failed on source host %s. '
                            'Resource allocations in the placement service '
                            'will be removed regardless because the instance '
                            'is now on the destination host %s. You can try '
                            'hard rebooting the instance to correct its '
                            'state.', self.host, migration.dest_compute,
                            instance=instance)
                finally:
                    # Whether an error occurred or not, at this point the
                    # instance is on the dest host so to avoid leaking
                    # allocations in placement, delete them here.
                    # TODO(mriedem): Should we catch and just log
                    # AllocationDeleteFailed? What is the user's recourse if
                    # we got this far but this fails? At this point the
                    # instance is on the target host and the allocations
                    # could just be manually cleaned up by the operator.
                    self._delete_allocation_after_move(ctxt, instance,
                                                       migration)
        do_confirm()

    def _confirm_snapshot_based_resize_at_source(
            self, ctxt, instance, migration):
        """Private version of confirm_snapshot_based_resize_at_source

        This allows the main method to be decorated with error handlers.

        :param ctxt: nova auth request context targeted at the source cell
        :param instance: Instance object being resized which should have the
            "old_flavor" attribute set
        :param migration: Migration object for the resize operation
        """
        # Cleanup the guest from the hypervisor including local disks.
        network_info = self.network_api.get_instance_nw_info(ctxt, instance)
        LOG.debug('Cleaning up guest from source hypervisor including disks.',
                  instance=instance)

        # FIXME(mriedem): Per bug 1809095, _confirm_resize calls
        # _get_updated_nw_info_with_pci_mapping here prior to unplugging
        # VIFs on the source, but in our case we have already unplugged
        # VIFs during prep_snapshot_based_resize_at_source, so what do we
        # need to do about those kinds of ports? Do we need to wait to unplug
        # VIFs until confirm like normal resize?

        # Note that prep_snapshot_based_resize_at_source already destroyed the
        # guest which disconnected volumes and unplugged VIFs but did not
        # destroy disks in case something failed during the resize and the
        # instance needed to be rebooted or rebuilt on the source host. Now
        # that we are confirming the resize we want to cleanup the disks left
        # on the source host. We call cleanup() instead of destroy() to avoid
        # any InstanceNotFound confusion from the driver since the guest was
        # already destroyed on this host. block_device_info=None and
        # destroy_vifs=False means cleanup() will not try to disconnect volumes
        # or unplug VIFs.
        self.driver.cleanup(
            ctxt, instance, network_info, block_device_info=None,
            destroy_disks=True, destroy_vifs=False)

        # Delete port bindings for the source host.
        self._confirm_snapshot_based_resize_delete_port_bindings(
            ctxt, instance)

        # Delete volume attachments for the source host.
        self._delete_volume_attachments(ctxt, instance.get_bdms())

        # Free up the old_flavor usage from the resource tracker for this host.
        self.rt.drop_move_claim_at_source(ctxt, instance, migration)

    def _confirm_snapshot_based_resize_delete_port_bindings(
            self, ctxt, instance):
        """Delete port bindings for the source host when confirming
        snapshot-based resize on the source host."

        :param ctxt: nova auth RequestContext
        :param instance: Instance object that was resized/cold migrated
        """
        LOG.debug('Deleting port bindings for source host.',
                  instance=instance)
        try:
            self.network_api.cleanup_instance_network_on_host(
                ctxt, instance, self.host)
        except exception.PortBindingDeletionFailed as e:
            # Do not let this stop us from cleaning up since the guest
            # is already gone.
            LOG.error('Failed to delete port bindings from source host. '
                      'Error: %s', str(e), instance=instance)

    def _delete_volume_attachments(self, ctxt, bdms):
        """Deletes volume attachment records for the given bdms.

        This method will log but not re-raise any exceptions if the volume
        attachment delete fails.

        :param ctxt: nova auth request context used to make
            DELETE /attachments/{attachment_id} requests to cinder.
        :param bdms: objects.BlockDeviceMappingList representing volume
            attachments to delete based on BlockDeviceMapping.attachment_id.
        """
        for bdm in bdms:
            if bdm.attachment_id:
                try:
                    self.volume_api.attachment_delete(ctxt, bdm.attachment_id)
                except Exception as e:
                    LOG.error('Failed to delete volume attachment with ID %s. '
                              'Error: %s', bdm.attachment_id, str(e),
                              instance_uuid=bdm.instance_uuid)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def revert_snapshot_based_resize_at_dest(self, ctxt, instance, migration):
        """Reverts a snapshot-based resize at the destination host.

        Cleans the guest from the destination compute service host hypervisor
        and related resources (ports, volumes) and frees resource usage from
        the compute service on that host.

        :param ctxt: nova auth request context targeted at the target cell
        :param instance: Instance object whose vm_state is "resized" and
            task_state is "resize_reverting".
        :param migration: Migration object whose status is "reverting".
        """
        # A resize revert is essentially a resize back to the old size, so we
        # need to send a usage event here.
        compute_utils.notify_usage_exists(
            self.notifier, ctxt, instance, self.host, current_period=True)

        @utils.synchronized(instance.uuid)
        def do_revert():
            LOG.info('Reverting resize on destination host.',
                     instance=instance)
            with self._error_out_instance_on_exception(ctxt, instance):
                self._revert_snapshot_based_resize_at_dest(
                    ctxt, instance, migration)
        do_revert()

        # Broadcast to all schedulers that the instance is no longer on
        # this host and clear any waiting callback events. This is best effort
        # so if anything fails just log it.
        try:
            self._delete_scheduler_instance_info(ctxt, instance.uuid)
            self.instance_events.clear_events_for_instance(instance)
        except Exception as e:
            LOG.warning('revert_snapshot_based_resize_at_dest failed during '
                        'post-processing. Error: %s', e, instance=instance)

    def _revert_snapshot_based_resize_at_dest(
            self, ctxt, instance, migration):
        """Private version of revert_snapshot_based_resize_at_dest.

        This allows the main method to be decorated with error handlers.

        :param ctxt: nova auth request context targeted at the target cell
        :param instance: Instance object whose vm_state is "resized" and
            task_state is "resize_reverting".
        :param migration: Migration object whose status is "reverting".
        """
        # Cleanup the guest from the hypervisor including local disks.
        network_info = self.network_api.get_instance_nw_info(ctxt, instance)
        bdms = instance.get_bdms()
        block_device_info = self._get_instance_block_device_info(
            ctxt, instance, bdms=bdms)
        LOG.debug('Destroying guest from destination hypervisor including '
                  'disks.', instance=instance)
        self.driver.destroy(
            ctxt, instance, network_info, block_device_info=block_device_info)

        # Activate source host port bindings. We need to do this before
        # deleting the (active) dest host port bindings in
        # setup_networks_on_host otherwise the ports will be unbound and
        # finish on the source will fail.
        # migrate_instance_start uses migration.dest_compute for the port
        # binding host and since we want to activate the source host port
        # bindings, we need to temporarily mutate the migration object.
        with utils.temporary_mutation(
                migration, dest_compute=migration.source_compute):
            LOG.debug('Activating port bindings for source host %s.',
                      migration.source_compute, instance=instance)
            # TODO(mriedem): https://review.opendev.org/#/c/594139/ would allow
            # us to remove this and make setup_networks_on_host do it.
            # TODO(mriedem): Should we try/except/log any errors but continue?
            self.network_api.migrate_instance_start(
                ctxt, instance, migration)

        # Delete port bindings for the target host.
        LOG.debug('Deleting port bindings for target host %s.',
                  self.host, instance=instance)
        try:
            # Note that deleting the destination host port bindings does
            # not automatically activate the source host port bindings.
            self.network_api.cleanup_instance_network_on_host(
                ctxt, instance, self.host)
        except exception.PortBindingDeletionFailed as e:
            # Do not let this stop us from cleaning up since the guest
            # is already gone.
            LOG.error('Failed to delete port bindings from target host. '
                      'Error: %s', str(e), instance=instance)

        # Delete any volume attachments remaining for this target host.
        LOG.debug('Deleting volume attachments for target host.',
                  instance=instance)
        self._delete_volume_attachments(ctxt, bdms)

        # Free up the new_flavor usage from the resource tracker for this host.
        self.rt.drop_move_claim_at_dest(ctxt, instance, migration)

    def _revert_instance_flavor_host_node(self, instance, migration):
        """Revert host, node and flavor fields after a resize-revert."""
        self._set_instance_info(instance, instance.old_flavor)
        instance.host = migration.source_compute
        instance.node = migration.source_node
        instance.save(expected_task_state=[task_states.RESIZE_REVERTING])

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def finish_revert_snapshot_based_resize_at_source(
            self, ctxt, instance, migration):
        """Reverts a snapshot-based resize at the source host.

        Spawn the guest and re-connect volumes/VIFs on the source host and
        revert the instance to use the old_flavor for resource usage reporting.

        Updates allocations in the placement service to move the source node
        allocations, held by the migration record, to the instance and drop
        the allocations held by the instance on the destination node.

        :param ctxt: nova auth request context targeted at the target cell
        :param instance: Instance object whose vm_state is "resized" and
            task_state is "resize_reverting".
        :param migration: Migration object whose status is "reverting".
        """

        @utils.synchronized(instance.uuid)
        def do_revert():
            LOG.info('Reverting resize on source host.', instance=instance)
            with self._error_out_instance_on_exception(ctxt, instance):
                self._finish_revert_snapshot_based_resize_at_source(
                    ctxt, instance, migration)

        try:
            do_revert()
        finally:
            self._delete_stashed_flavor_info(instance)

        # Broadcast to all schedulers that the instance is on this host.
        # This is best effort so if anything fails just log it.
        try:
            self._update_scheduler_instance_info(ctxt, instance)
        except Exception as e:
            LOG.warning('finish_revert_snapshot_based_resize_at_source failed '
                        'during post-processing. Error: %s', e,
                        instance=instance)

    def _finish_revert_snapshot_based_resize_at_source(
            self, ctxt, instance, migration):
        """Private version of finish_revert_snapshot_based_resize_at_source.

        This allows the main method to be decorated with error handlers.

        :param ctxt: nova auth request context targeted at the source cell
        :param instance: Instance object whose vm_state is "resized" and
            task_state is "resize_reverting".
        :param migration: Migration object whose status is "reverting".
        """
        # Get stashed old_vm_state information to determine if guest should
        # be powered on after spawn; we default to ACTIVE for backwards
        # compatibility if old_vm_state is not set
        old_vm_state = instance.system_metadata.get(
            'old_vm_state', vm_states.ACTIVE)

        # Revert the flavor and host/node fields to their previous values
        self._revert_instance_flavor_host_node(instance, migration)

        # Move the allocations against the source compute node resource
        # provider, held by the migration, to the instance which will drop
        # the destination compute node resource provider allocations held by
        # the instance. This puts the allocations against the source node
        # back to the old_flavor and owned by the instance.
        try:
            self._revert_allocation(ctxt, instance, migration)
        except exception.AllocationMoveFailed:
            # Log the error but do not re-raise because we want to continue to
            # process ports and volumes below.
            LOG.error('Reverting allocation in placement for migration '
                      '%(migration_uuid)s failed. You may need to manually '
                      'remove the allocations for the migration consumer '
                      'against the source node resource provider '
                      '%(source_provider)s and the allocations for the '
                      'instance consumer against the destination node '
                      'resource provider %(dest_provider)s and then run the '
                      '"nova-manage placement heal_allocations" command.',
                      {'instance_uuid': instance.uuid,
                       'migration_uuid': migration.uuid,
                       'source_provider': migration.source_node,
                       'dest_provider': migration.dest_node},
                      instance=instance)

        bdms = instance.get_bdms()
        # prep_snapshot_based_resize_at_source created empty volume attachments
        # that we need to update here to get the connection_info before calling
        # driver.finish_revert_migration which will connect the volumes to this
        # host.
        LOG.debug('Updating volume attachments for target host %s.',
                  self.host, instance=instance)
        # TODO(mriedem): We should probably make _update_volume_attachments
        # (optionally) graceful to errors so we (1) try to process all
        # attachments and (2) continue to process networking below.
        self._update_volume_attachments(ctxt, instance, bdms)

        LOG.debug('Updating port bindings for source host %s.',
                  self.host, instance=instance)
        # TODO(mriedem): Calculate provider mappings when we support
        # cross-cell resize/migrate with ports having resource requests.
        # NOTE(hanrong): we need to change migration.dest_compute to
        # source host temporarily.
        # "network_api.migrate_instance_finish" will setup the network
        # for the instance on the destination host. For revert resize,
        # the instance will back to the source host, the setup of the
        # network for instance should be on the source host. So set
        # the migration.dest_compute to source host at here.
        with utils.temporary_mutation(
            migration, dest_compute=migration.source_compute
        ):
            self.network_api.migrate_instance_finish(
                ctxt, instance, migration, provider_mappings=None)
        network_info = self.network_api.get_instance_nw_info(ctxt, instance)

        # Remember that prep_snapshot_based_resize_at_source destroyed the
        # guest but left the disks intact so we cannot call spawn() here but
        # finish_revert_migration should do the job.
        block_device_info = self._get_instance_block_device_info(
            ctxt, instance, bdms=bdms)
        power_on = old_vm_state == vm_states.ACTIVE
        driver_error = None
        try:
            self.driver.finish_revert_migration(
                ctxt, instance, network_info, migration,
                block_device_info=block_device_info, power_on=power_on)
        except Exception as e:
            driver_error = e
            # Leave a hint about hard rebooting the guest and reraise so the
            # instance is put into ERROR state.
            with excutils.save_and_reraise_exception(logger=LOG):
                LOG.error('An error occurred during finish_revert_migration. '
                          'The instance may need to be hard rebooted. Error: '
                          '%s', driver_error, instance=instance)
        else:
            # Perform final cleanup of the instance in the database.
            instance.drop_migration_context()
            # If the original vm_state was STOPPED, set it back to STOPPED.
            vm_state = vm_states.ACTIVE if power_on else vm_states.STOPPED
            self._update_instance_after_spawn(instance, vm_state=vm_state)
            instance.save(expected_task_state=[task_states.RESIZE_REVERTING])
        finally:
            # Complete any volume attachments so the volumes are in-use. We
            # do this regardless of finish_revert_migration failing because
            # the instance is back on this host now and we do not want to leave
            # the volumes in a pending state in case the instance is hard
            # rebooted.
            LOG.debug('Completing volume attachments for instance on source '
                      'host.', instance=instance)
            with excutils.save_and_reraise_exception(
                    reraise=driver_error is not None, logger=LOG):
                self._complete_volume_attachments(ctxt, bdms)

        migration.status = 'reverted'
        migration.save()

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def revert_resize(self, context, instance, migration, request_spec):
        """Destroys the new instance on the destination machine.

        Reverts the model changes, and powers on the old instance on the
        source machine.

        """
        # NOTE(comstud): A revert_resize is essentially a resize back to
        # the old size, so we need to send a usage event here.
        compute_utils.notify_usage_exists(self.notifier, context, instance,
                                          self.host, current_period=True)

        with self._error_out_instance_on_exception(context, instance):
            # NOTE(tr3buchet): tear down networks on destination host
            self.network_api.setup_networks_on_host(context, instance,
                                                    teardown=True)

            self.network_api.migrate_instance_start(context,
                                                    instance,
                                                    migration)

            network_info = self.network_api.get_instance_nw_info(context,
                                                                 instance)
            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                    context, instance.uuid)
            block_device_info = self._get_instance_block_device_info(
                                context, instance, bdms=bdms)

            destroy_disks = not self._is_instance_storage_shared(
                context, instance, host=migration.source_compute)
            self.driver.destroy(context, instance, network_info,
                                block_device_info, destroy_disks)

            self._terminate_volume_connections(context, instance, bdms)

            # Free up the new_flavor usage from the resource tracker for this
            # host.
            self.rt.drop_move_claim_at_dest(context, instance, migration)

            # RPC cast back to the source host to finish the revert there.
            self.compute_rpcapi.finish_revert_resize(context, instance,
                    migration, migration.source_compute, request_spec)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def finish_revert_resize(self, context, instance, migration, request_spec):
        """Finishes the second half of reverting a resize on the source host.

        Bring the original source instance state back (active/shutoff) and
        revert the resized attributes in the database.

        """
        try:
            self._finish_revert_resize(
                context, instance, migration, request_spec)
        finally:
            self._delete_stashed_flavor_info(instance)

    def _finish_revert_resize(
        self, context, instance, migration, request_spec=None,
    ):
        """Inner version of finish_revert_resize."""
        with self._error_out_instance_on_exception(context, instance):
            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                context, instance.uuid)
            self._notify_about_instance_usage(
                    context, instance, "resize.revert.start")
            compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.RESIZE_REVERT,
                    phase=fields.NotificationPhase.START, bdms=bdms)

            # Get stashed old_vm_state information to determine if guest should
            # be powered on after spawn; we default to ACTIVE for backwards
            # compatibility if old_vm_state is not set
            old_vm_state = instance.system_metadata.get(
                'old_vm_state', vm_states.ACTIVE)

            # Revert the flavor and host/node fields to their previous values
            self._revert_instance_flavor_host_node(instance, migration)

            try:
                source_allocations = self._revert_allocation(
                    context, instance, migration)
            except exception.AllocationMoveFailed:
                LOG.error('Reverting allocation in placement for migration '
                          '%(migration_uuid)s failed. The instance '
                          '%(instance_uuid)s will be put into ERROR state but '
                          'the allocation held by the migration is leaked.',
                          {'instance_uuid': instance.uuid,
                           'migration_uuid': migration.uuid})
                raise

            provider_mappings = self._fill_provider_mapping_based_on_allocs(
                context, source_allocations, request_spec)

            self.network_api.setup_networks_on_host(context, instance,
                                                    migration.source_compute)
            # NOTE(hanrong): we need to change migration.dest_compute to
            # source host temporarily. "network_api.migrate_instance_finish"
            # will setup the network for the instance on the destination host.
            # For revert resize, the instance will back to the source host, the
            # setup of the network for instance should be on the source host.
            # So set the migration.dest_compute to source host at here.
            with utils.temporary_mutation(
                    migration, dest_compute=migration.source_compute):
                self.network_api.migrate_instance_finish(context,
                                                         instance,
                                                         migration,
                                                         provider_mappings)
            network_info = self.network_api.get_instance_nw_info(context,
                                                                 instance)

            # revert_resize deleted any volume attachments for the instance
            # and created new ones to be used on this host, but we
            # have to update those attachments with the host connector so the
            # BDM.connection_info will get set in the call to
            # _get_instance_block_device_info below with refresh_conn_info=True
            # and then the volumes can be re-connected via the driver on this
            # host.
            self._update_volume_attachments(context, instance, bdms)

            block_device_info = self._get_instance_block_device_info(
                    context, instance, refresh_conn_info=True, bdms=bdms)

            power_on = old_vm_state != vm_states.STOPPED
            self.driver.finish_revert_migration(
                context, instance, network_info, migration, block_device_info,
                power_on)

            instance.drop_migration_context()
            instance.launched_at = timeutils.utcnow()
            instance.save(expected_task_state=task_states.RESIZE_REVERTING)

            # Complete any volume attachments so the volumes are in-use.
            self._complete_volume_attachments(context, bdms)

            # if the original vm state was STOPPED, set it back to STOPPED
            LOG.info("Updating instance to original state: '%s'",
                     old_vm_state, instance=instance)
            if power_on:
                instance.vm_state = vm_states.ACTIVE
                instance.task_state = None
                instance.save()
            else:
                instance.task_state = task_states.POWERING_OFF
                instance.save()
                self.stop_instance(context, instance=instance,
                                   clean_shutdown=True)

            self._notify_about_instance_usage(
                    context, instance, "resize.revert.end")
            compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.RESIZE_REVERT,
                    phase=fields.NotificationPhase.END, bdms=bdms)

    def _fill_provider_mapping_based_on_allocs(
            self, context, allocations, request_spec):
        """Fills and returns the request group - resource provider mapping
        based on the allocation passed in.

        :param context: The security context
        :param allocation: allocation dict keyed by RP UUID.
        :param request_spec: The RequestSpec object associated with the
            operation
        :returns: None if the request_spec is None. Otherwise a mapping
            between RequestGroup requester_id, currently Neutron port_id,
            and a list of resource provider UUIDs providing resource for
            that RequestGroup.
        """
        if request_spec:
            # NOTE(gibi): We need to re-calculate the resource provider -
            # port mapping as we have to have the neutron ports allocate
            # from the source compute after revert.
            scheduler_utils.fill_provider_mapping_based_on_allocation(
                context, self.reportclient, request_spec, allocations)
            provider_mappings = self._get_request_group_mapping(
                request_spec)
        else:
            # TODO(sbauza): Remove this conditional once we only support RPC
            # API 6.0
            # NOTE(gibi): The compute RPC is pinned to be older than 5.2
            # and therefore request_spec is not sent. We cannot calculate
            # the provider mappings. If the instance has ports with
            # resource request then the port update will fail in
            # _update_port_binding_for_instance() called via
            # migrate_instance_finish() in finish_revert_resize.
            provider_mappings = None
        return provider_mappings

    def _revert_allocation(self, context, instance, migration):
        """Revert an allocation that is held by migration to our instance."""

        # Fetch the original allocation that the instance had on the source
        # node, which are now held by the migration
        orig_alloc = self.reportclient.get_allocations_for_consumer(
            context, migration.uuid)
        if not orig_alloc:
            LOG.error('Did not find resource allocations for migration '
                      '%s on source node %s. Unable to revert source node '
                      'allocations back to the instance.',
                      migration.uuid, migration.source_node, instance=instance)
            return False

        LOG.info('Swapping old allocation on %(rp_uuids)s held by migration '
                 '%(mig)s for instance',
                 {'rp_uuids': orig_alloc.keys(), 'mig': migration.uuid},
                 instance=instance)
        # FIXME(gibi): This method is flawed in that it does not handle
        # allocations against sharing providers in any special way. This leads
        # to duplicate allocations against the sharing provider during
        # migration.
        # TODO(cdent): Should we be doing anything with return values here?
        self.reportclient.move_allocations(context, migration.uuid,
                                           instance.uuid)
        return orig_alloc

    def _prep_resize(
        self, context, image, instance, flavor, filter_properties, node,
        migration, request_spec, clean_shutdown=True,
    ):

        if not filter_properties:
            filter_properties = {}

        if not instance.host:
            self._set_instance_obj_error_state(instance)
            msg = _('Instance has no source host')
            raise exception.MigrationError(reason=msg)

        same_host = instance.host == self.host
        # if the flavor IDs match, it's migrate; otherwise resize
        if same_host and flavor.id == instance['instance_type_id']:
            # check driver whether support migrate to same host
            if not self.driver.capabilities.get(
                    'supports_migrate_to_same_host', False):
                # Raise InstanceFaultRollback so that the
                # _error_out_instance_on_exception context manager in
                # prep_resize will set the instance.vm_state properly.
                raise exception.InstanceFaultRollback(
                    inner_exception=exception.UnableToMigrateToSelf(
                        instance_id=instance.uuid, host=self.host))

        # NOTE(danms): Stash the new flavor to avoid having to
        # look it up in the database later
        instance.new_flavor = flavor
        # NOTE(mriedem): Stash the old vm_state so we can set the
        # resized/reverted instance back to the same state later.
        vm_state = instance.vm_state
        LOG.debug('Stashing vm_state: %s', vm_state, instance=instance)
        instance.system_metadata['old_vm_state'] = vm_state
        instance.save()

        if not isinstance(request_spec, objects.RequestSpec):
            # Prior to compute RPC API 5.1 conductor would pass a legacy dict
            # version of the request spec to compute and since Stein compute
            # could be sending that back to conductor on reschedule, so if we
            # got a dict convert it to an object.
            # TODO(mriedem): We can drop this compat code when we only support
            # compute RPC API >=6.0.
            request_spec = objects.RequestSpec.from_primitives(
                context, request_spec, filter_properties)
            # We don't have to set the new flavor on the request spec because
            # if we got here it was due to a reschedule from the compute and
            # the request spec would already have the new flavor in it from the
            # else block below.

        provider_mapping = self._get_request_group_mapping(request_spec)

        if provider_mapping:
            try:
                compute_utils.\
                    update_pci_request_spec_with_allocated_interface_name(
                        context, self.reportclient,
                        instance.pci_requests.requests, provider_mapping)
            except (exception.AmbiguousResourceProviderForPCIRequest,
                    exception.UnexpectedResourceProviderNameForPCIRequest
                    ) as e:
                raise exception.BuildAbortException(
                    reason=str(e), instance_uuid=instance.uuid)

        limits = filter_properties.get('limits', {})
        allocs = self.reportclient.get_allocations_for_consumer(
            context, instance.uuid)
        with self.rt.resize_claim(
            context, instance, flavor, node, migration, allocs,
            image_meta=image, limits=limits,
        ) as claim:
            LOG.info('Migrating', instance=instance)
            # RPC cast to the source host to start the actual resize/migration.
            self.compute_rpcapi.resize_instance(
                context, instance, claim.migration, image,
                flavor, request_spec, clean_shutdown)

    def _send_prep_resize_notifications(
            self, context, instance, phase, flavor):
        """Send "resize.prep.*" notifications.

        :param context: nova auth request context
        :param instance: The instance being resized
        :param phase: The phase of the action (NotificationPhase enum)
        :param flavor: The (new) flavor for the resize (same as existing
            instance.flavor for a cold migration)
        """
        # Only send notify_usage_exists if it's the "start" phase.
        if phase == fields.NotificationPhase.START:
            compute_utils.notify_usage_exists(
                self.notifier, context, instance, self.host,
                current_period=True)

        # Send extra usage info about the flavor if it's the "end" phase for
        # the legacy unversioned notification.
        extra_usage_info = None
        if phase == fields.NotificationPhase.END:
            extra_usage_info = dict(
                new_instance_type=flavor.name,
                new_instance_type_id=flavor.id)
        self._notify_about_instance_usage(
            context, instance, "resize.prep.%s" % phase,
            extra_usage_info=extra_usage_info)

        # Send the versioned notification.
        compute_utils.notify_about_resize_prep_instance(
            context, instance, self.host, phase, flavor)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def prep_resize(self, context, image, instance, flavor,
                    request_spec, filter_properties, node,
                    clean_shutdown, migration, host_list):
        """Initiates the process of moving a running instance to another host.

        Possibly changes the VCPU, RAM and disk size in the process.

        This is initiated from conductor and runs on the destination host.

        The main purpose of this method is performing some checks on the
        destination host and making a claim for resources. If the claim fails
        then a reschedule to another host may be attempted which involves
        calling back to conductor to start the process over again.
        """
        if node is None:
            node = self._get_nodename(instance, refresh=True)

        # Pass instance_state=instance.vm_state because we can resize
        # a STOPPED server and we don't want to set it back to ACTIVE
        # in case _prep_resize fails.
        instance_state = instance.vm_state
        with self._error_out_instance_on_exception(
                context, instance, instance_state=instance_state),\
                errors_out_migration_ctxt(migration):

            self._send_prep_resize_notifications(
                context, instance, fields.NotificationPhase.START,
                flavor)
            try:
                scheduler_hints = self._get_scheduler_hints(filter_properties,
                                                            request_spec)
                # Error out if this host cannot accept the new instance due
                # to anti-affinity. At this point the migration is already
                # in-progress, so this is the definitive moment to abort due to
                # the policy violation. Also, exploding here is covered by the
                # cleanup methods in except block.
                try:
                    self._validate_instance_group_policy(context, instance,
                                                         scheduler_hints)
                except exception.RescheduledException as e:
                    raise exception.InstanceFaultRollback(inner_exception=e)

                self._prep_resize(context, image, instance,
                                  flavor, filter_properties,
                                  node, migration, request_spec,
                                  clean_shutdown)
            except exception.BuildAbortException:
                # NOTE(gibi): We failed
                # update_pci_request_spec_with_allocated_interface_name so
                # there is no reason to re-schedule. Just revert the allocation
                # and fail the migration.
                with excutils.save_and_reraise_exception():
                    self._revert_allocation(context, instance, migration)
            except Exception:
                # Since we hit a failure, we're either rescheduling or dead
                # and either way we need to cleanup any allocations created
                # by the scheduler for the destination node.
                self._revert_allocation(context, instance, migration)
                # try to re-schedule the resize elsewhere:
                exc_info = sys.exc_info()
                self._reschedule_resize_or_reraise(context, instance,
                        exc_info, flavor, request_spec,
                        filter_properties, host_list)
            finally:
                self._send_prep_resize_notifications(
                    context, instance, fields.NotificationPhase.END,
                    flavor)

    def _reschedule_resize_or_reraise(self, context, instance, exc_info,
            flavor, request_spec, filter_properties, host_list):
        """Try to re-schedule the resize or re-raise the original error to
        error out the instance.
        """
        if not filter_properties:
            filter_properties = {}

        rescheduled = False
        instance_uuid = instance.uuid

        try:
            retry = filter_properties.get('retry')
            if retry:
                LOG.debug('Rescheduling, attempt %d', retry['num_attempts'],
                          instance_uuid=instance_uuid)

                # reset the task state
                task_state = task_states.RESIZE_PREP
                self._instance_update(context, instance, task_state=task_state)

                if exc_info:
                    # stringify to avoid circular ref problem in json
                    # serialization
                    retry['exc'] = traceback.format_exception_only(
                        exc_info[0], exc_info[1])

                scheduler_hint = {'filter_properties': filter_properties}

                self.compute_task_api.resize_instance(
                    context, instance, scheduler_hint, flavor,
                    request_spec=request_spec, host_list=host_list)

                rescheduled = True
            else:
                # no retry information, do not reschedule.
                LOG.debug('Retry info not present, will not reschedule',
                          instance_uuid=instance_uuid)
                rescheduled = False
        except Exception as error:
            rescheduled = False
            LOG.exception("Error trying to reschedule",
                          instance_uuid=instance_uuid)
            compute_utils.add_instance_fault_from_exc(context,
                    instance, error,
                    exc_info=sys.exc_info())
            self._notify_about_instance_usage(context, instance,
                    'resize.error', fault=error)
            compute_utils.notify_about_instance_action(
                context, instance, self.host,
                action=fields.NotificationAction.RESIZE,
                phase=fields.NotificationPhase.ERROR,
                exception=error,
            )

        if rescheduled:
            self._log_original_error(exc_info, instance_uuid)
            compute_utils.add_instance_fault_from_exc(context,
                    instance, exc_info[1], exc_info=exc_info)
            self._notify_about_instance_usage(context, instance,
                    'resize.error', fault=exc_info[1])
            compute_utils.notify_about_instance_action(
                context, instance, self.host,
                action=fields.NotificationAction.RESIZE,
                phase=fields.NotificationPhase.ERROR,
                exception=exc_info[1],
            )
        else:
            # not re-scheduling
            exc = exc_info[1] or exc_info[0]()
            if exc.__traceback__ is not exc_info[2]:
                raise exc.with_traceback(exc_info[2])
            raise exc

    @messaging.expected_exceptions(exception.MigrationPreCheckError)
    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def prep_snapshot_based_resize_at_dest(
            self, ctxt, instance, flavor, nodename, migration, limits):
        """Performs pre-cross-cell resize resource claim on the dest host.

        This runs on the destination host in a cross-cell resize operation
        before the resize is actually started.

        Performs a resize_claim for resources that are not claimed in placement
        like PCI devices and NUMA topology.

        Note that this is different from same-cell prep_resize in that this:

        * Does not RPC cast to the source compute, that is orchestrated from
          conductor.
        * This does not reschedule on failure, conductor handles that since
          conductor is synchronously RPC calling this method. As such, the
          reverts_task_state decorator is not used on this method.

        :param ctxt: user auth request context
        :param instance: the instance being resized
        :param flavor: the flavor being resized to (unchanged for cold migrate)
        :param nodename: Name of the target compute node
        :param migration: nova.objects.Migration object for the operation
        :param limits: nova.objects.SchedulerLimits object of resource limits
        :returns: nova.objects.MigrationContext; the migration context created
            on the destination host during the resize_claim.
        :raises: nova.exception.MigrationPreCheckError if the pre-check
            validation fails for the given host selection
        """
        LOG.debug('Checking if we can cross-cell migrate instance to this '
                  'host (%s).', self.host, instance=instance)
        self._send_prep_resize_notifications(
            ctxt, instance, fields.NotificationPhase.START, flavor)
        # TODO(mriedem): update_pci_request_spec_with_allocated_interface_name
        # should be called here if the request spec has request group mappings,
        # e.g. for things like QoS ports with resource requests. Do it outside
        # the try/except so if it raises BuildAbortException we do not attempt
        # to reschedule.
        try:
            # Get the allocations within the try/except block in case we get
            # an error so MigrationPreCheckError is raised up.
            allocations = self.reportclient.get_allocs_for_consumer(
                ctxt, instance.uuid)['allocations']
            # Claim resources on this target host using the new flavor which
            # will create the MigrationContext object. Note that in the future
            # if we want to do other validation here we should do it within
            # the MoveClaim context so we can drop the claim if anything fails.
            self.rt.resize_claim(
                ctxt, instance, flavor, nodename, migration, allocations,
                image_meta=instance.image_meta, limits=limits)
        except Exception as ex:
            err = str(ex)
            LOG.warning(
                'Cross-cell resize pre-checks failed for this host (%s). '
                'Cleaning up. Failure: %s', self.host, err,
                instance=instance, exc_info=True)
            raise exception.MigrationPreCheckError(
                reason=(_("Pre-checks failed on host '%(host)s'. "
                          "Error: %(error)s") %
                        {'host': self.host, 'error': err}))
        finally:
            self._send_prep_resize_notifications(
                ctxt, instance, fields.NotificationPhase.END, flavor)

        # ResourceTracker.resize_claim() sets instance.migration_context.
        return instance.migration_context

    @messaging.expected_exceptions(exception.InstancePowerOffFailure)
    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def prep_snapshot_based_resize_at_source(
            self, ctxt, instance, migration, snapshot_id=None):
        """Prepares the instance at the source host for cross-cell resize

        Performs actions like powering off the guest, upload snapshot data if
        the instance is not volume-backed, disconnecting volumes, unplugging
        VIFs and activating the destination host port bindings.

        :param ctxt: user auth request context targeted at source cell
        :param instance: nova.objects.Instance; the instance being resized.
            The expected instance.task_state is "resize_migrating" when calling
            this method, and the expected task_state upon successful completion
            is "resize_migrated".
        :param migration: nova.objects.Migration object for the operation.
            The expected migration.status is "pre-migrating" when calling this
            method and the expected status upon successful completion is
            "post-migrating".
        :param snapshot_id: ID of the image snapshot to upload if not a
            volume-backed instance
        :raises: nova.exception.InstancePowerOffFailure if stopping the
            instance fails
        """
        LOG.info('Preparing for snapshot based resize on source host %s.',
                 self.host, instance=instance)
        # Note that if anything fails here, the migration-based allocations
        # created in conductor should be reverted by conductor as well,
        # see MigrationTask.rollback.
        self._prep_snapshot_based_resize_at_source(
            ctxt, instance, migration, snapshot_id=snapshot_id)

    @delete_image_on_error
    def _snapshot_for_resize(self, ctxt, image_id, instance):
        """Uploads snapshot for the instance during a snapshot-based resize

        If the snapshot operation fails the image will be deleted.

        :param ctxt: the nova auth request context for the resize operation
        :param image_id: the snapshot image ID
        :param instance: the instance to snapshot/resize
        """
        LOG.debug('Uploading snapshot data for image %s', image_id,
                  instance=instance)
        # Note that we do not track the snapshot phase task states
        # during resize since we do not want to reflect those into the
        # actual instance.task_state.
        update_task_state = lambda *args, **kwargs: None
        with timeutils.StopWatch() as timer:
            self.driver.snapshot(ctxt, instance, image_id, update_task_state)
            LOG.debug('Took %0.2f seconds to snapshot the instance on '
                      'the hypervisor.', timer.elapsed(), instance=instance)

    def _prep_snapshot_based_resize_at_source(
            self, ctxt, instance, migration, snapshot_id=None):
        """Private method for prep_snapshot_based_resize_at_source so calling
        code can handle errors and perform rollbacks as necessary.
        """
        # Fetch and update the instance.info_cache.
        network_info = self.network_api.get_instance_nw_info(ctxt, instance)
        # Get the BDMs attached to this instance on this source host.
        bdms = instance.get_bdms()
        # Send the resize.start notification.
        self._send_resize_instance_notifications(
            ctxt, instance, bdms, network_info, fields.NotificationPhase.START)
        # Update the migration status from "pre-migrating" to "migrating".
        migration.status = 'migrating'
        migration.save()

        # Since the instance is going to be left on the source host during the
        # resize, we need to power it off so we do not have the instance
        # potentially running in two places.
        LOG.debug('Stopping instance', instance=instance)
        try:
            self._power_off_instance(instance)
        except Exception as e:
            LOG.exception('Failed to power off instance.', instance=instance)
            raise exception.InstancePowerOffFailure(reason=str(e))
        instance.power_state = self._get_power_state(instance)

        # If a snapshot image ID was provided, we need to snapshot the guest
        # disk image and upload it to the image service.
        if snapshot_id:
            self._snapshot_for_resize(ctxt, snapshot_id, instance)

        block_device_info = self._get_instance_block_device_info(
            ctxt, instance, bdms=bdms)

        # If something fails at this point the instance must go to ERROR
        # status for operator intervention or to reboot/rebuild the instance.
        with self._error_out_instance_on_exception(
                ctxt, instance, instance_state=vm_states.ERROR):

            # Destroy the guest on the source host which will disconnect
            # volumes and unplug VIFs. Note that we DO NOT destroy disks since
            # we want to leave those on the source host in case of a later
            # failure and disks are needed to recover the guest or in case the
            # resize is reverted.
            LOG.debug('Destroying guest on source host but retaining disks.',
                      instance=instance)
            self.driver.destroy(
                ctxt, instance, network_info,
                block_device_info=block_device_info, destroy_disks=False)

            # At this point the volumes are disconnected from this source host.
            # Delete the old volume attachment records and create new empty
            # ones which will be used later if the resize is reverted.
            LOG.debug('Deleting volume attachments for the source host.',
                      instance=instance)
            self._terminate_volume_connections(ctxt, instance, bdms)

            # At this point the VIFs are unplugged from this source host.
            # Activate the dest host port bindings created by conductor.
            self.network_api.migrate_instance_start(ctxt, instance, migration)

            # Update the migration status from "migrating" to "post-migrating".
            migration.status = 'post-migrating'
            migration.save()

            # At this point, the traditional resize_instance would update the
            # instance host/node values to point at the dest host/node because
            # that is where the disk is transferred during resize_instance, but
            # with cross-cell resize the instance is not yet at the dest host
            # so we do not make that update here.
            instance.task_state = task_states.RESIZE_MIGRATED
            instance.save(expected_task_state=task_states.RESIZE_MIGRATING)

        self._send_resize_instance_notifications(
            ctxt, instance, bdms, network_info,
            fields.NotificationPhase.END)
        self.instance_events.clear_events_for_instance(instance)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def resize_instance(self, context, instance, image,
                        migration, flavor, clean_shutdown,
                        request_spec):
        """Starts the migration of a running instance to another host.

        This is initiated from the destination host's ``prep_resize`` routine
        and runs on the source host.
        """
        try:
            self._resize_instance(context, instance, image, migration,
                                  flavor, clean_shutdown, request_spec)
        except Exception:
            with excutils.save_and_reraise_exception():
                self._revert_allocation(context, instance, migration)

    def _resize_instance(
        self, context, instance, image, migration, flavor,
        clean_shutdown, request_spec,
    ):
        # Pass instance_state=instance.vm_state because we can resize
        # a STOPPED server and we don't want to set it back to ACTIVE
        # in case migrate_disk_and_power_off raises InstanceFaultRollback.
        instance_state = instance.vm_state
        with self._error_out_instance_on_exception(
                context, instance, instance_state=instance_state), \
             errors_out_migration_ctxt(migration):
            network_info = self.network_api.get_instance_nw_info(context,
                                                                 instance)

            migration.status = 'migrating'
            migration.save()

            instance.task_state = task_states.RESIZE_MIGRATING
            instance.save(expected_task_state=task_states.RESIZE_PREP)

            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                    context, instance.uuid)
            self._send_resize_instance_notifications(
                context, instance, bdms, network_info,
                fields.NotificationPhase.START)

            block_device_info = self._get_instance_block_device_info(
                                context, instance, bdms=bdms)

            timeout, retry_interval = self._get_power_off_values(
                instance, clean_shutdown)
            disk_info = self.driver.migrate_disk_and_power_off(
                context, instance, migration.dest_host,
                flavor, network_info,
                block_device_info,
                timeout, retry_interval)

            self._terminate_volume_connections(context, instance, bdms)

            self.network_api.migrate_instance_start(context,
                                                    instance,
                                                    migration)

            migration.status = 'post-migrating'
            migration.save()

            instance.host = migration.dest_compute
            instance.node = migration.dest_node
            # NOTE(gibi): as the instance now tracked on the destination we
            # have to make sure that the source compute resource track can
            # track this instance as a migration. For that the resource tracker
            # needs to see the old_flavor set on the instance. The old_flavor
            # setting used to be done on the destination host in finish_resize
            # but that is racy with a source host update_available_resource
            # periodic run
            instance.old_flavor = instance.flavor
            instance.task_state = task_states.RESIZE_MIGRATED
            instance.save(expected_task_state=task_states.RESIZE_MIGRATING)

            # RPC cast to the destination host to finish the resize/migration.
            self.compute_rpcapi.finish_resize(context, instance,
                migration, image, disk_info, migration.dest_compute,
                request_spec)

        self._send_resize_instance_notifications(
            context, instance, bdms, network_info,
            fields.NotificationPhase.END)
        self.instance_events.clear_events_for_instance(instance)

    def _send_resize_instance_notifications(
            self, context, instance, bdms, network_info, phase):
        """Send "resize.(start|end)" notifications.

        :param context: nova auth request context
        :param instance: The instance being resized
        :param bdms: BlockDeviceMappingList for the BDMs associated with the
            instance
        :param network_info: NetworkInfo for the instance info cache of ports
        :param phase: The phase of the action (NotificationPhase enum, either
            ``start`` or ``end``)
        """
        action = fields.NotificationAction.RESIZE
        # Send the legacy unversioned notification.
        self._notify_about_instance_usage(
            context, instance, "%s.%s" % (action, phase),
            network_info=network_info)
        # Send the versioned notification.
        compute_utils.notify_about_instance_action(
            context, instance, self.host, action=action, phase=phase,
            bdms=bdms)

    def _terminate_volume_connections(self, context, instance, bdms):
        connector = None
        for bdm in bdms:
            if bdm.is_volume:
                if bdm.attachment_id:
                    # NOTE(jdg): So here's the thing, the idea behind the new
                    # attach API's was to have a new code fork/path that we
                    # followed, we're not going to do that so we have to do
                    # some extra work in here to make it *behave* just like the
                    # old code. Cinder doesn't allow disconnect/reconnect (you
                    # just delete the attachment and get a new one)
                    # attachments in the new attach code so we have to do
                    # a delete and create without a connector (reserve),
                    # in other words, beware
                    attachment_id = self.volume_api.attachment_create(
                        context, bdm.volume_id, instance.uuid)['id']
                    self.volume_api.attachment_delete(context,
                                                      bdm.attachment_id)
                    bdm.attachment_id = attachment_id
                    bdm.save()

                else:
                    if connector is None:
                        connector = self.driver.get_volume_connector(instance)
                    self.volume_api.terminate_connection(context,
                                                         bdm.volume_id,
                                                         connector)

    @staticmethod
    def _set_instance_info(instance, flavor):
        instance.instance_type_id = flavor.id
        instance.memory_mb = flavor.memory_mb
        instance.vcpus = flavor.vcpus
        instance.root_gb = flavor.root_gb
        instance.ephemeral_gb = flavor.ephemeral_gb
        instance.flavor = flavor

    def _update_volume_attachments(self, context, instance, bdms):
        """Updates volume attachments using the virt driver host connector.

        :param context: nova.context.RequestContext - user request context
        :param instance: nova.objects.Instance
        :param bdms: nova.objects.BlockDeviceMappingList - the list of block
                     device mappings for the given instance
        """
        if bdms:
            connector = None
            for bdm in bdms:
                if bdm.is_volume and bdm.attachment_id:
                    if connector is None:
                        connector = self.driver.get_volume_connector(instance)
                    self.volume_api.attachment_update(
                        context, bdm.attachment_id, connector, bdm.device_name)

    def _complete_volume_attachments(self, context, bdms):
        """Completes volume attachments for the instance

        :param context: nova.context.RequestContext - user request context
        :param bdms: nova.objects.BlockDeviceMappingList - the list of block
                     device mappings for the given instance
        """
        if bdms:
            for bdm in bdms:
                if bdm.is_volume and bdm.attachment_id:
                    self.volume_api.attachment_complete(
                        context, bdm.attachment_id)

    def _finish_resize(self, context, instance, migration, disk_info,
                       image_meta, bdms, request_spec):
        resize_instance = False  # indicates disks have been resized
        old_instance_type_id = migration.old_instance_type_id
        new_instance_type_id = migration.new_instance_type_id
        old_flavor = instance.flavor  # the current flavor is now old
        # NOTE(mriedem): Get the old_vm_state so we know if we should
        # power on the instance. If old_vm_state is not set we need to default
        # to ACTIVE for backwards compatibility
        old_vm_state = instance.system_metadata.get('old_vm_state',
                                                    vm_states.ACTIVE)
        # NOTE(gibi): this is already set by the resize_instance on the source
        # node before calling finish_resize on destination but during upgrade
        # it can be that the source node is not having the fix for bug 1944759
        # yet. This assignment can be removed in Z release.
        instance.old_flavor = old_flavor

        if old_instance_type_id != new_instance_type_id:
            new_flavor = instance.new_flavor  # this is set in _prep_resize
            # Set the flavor-related fields on the instance object including
            # making instance.flavor = new_flavor.
            self._set_instance_info(instance, new_flavor)
            for key in ('root_gb', 'swap', 'ephemeral_gb'):
                if old_flavor[key] != new_flavor[key]:
                    resize_instance = True
                    break
        instance.apply_migration_context()

        # NOTE(tr3buchet): setup networks on destination host
        self.network_api.setup_networks_on_host(context, instance,
                                                migration.dest_compute)
        provider_mappings = self._get_request_group_mapping(request_spec)

        # For neutron, migrate_instance_finish updates port bindings for this
        # host including any PCI devices claimed for SR-IOV ports.
        self.network_api.migrate_instance_finish(
            context, instance, migration, provider_mappings)

        network_info = self.network_api.get_instance_nw_info(context, instance)

        instance.task_state = task_states.RESIZE_FINISH
        instance.save(expected_task_state=task_states.RESIZE_MIGRATED)

        self._send_finish_resize_notifications(
            context, instance, bdms, network_info,
            fields.NotificationPhase.START)

        # We need to update any volume attachments using the destination
        # host connector so that we can update the BDM.connection_info
        # before calling driver.finish_migration otherwise the driver
        # won't know how to connect the volumes to this host.
        # Note that _get_instance_block_device_info with
        # refresh_conn_info=True will update the BDM.connection_info value
        # in the database so we must do this before calling that method.
        self._update_volume_attachments(context, instance, bdms)

        block_device_info = self._get_instance_block_device_info(
            context, instance, refresh_conn_info=True, bdms=bdms)

        # NOTE(mriedem): If the original vm_state was STOPPED, we don't
        # automatically power on the instance after it's migrated
        power_on = old_vm_state != vm_states.STOPPED

        # NOTE(sbauza): During a migration, the original allocation is against
        # the migration UUID while the target allocation (for the destination
        # node) is related to the instance UUID, so here we need to pass the
        # new ones.
        allocations = self.reportclient.get_allocs_for_consumer(
            context, instance.uuid)['allocations']

        try:
            self.driver.finish_migration(context, migration, instance,
                                         disk_info,
                                         network_info,
                                         image_meta, resize_instance,
                                         allocations,
                                         block_device_info, power_on)
        except Exception:
            # Note that we do not rollback port bindings to the source host
            # because resize_instance (on the source host) updated the
            # instance.host to point to *this* host (the destination host)
            # so the port bindings pointing at this host are correct even
            # though we failed to create the guest.
            with excutils.save_and_reraise_exception():
                # If we failed to create the guest on this host, reset the
                # instance flavor-related fields to the old flavor. An
                # error handler like reverts_task_state will save the changes.
                if old_instance_type_id != new_instance_type_id:
                    self._set_instance_info(instance, old_flavor)

        # Now complete any volume attachments that were previously updated.
        self._complete_volume_attachments(context, bdms)

        migration.status = 'finished'
        migration.save()

        instance.vm_state = vm_states.RESIZED
        instance.task_state = None
        instance.launched_at = timeutils.utcnow()
        instance.save(expected_task_state=task_states.RESIZE_FINISH)

        return network_info

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def finish_resize(self, context, disk_info, image, instance,
                      migration, request_spec):
        """Completes the migration process.

        Sets up the newly transferred disk and turns on the instance at its
        new host machine.

        """
        try:
            self._finish_resize_helper(context, disk_info, image, instance,
                                       migration, request_spec)
        except Exception:
            with excutils.save_and_reraise_exception():
                # At this point, resize_instance (which runs on the source) has
                # already updated the instance host/node values to point to
                # this (the dest) compute, so we need to leave the allocations
                # against the dest node resource provider intact and drop the
                # allocations against the source node resource provider. If the
                # user tries to recover the server by hard rebooting it, it
                # will happen on this host so that's where the allocations
                # should go. Note that this is the same method called from
                # confirm_resize to cleanup the source node allocations held
                # by the migration record.
                LOG.info('Deleting allocations for old flavor on source node '
                         '%s after finish_resize failure. You may be able to '
                         'recover the instance by hard rebooting it.',
                         migration.source_compute, instance=instance)
                self._delete_allocation_after_move(
                    context, instance, migration)

    def _finish_resize_helper(self, context, disk_info, image, instance,
                              migration, request_spec):
        """Completes the migration process.

        The caller must revert the instance's allocations if the migration
        process failed.
        """
        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
            context, instance.uuid)

        with self._error_out_instance_on_exception(context, instance):
            image_meta = objects.ImageMeta.from_dict(image)
            network_info = self._finish_resize(context, instance, migration,
                                               disk_info, image_meta, bdms,
                                               request_spec)

        # TODO(melwitt): We should clean up instance console tokens here. The
        # instance is on a new host and will need to establish a new console
        # connection.
        self._update_scheduler_instance_info(context, instance)
        self._send_finish_resize_notifications(
            context, instance, bdms, network_info,
            fields.NotificationPhase.END)

    def _send_finish_resize_notifications(
            self, context, instance, bdms, network_info, phase):
        """Send notifications for the finish_resize flow.

        :param context: nova auth request context
        :param instance: The instance being resized
        :param bdms: BlockDeviceMappingList for the BDMs associated with the
            instance
        :param network_info: NetworkInfo for the instance info cache of ports
        :param phase: The phase of the action (NotificationPhase enum, either
            ``start`` or ``end``)
        """
        # Send the legacy unversioned notification.
        self._notify_about_instance_usage(
            context, instance, "finish_resize.%s" % phase,
            network_info=network_info)
        # Send the versioned notification.
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.RESIZE_FINISH, phase=phase,
            bdms=bdms)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def finish_snapshot_based_resize_at_dest(
            self, ctxt, instance, migration, snapshot_id):
        """Finishes the snapshot-based resize at the destination compute.

        Sets up block devices and networking on the destination compute and
        spawns the guest.

        :param ctxt: nova auth request context targeted at the target cell DB
        :param instance: The Instance object being resized with the
            ``migration_context`` field set. Upon successful completion of this
            method the vm_state should be "resized", the task_state should be
            None, and migration context, host/node and flavor-related fields
            should be set on the instance.
        :param migration: The Migration object for this resize operation. Upon
            successful completion of this method the migration status should
            be "finished".
        :param snapshot_id: ID of the image snapshot created for a
            non-volume-backed instance, else None.
        """
        LOG.info('Finishing snapshot based resize on destination host %s.',
                 self.host, instance=instance)
        with self._error_out_instance_on_exception(ctxt, instance):
            # Note that if anything fails here, the migration-based allocations
            # created in conductor should be reverted by conductor as well,
            # see MigrationTask.rollback.
            self._finish_snapshot_based_resize_at_dest(
                ctxt, instance, migration, snapshot_id)

    def _finish_snapshot_based_resize_at_dest(
            self, ctxt, instance, migration, snapshot_id):
        """Private variant of finish_snapshot_based_resize_at_dest so the
        caller can handle reverting resource allocations on failure and perform
        other generic error handling.
        """
        # Figure out the image metadata to use when spawning the guest.
        origin_image_ref = instance.image_ref
        if snapshot_id:
            instance.image_ref = snapshot_id
            image_meta = objects.ImageMeta.from_image_ref(
                ctxt, self.image_api, snapshot_id)
        else:
            # Just use what is already on the volume-backed instance.
            image_meta = instance.image_meta

        resize = migration.migration_type == 'resize'
        instance.old_flavor = instance.flavor
        if resize:
            flavor = instance.new_flavor
            # If we are resizing to a new flavor we need to set the
            # flavor-related fields on the instance.
            # NOTE(mriedem): This is likely where storing old/new_flavor on
            # the MigrationContext would make this cleaner.
            self._set_instance_info(instance, flavor)

        instance.apply_migration_context()
        instance.task_state = task_states.RESIZE_FINISH
        instance.save(expected_task_state=task_states.RESIZE_MIGRATED)

        # This seems a bit late to be sending the start notification but
        # it is what traditional resize has always done as well and it does
        # contain the changes to the instance with the new_flavor and
        # task_state.
        bdms = instance.get_bdms()
        network_info = instance.get_network_info()
        self._send_finish_resize_notifications(
            ctxt, instance, bdms, network_info,
            fields.NotificationPhase.START)

        # Setup volumes and networking and spawn the guest in the hypervisor.
        self._finish_snapshot_based_resize_at_dest_spawn(
            ctxt, instance, migration, image_meta, bdms)

        # If we spawned from a temporary snapshot image we can delete that now,
        # similar to how unshelve works.
        if snapshot_id:
            instance.image_ref = origin_image_ref
            compute_utils.delete_image(
                ctxt, instance, self.image_api, snapshot_id)

        migration.status = 'finished'
        migration.save()

        self._update_instance_after_spawn(instance, vm_state=vm_states.RESIZED)
        # Setting the host/node values will make the ResourceTracker continue
        # to track usage for this instance on this host.
        instance.host = migration.dest_compute
        instance.node = migration.dest_node
        instance.save(expected_task_state=task_states.RESIZE_FINISH)

        # Broadcast to all schedulers that the instance is on this host.
        self._update_scheduler_instance_info(ctxt, instance)
        self._send_finish_resize_notifications(
            ctxt, instance, bdms, network_info,
            fields.NotificationPhase.END)

    def _finish_snapshot_based_resize_at_dest_spawn(
            self, ctxt, instance, migration, image_meta, bdms):
        """Sets up volumes and networking and spawns the guest on the dest host

        If the instance was stopped when the resize was initiated the guest
        will be created but remain in a shutdown power state.

        If the spawn fails, port bindings are rolled back to the source host
        and volume connections are terminated for this dest host.

        :param ctxt: nova auth request context
        :param instance: Instance object being migrated
        :param migration: Migration object for the operation
        :param image_meta: ImageMeta object used during driver.spawn
        :param bdms: BlockDeviceMappingList of BDMs for the instance
        """
        # Update the volume attachments using this host's connector.
        # That will update the BlockDeviceMapping.connection_info which
        # will be used to connect the volumes on this host during spawn().
        block_device_info = self._prep_block_device(ctxt, instance, bdms)

        allocations = self.reportclient.get_allocations_for_consumer(
            ctxt, instance.uuid)

        # We do not call self.network_api.setup_networks_on_host here because
        # for neutron that sets up the port migration profile which is only
        # used during live migration with DVR. Yes it is gross knowing what
        # that method does internally. We could change this when bug 1814837
        # is fixed if setup_networks_on_host is made smarter by passing the
        # migration record and the method checks the migration_type.

        # Activate the port bindings for this host.
        # FIXME(mriedem): We're going to have the same issue as bug 1813789
        # here because this will update the port bindings and send the
        # network-vif-plugged event and that means when driver.spawn waits for
        # it we might have already gotten the event and neutron won't send
        # another one so we could timeout.
        # TODO(mriedem): Calculate provider mappings when we support cross-cell
        # resize/migrate with ports having resource requests.
        self.network_api.migrate_instance_finish(
            ctxt, instance, migration, provider_mappings=None)
        network_info = self.network_api.get_instance_nw_info(ctxt, instance)

        # If the original vm_state was STOPPED, we do not automatically
        # power on the instance after it is migrated.
        power_on = instance.system_metadata['old_vm_state'] == vm_states.ACTIVE
        try:
            # NOTE(mriedem): If this instance uses a config drive, it will get
            # rebuilt here which means any personality files will be lost,
            # similar to unshelve. If the instance is not using a config drive
            # and getting metadata from the metadata API service, personality
            # files would be lost regardless of the move operation.
            self.driver.spawn(
                ctxt, instance, image_meta, injected_files=[],
                admin_password=None, allocations=allocations,
                network_info=network_info, block_device_info=block_device_info,
                power_on=power_on)
        except Exception:
            with excutils.save_and_reraise_exception(logger=LOG):
                # Rollback port bindings to the source host.
                try:
                    # This is gross but migrate_instance_start looks at the
                    # migration.dest_compute to determine where to activate the
                    # port bindings and we want the source compute port
                    # bindings to be re-activated. Remember at this point the
                    # instance.host is still pointing at the source compute.
                    # TODO(mriedem): Maybe we should be calling
                    # setup_instance_network_on_host here to deal with pci
                    # devices?
                    with utils.temporary_mutation(
                            migration, dest_compute=migration.source_compute):
                        self.network_api.migrate_instance_start(
                            ctxt, instance, migration)
                except Exception:
                    LOG.exception(
                        'Failed to activate port bindings on the source '
                        'host: %s', migration.source_compute,
                        instance=instance)

                # Rollback volume connections on this host.
                for bdm in bdms:
                    if bdm.is_volume:
                        try:
                            self._remove_volume_connection(
                                ctxt, bdm, instance, delete_attachment=True)
                        except Exception:
                            LOG.exception('Failed to remove volume connection '
                                          'on this host %s for volume %s.',
                                          self.host, bdm.volume_id,
                                          instance=instance)

    @wrap_exception()
    @wrap_instance_fault
    def add_fixed_ip_to_instance(self, context, network_id, instance):
        """Calls network_api to add new fixed_ip to instance
        then injects the new network info and resets instance networking.

        """
        self._notify_about_instance_usage(
                context, instance, "create_ip.start")

        network_info = self.network_api.add_fixed_ip_to_instance(context,
                                                                 instance,
                                                                 network_id)
        self._inject_network_info(instance, network_info)

        # NOTE(russellb) We just want to bump updated_at.  See bug 1143466.
        instance.updated_at = timeutils.utcnow()
        instance.save()

        self._notify_about_instance_usage(
            context, instance, "create_ip.end", network_info=network_info)

    @wrap_exception()
    @wrap_instance_fault
    def remove_fixed_ip_from_instance(self, context, address, instance):
        """Calls network_api to remove existing fixed_ip from instance
        by injecting the altered network info and resetting
        instance networking.
        """
        self._notify_about_instance_usage(
                context, instance, "delete_ip.start")

        network_info = self.network_api.remove_fixed_ip_from_instance(context,
                                                                      instance,
                                                                      address)
        self._inject_network_info(instance, network_info)

        # NOTE(russellb) We just want to bump updated_at.  See bug 1143466.
        instance.updated_at = timeutils.utcnow()
        instance.save()

        self._notify_about_instance_usage(
            context, instance, "delete_ip.end", network_info=network_info)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def pause_instance(self, context, instance):
        """Pause an instance on this host."""
        context = context.elevated()
        LOG.info('Pausing', instance=instance)
        self._notify_about_instance_usage(context, instance, 'pause.start')
        compute_utils.notify_about_instance_action(context, instance,
               self.host, action=fields.NotificationAction.PAUSE,
               phase=fields.NotificationPhase.START)
        self.driver.pause(instance)
        instance.power_state = self._get_power_state(instance)
        instance.vm_state = vm_states.PAUSED
        instance.task_state = None
        instance.save(expected_task_state=task_states.PAUSING)
        self._notify_about_instance_usage(context, instance, 'pause.end')
        compute_utils.notify_about_instance_action(context, instance,
               self.host, action=fields.NotificationAction.PAUSE,
               phase=fields.NotificationPhase.END)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def unpause_instance(self, context, instance):
        """Unpause a paused instance on this host."""
        context = context.elevated()
        LOG.info('Unpausing', instance=instance)
        self._notify_about_instance_usage(context, instance, 'unpause.start')
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.UNPAUSE,
            phase=fields.NotificationPhase.START)
        self.driver.unpause(instance)
        instance.power_state = self._get_power_state(instance)
        instance.vm_state = vm_states.ACTIVE
        instance.task_state = None
        instance.save(expected_task_state=task_states.UNPAUSING)
        self._notify_about_instance_usage(context, instance, 'unpause.end')
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.UNPAUSE,
            phase=fields.NotificationPhase.END)

    @wrap_exception()
    def host_power_action(self, context, action):
        """Reboots, shuts down or powers up the host."""
        return self.driver.host_power_action(action)

    @wrap_exception()
    def host_maintenance_mode(self, context, host, mode):
        """Start/Stop host maintenance window. On start, it triggers
        guest VMs evacuation.
        """
        return self.driver.host_maintenance_mode(host, mode)

    def _update_compute_provider_status(self, context, enabled):
        """Adds or removes the COMPUTE_STATUS_DISABLED trait for this host.

        For each ComputeNode managed by this service, adds or removes the
        COMPUTE_STATUS_DISABLED traits to/from the associated resource provider
        in Placement.

        :param context: nova auth RequestContext
        :param enabled: True if the node is enabled in which case the trait
            would be removed, False if the node is disabled in which case
            the trait would be added.
        :raises: ComputeHostNotFound if there are no compute nodes found in
            the ResourceTracker for this service.
        """
        # Get the compute node(s) on this host. Remember that ironic can be
        # managing more than one compute node.
        nodes = self.rt.compute_nodes.values()
        if not nodes:
            raise exception.ComputeHostNotFound(host=self.host)
        # For each node, we want to add (or remove) the COMPUTE_STATUS_DISABLED
        # trait on the related resource provider in placement so the scheduler
        # (pre-)filters the provider based on its status.
        for node in nodes:
            try:
                self.virtapi.update_compute_provider_status(
                    context, node.uuid, enabled)
            except (exception.ResourceProviderTraitRetrievalFailed,
                    exception.ResourceProviderUpdateConflict,
                    exception.ResourceProviderUpdateFailed,
                    exception.TraitRetrievalFailed) as e:
                # This is best effort so just log a warning and continue.
                LOG.warning('An error occurred while updating '
                            'COMPUTE_STATUS_DISABLED trait on compute node '
                            'resource provider %s. The trait will be '
                            'synchronized when the update_available_resource '
                            'periodic task runs. Error: %s',
                            node.uuid, e.format_message())
            except Exception:
                LOG.exception('An error occurred while updating '
                              'COMPUTE_STATUS_DISABLED trait on compute node '
                              'resource provider %s. The trait will be '
                              'synchronized when the '
                              'update_available_resource periodic task runs.',
                              node.uuid)

    @wrap_exception()
    def set_host_enabled(self, context, enabled):
        """Sets the specified host's ability to accept new instances.

        This method will add or remove the COMPUTE_STATUS_DISABLED trait
        to/from the associated compute node resource provider(s) for this
        compute service.
        """
        try:
            self._update_compute_provider_status(context, enabled)
        except exception.ComputeHostNotFound:
            LOG.warning('Unable to add/remove trait COMPUTE_STATUS_DISABLED. '
                        'No ComputeNode(s) found for host: %s', self.host)

        try:
            return self.driver.set_host_enabled(enabled)
        except NotImplementedError:
            # Only the xenapi driver implements set_host_enabled but we don't
            # want NotImplementedError to get raised back to the API. We still
            # need to honor the compute RPC API contract and return 'enabled'
            # or 'disabled' though.
            return 'enabled' if enabled else 'disabled'

    @wrap_exception()
    def get_host_uptime(self, context):
        """Returns the result of calling "uptime" on the target host."""
        return self.driver.get_host_uptime()

    @wrap_exception()
    @wrap_instance_fault
    def get_diagnostics(self, context, instance):
        """Retrieve diagnostics for an instance on this host."""
        current_power_state = self._get_power_state(instance)
        if current_power_state == power_state.RUNNING:
            LOG.info("Retrieving diagnostics", instance=instance)
            return self.driver.get_diagnostics(instance)
        else:
            raise exception.InstanceInvalidState(
                attr='power state',
                instance_uuid=instance.uuid,
                state=power_state.STATE_MAP[instance.power_state],
                method='get_diagnostics')

    @wrap_exception()
    @wrap_instance_fault
    def get_instance_diagnostics(self, context, instance):
        """Retrieve diagnostics for an instance on this host."""
        current_power_state = self._get_power_state(instance)
        if current_power_state == power_state.RUNNING:
            LOG.info("Retrieving diagnostics", instance=instance)
            return self.driver.get_instance_diagnostics(instance)
        else:
            raise exception.InstanceInvalidState(
                attr='power state',
                instance_uuid=instance.uuid,
                state=power_state.STATE_MAP[instance.power_state],
                method='get_diagnostics')

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def suspend_instance(self, context, instance):
        """Suspend the given instance."""
        context = context.elevated()

        # Store the old state
        instance.system_metadata['old_vm_state'] = instance.vm_state
        self._notify_about_instance_usage(context, instance, 'suspend.start')
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.SUSPEND,
                phase=fields.NotificationPhase.START)
        with self._error_out_instance_on_exception(context, instance,
             instance_state=instance.vm_state):
            self.driver.suspend(context, instance)
        instance.power_state = self._get_power_state(instance)
        instance.vm_state = vm_states.SUSPENDED
        instance.task_state = None
        instance.save(expected_task_state=task_states.SUSPENDING)
        self._notify_about_instance_usage(context, instance, 'suspend.end')
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.SUSPEND,
                phase=fields.NotificationPhase.END)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def resume_instance(self, context, instance):
        """Resume the given suspended instance."""
        context = context.elevated()
        LOG.info('Resuming', instance=instance)

        self._notify_about_instance_usage(context, instance, 'resume.start')

        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
            context, instance.uuid)
        block_device_info = self._get_instance_block_device_info(
            context, instance, bdms=bdms)

        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.RESUME,
            phase=fields.NotificationPhase.START, bdms=bdms)

        network_info = self.network_api.get_instance_nw_info(context, instance)

        with self._error_out_instance_on_exception(context, instance,
             instance_state=instance.vm_state):
            self.driver.resume(context, instance, network_info,
                               block_device_info)

        instance.power_state = self._get_power_state(instance)

        # We default to the ACTIVE state for backwards compatibility
        instance.vm_state = instance.system_metadata.pop('old_vm_state',
                                                         vm_states.ACTIVE)

        instance.task_state = None
        instance.save(expected_task_state=task_states.RESUMING)
        self._notify_about_instance_usage(context, instance, 'resume.end')
        compute_utils.notify_about_instance_action(context, instance,
            self.host, action=fields.NotificationAction.RESUME,
            phase=fields.NotificationPhase.END, bdms=bdms)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def shelve_instance(self, context, instance, image_id,
                        clean_shutdown, accel_uuids):
        """Shelve an instance.

        This should be used when you want to take a snapshot of the instance.
        It also adds system_metadata that can be used by a periodic task to
        offload the shelved instance after a period of time.

        :param context: request context
        :param instance: an Instance object
        :param image_id: an image id to snapshot to.
        :param clean_shutdown: give the GuestOS a chance to stop
        :param accel_uuids: the accelerators uuids for the instance
        """

        @utils.synchronized(instance.uuid)
        def do_shelve_instance():
            self._shelve_instance(context, instance, image_id, clean_shutdown,
                                  accel_uuids)
        do_shelve_instance()

    def _shelve_instance(self, context, instance, image_id,
                         clean_shutdown, accel_uuids=None):
        LOG.info('Shelving', instance=instance)
        offload = CONF.shelved_offload_time == 0
        if offload:
            # Get the BDMs early so we can pass them into versioned
            # notifications since _shelve_offload_instance needs the
            # BDMs anyway.
            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                context, instance.uuid)
        else:
            bdms = None
        compute_utils.notify_usage_exists(self.notifier, context, instance,
                                          self.host, current_period=True)
        self._notify_about_instance_usage(context, instance, 'shelve.start')
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.SHELVE,
                phase=fields.NotificationPhase.START, bdms=bdms)

        def update_task_state(task_state, expected_state=task_states.SHELVING):
            shelving_state_map = {
                    task_states.IMAGE_PENDING_UPLOAD:
                        task_states.SHELVING_IMAGE_PENDING_UPLOAD,
                    task_states.IMAGE_UPLOADING:
                        task_states.SHELVING_IMAGE_UPLOADING,
                    task_states.SHELVING: task_states.SHELVING}
            task_state = shelving_state_map[task_state]
            expected_state = shelving_state_map[expected_state]
            instance.task_state = task_state
            instance.save(expected_task_state=expected_state)
        # Do not attempt a clean shutdown of a paused guest since some
        # hypervisors will fail the clean shutdown if the guest is not
        # running.
        if instance.power_state == power_state.PAUSED:
            clean_shutdown = False
        self._power_off_instance(instance, clean_shutdown)
        self.driver.snapshot(context, instance, image_id, update_task_state)

        instance.system_metadata['shelved_at'] = timeutils.utcnow().isoformat()
        instance.system_metadata['shelved_image_id'] = image_id
        instance.system_metadata['shelved_host'] = self.host
        instance.vm_state = vm_states.SHELVED
        instance.task_state = None
        if offload:
            instance.task_state = task_states.SHELVING_OFFLOADING
        instance.power_state = self._get_power_state(instance)
        instance.save(expected_task_state=[
                task_states.SHELVING,
                task_states.SHELVING_IMAGE_UPLOADING])

        self._notify_about_instance_usage(context, instance, 'shelve.end')
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.SHELVE,
                phase=fields.NotificationPhase.END, bdms=bdms)

        if offload:
            self._shelve_offload_instance(
                context, instance, clean_shutdown=False, bdms=bdms,
                accel_uuids=accel_uuids)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def shelve_offload_instance(self, context, instance, clean_shutdown,
            accel_uuids):
        """Remove a shelved instance from the hypervisor.

        This frees up those resources for use by other instances, but may lead
        to slower unshelve times for this instance.  This method is used by
        volume backed instances since restoring them doesn't involve the
        potentially large download of an image.

        :param context: request context
        :param instance: nova.objects.instance.Instance
        :param clean_shutdown: give the GuestOS a chance to stop
        :param accel_uuids: the accelerators uuids for the instance
        """

        @utils.synchronized(instance.uuid)
        def do_shelve_offload_instance():
            self._shelve_offload_instance(context, instance, clean_shutdown,
                                          accel_uuids=accel_uuids)
        do_shelve_offload_instance()

    def _shelve_offload_instance(self, context, instance, clean_shutdown,
                                 bdms=None, accel_uuids=None):
        LOG.info('Shelve offloading', instance=instance)
        if bdms is None:
            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                context, instance.uuid)
        self._notify_about_instance_usage(context, instance,
                'shelve_offload.start')
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.SHELVE_OFFLOAD,
                phase=fields.NotificationPhase.START, bdms=bdms)

        self._power_off_instance(instance, clean_shutdown)
        current_power_state = self._get_power_state(instance)
        network_info = self.network_api.get_instance_nw_info(context, instance)

        block_device_info = self._get_instance_block_device_info(context,
                                                                 instance,
                                                                 bdms=bdms)
        self.driver.destroy(context, instance, network_info,
                block_device_info)

        # the instance is going to be removed from the host so we want to
        # terminate all the connections with the volume server and the host
        self._terminate_volume_connections(context, instance, bdms)

        # NOTE(brinzhang): Free up the accelerator resource occupied
        # in the cyborg service.
        if accel_uuids:
            cyclient = cyborg.get_client(context)
            cyclient.delete_arqs_for_instance(instance.uuid)

        # Free up the resource allocations in the placement service.
        # This should happen *before* the vm_state is changed to
        # SHELVED_OFFLOADED in case client-side code is polling the API to
        # schedule more instances (or unshelve) once this server is offloaded.
        self.rt.delete_allocation_for_shelve_offloaded_instance(context,
                                                                instance)

        instance.power_state = current_power_state
        # NOTE(mriedem): The vm_state has to be set before updating the
        # resource tracker, see vm_states.ALLOW_RESOURCE_REMOVAL. The host/node
        # values cannot be nulled out until after updating the resource tracker
        # though.
        instance.vm_state = vm_states.SHELVED_OFFLOADED
        instance.task_state = None
        instance.save(expected_task_state=[task_states.SHELVING,
                                           task_states.SHELVING_OFFLOADING])

        # NOTE(ndipanov): Free resources from the resource tracker
        self._update_resource_tracker(context, instance)

        # NOTE(sfinucan): RPC calls should no longer be attempted against this
        # instance, so ensure any calls result in errors
        self._nil_out_instance_obj_host_and_node(instance)
        instance.save(expected_task_state=None)

        # TODO(melwitt): We should clean up instance console tokens here. The
        # instance has no host at this point and will need to establish a new
        # console connection in the future after it is unshelved.
        self._delete_scheduler_instance_info(context, instance.uuid)
        self._notify_about_instance_usage(context, instance,
                'shelve_offload.end')
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.SHELVE_OFFLOAD,
                phase=fields.NotificationPhase.END, bdms=bdms)

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def unshelve_instance(self, context, instance, image,
                          filter_properties, node, request_spec, accel_uuids):
        """Unshelve the instance.

        :param context: request context
        :param instance: a nova.objects.instance.Instance object
        :param image: an image to build from.  If None we assume a
            volume backed instance.
        :param filter_properties: dict containing limits, retry info etc.
        :param node: target compute node
        :param request_spec: the RequestSpec object used to schedule the
            instance
        :param accel_uuids: the accelerators uuids for the instance
        """
        if filter_properties is None:
            filter_properties = {}

        @utils.synchronized(instance.uuid)
        def do_unshelve_instance():
            self._unshelve_instance(
                context, instance, image, filter_properties, node,
                request_spec, accel_uuids)
        do_unshelve_instance()

    def _unshelve_instance_key_scrub(self, instance):
        """Remove data from the instance that may cause side effects."""
        cleaned_keys = dict(
                key_data=instance.key_data,
                auto_disk_config=instance.auto_disk_config)
        instance.key_data = None
        instance.auto_disk_config = False
        return cleaned_keys

    def _unshelve_instance_key_restore(self, instance, keys):
        """Restore previously scrubbed keys before saving the instance."""
        instance.update(keys)

    def _unshelve_instance(self, context, instance, image, filter_properties,
                           node, request_spec, accel_uuids):
        LOG.info('Unshelving', instance=instance)
        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                context, instance.uuid)

        self._notify_about_instance_usage(context, instance, 'unshelve.start')
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.UNSHELVE,
                phase=fields.NotificationPhase.START, bdms=bdms)

        instance.task_state = task_states.SPAWNING
        instance.save()

        block_device_info = self._prep_block_device(context, instance, bdms)
        scrubbed_keys = self._unshelve_instance_key_scrub(instance)

        if node is None:
            node = self._get_nodename(instance)

        limits = filter_properties.get('limits', {})

        allocations = self.reportclient.get_allocations_for_consumer(
            context, instance.uuid)

        shelved_image_ref = instance.image_ref
        if image:
            instance.image_ref = image['id']
            image_meta = objects.ImageMeta.from_dict(image)
        else:
            image_meta = objects.ImageMeta.from_dict(
                utils.get_image_from_system_metadata(
                    instance.system_metadata))

        provider_mappings = self._get_request_group_mapping(request_spec)

        try:
            if provider_mappings:
                update = (
                    compute_utils.
                        update_pci_request_spec_with_allocated_interface_name)
                update(
                    context, self.reportclient, instance.pci_requests.requests,
                    provider_mappings)

            accel_info = []
            if accel_uuids:
                try:
                    accel_info = self._get_bound_arq_resources(
                        context, instance, accel_uuids)
                except (Exception, eventlet.timeout.Timeout) as exc:
                    LOG.exception('Failure getting accelerator requests '
                                  'with the exception: %s', exc,
                                  instance=instance)
                    self._build_resources_cleanup(instance, None)
                    raise

            with self.rt.instance_claim(context, instance, node, allocations,
                                        limits):
                self.network_api.setup_instance_network_on_host(
                    context, instance, self.host,
                    provider_mappings=provider_mappings)
                network_info = self.network_api.get_instance_nw_info(
                    context, instance)

                self.driver.spawn(context, instance, image_meta,
                                  injected_files=[],
                                  admin_password=None,
                                  allocations=allocations,
                                  network_info=network_info,
                                  block_device_info=block_device_info,
                                  accel_info=accel_info)
        except Exception:
            with excutils.save_and_reraise_exception(logger=LOG):
                LOG.exception('Instance failed to spawn',
                              instance=instance)
                # Set the image_ref back to initial image_ref because instance
                # object might have been saved with image['id']
                # https://bugs.launchpad.net/nova/+bug/1934094
                instance.image_ref = shelved_image_ref
                # Cleanup allocations created by the scheduler on this host
                # since we failed to spawn the instance. We do this both if
                # the instance claim failed with ComputeResourcesUnavailable
                # or if we did claim but the spawn failed, because aborting the
                # instance claim will not remove the allocations.
                self.reportclient.delete_allocation_for_instance(
                    context, instance.uuid, force=True)
                # FIXME: Umm, shouldn't we be rolling back port bindings too?
                self._terminate_volume_connections(context, instance, bdms)
                # The reverts_task_state decorator on unshelve_instance will
                # eventually save these updates.
                self._nil_out_instance_obj_host_and_node(instance)

        if image:
            instance.image_ref = shelved_image_ref
            self._delete_snapshot_of_shelved_instance(context, instance,
                                                      image['id'])

        self._unshelve_instance_key_restore(instance, scrubbed_keys)
        self._update_instance_after_spawn(instance)
        # Delete system_metadata for a shelved instance
        compute_utils.remove_shelved_keys_from_system_metadata(instance)

        instance.save(expected_task_state=task_states.SPAWNING)
        self._update_scheduler_instance_info(context, instance)
        self._notify_about_instance_usage(context, instance, 'unshelve.end')
        compute_utils.notify_about_instance_action(context, instance,
                self.host, action=fields.NotificationAction.UNSHELVE,
                phase=fields.NotificationPhase.END, bdms=bdms)

    def _inject_network_info(self, instance, network_info):
        """Inject network info for the given instance."""
        LOG.debug('Inject network info', instance=instance)
        LOG.debug('network_info to inject: |%s|', network_info,
                  instance=instance)

        self.driver.inject_network_info(instance, network_info)

    @wrap_instance_fault
    def inject_network_info(self, context, instance):
        """Inject network info, but don't return the info."""
        network_info = self.network_api.get_instance_nw_info(context, instance)
        self._inject_network_info(instance, network_info)

    @messaging.expected_exceptions(NotImplementedError,
                                   exception.ConsoleNotAvailable,
                                   exception.InstanceNotFound)
    @wrap_exception()
    @wrap_instance_fault
    def get_console_output(self, context, instance, tail_length):
        """Send the console output for the given instance."""
        context = context.elevated()
        LOG.info("Get console output", instance=instance)
        output = self.driver.get_console_output(context, instance)

        if type(output) is str:
            output = output.encode("latin-1")

        if tail_length is not None:
            output = self._tail_log(output, tail_length)

        return output.decode('ascii', 'replace')

    def _tail_log(self, log, length):
        try:
            length = int(length)
        except ValueError:
            length = 0

        if length == 0:
            return b''
        else:
            return b'\n'.join(log.split(b'\n')[-int(length):])

    @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
                                   exception.InstanceNotReady,
                                   exception.InstanceNotFound,
                                   exception.ConsoleTypeUnavailable,
                                   NotImplementedError)
    @wrap_exception()
    @wrap_instance_fault
    def get_vnc_console(self, context, console_type, instance):
        """Return connection information for a vnc console."""
        context = context.elevated()
        LOG.debug("Getting vnc console", instance=instance)

        if not CONF.vnc.enabled:
            raise exception.ConsoleTypeUnavailable(console_type=console_type)

        if console_type == 'novnc':
            # For essex, novncproxy_base_url must include the full path
            # including the html file (like http://myhost/vnc_auto.html)
            access_url_base = CONF.vnc.novncproxy_base_url
        else:
            raise exception.ConsoleTypeInvalid(console_type=console_type)

        try:
            # Retrieve connect info from driver, and then decorate with our
            # access info token
            console = self.driver.get_vnc_console(context, instance)
            console_auth = objects.ConsoleAuthToken(
                context=context,
                console_type=console_type,
                host=console.host,
                port=console.port,
                internal_access_path=console.internal_access_path,
                instance_uuid=instance.uuid,
                access_url_base=access_url_base,
            )
            console_auth.authorize(CONF.consoleauth.token_ttl)
            connect_info = console.get_connection_info(
                console_auth.token, console_auth.access_url)

        except exception.InstanceNotFound:
            if instance.vm_state != vm_states.BUILDING:
                raise
            raise exception.InstanceNotReady(instance_id=instance.uuid)

        return connect_info

    @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
                                   exception.InstanceNotReady,
                                   exception.InstanceNotFound,
                                   exception.ConsoleTypeUnavailable,
                                   NotImplementedError)
    @wrap_exception()
    @wrap_instance_fault
    def get_spice_console(self, context, console_type, instance):
        """Return connection information for a spice console."""
        context = context.elevated()
        LOG.debug("Getting spice console", instance=instance)

        if not CONF.spice.enabled:
            raise exception.ConsoleTypeUnavailable(console_type=console_type)

        if console_type != 'spice-html5':
            raise exception.ConsoleTypeInvalid(console_type=console_type)

        try:
            # Retrieve connect info from driver, and then decorate with our
            # access info token
            console = self.driver.get_spice_console(context, instance)
            console_auth = objects.ConsoleAuthToken(
                context=context,
                console_type=console_type,
                host=console.host,
                port=console.port,
                internal_access_path=console.internal_access_path,
                instance_uuid=instance.uuid,
                access_url_base=CONF.spice.html5proxy_base_url,
            )
            console_auth.authorize(CONF.consoleauth.token_ttl)
            connect_info = console.get_connection_info(
                console_auth.token, console_auth.access_url)

        except exception.InstanceNotFound:
            if instance.vm_state != vm_states.BUILDING:
                raise
            raise exception.InstanceNotReady(instance_id=instance.uuid)

        return connect_info

    @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
                                   exception.InstanceNotReady,
                                   exception.InstanceNotFound,
                                   exception.ConsoleTypeUnavailable,
                                   NotImplementedError)
    @wrap_exception()
    @wrap_instance_fault
    def get_rdp_console(self, context, console_type, instance):
        """Return connection information for a RDP console."""
        context = context.elevated()
        LOG.debug("Getting RDP console", instance=instance)

        if not CONF.rdp.enabled:
            raise exception.ConsoleTypeUnavailable(console_type=console_type)

        if console_type != 'rdp-html5':
            raise exception.ConsoleTypeInvalid(console_type=console_type)

        try:
            # Retrieve connect info from driver, and then decorate with our
            # access info token
            console = self.driver.get_rdp_console(context, instance)
            console_auth = objects.ConsoleAuthToken(
                context=context,
                console_type=console_type,
                host=console.host,
                port=console.port,
                internal_access_path=console.internal_access_path,
                instance_uuid=instance.uuid,
                access_url_base=CONF.rdp.html5_proxy_base_url,
            )
            console_auth.authorize(CONF.consoleauth.token_ttl)
            connect_info = console.get_connection_info(
                console_auth.token, console_auth.access_url)

        except exception.InstanceNotFound:
            if instance.vm_state != vm_states.BUILDING:
                raise
            raise exception.InstanceNotReady(instance_id=instance.uuid)

        return connect_info

    @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
                                   exception.InstanceNotReady,
                                   exception.InstanceNotFound,
                                   exception.ConsoleTypeUnavailable,
                                   NotImplementedError)
    @wrap_exception()
    @wrap_instance_fault
    def get_mks_console(self, context, console_type, instance):
        """Return connection information for a MKS console."""
        context = context.elevated()
        LOG.debug("Getting MKS console", instance=instance)

        if not CONF.mks.enabled:
            raise exception.ConsoleTypeUnavailable(console_type=console_type)

        if console_type != 'webmks':
            raise exception.ConsoleTypeInvalid(console_type=console_type)

        try:
            # Retrieve connect info from driver, and then decorate with our
            # access info token
            console = self.driver.get_mks_console(context, instance)
            console_auth = objects.ConsoleAuthToken(
                context=context,
                console_type=console_type,
                host=console.host,
                port=console.port,
                internal_access_path=console.internal_access_path,
                instance_uuid=instance.uuid,
                access_url_base=CONF.mks.mksproxy_base_url,
            )
            console_auth.authorize(CONF.consoleauth.token_ttl)
            connect_info = console.get_connection_info(
                console_auth.token, console_auth.access_url)

        except exception.InstanceNotFound:
            if instance.vm_state != vm_states.BUILDING:
                raise
            raise exception.InstanceNotReady(instance_id=instance.uuid)

        return connect_info

    @messaging.expected_exceptions(
        exception.ConsoleTypeInvalid,
        exception.InstanceNotReady,
        exception.InstanceNotFound,
        exception.ConsoleTypeUnavailable,
        exception.SocketPortRangeExhaustedException,
        exception.ImageSerialPortNumberInvalid,
        exception.ImageSerialPortNumberExceedFlavorValue,
        NotImplementedError)
    @wrap_exception()
    @wrap_instance_fault
    def get_serial_console(self, context, console_type, instance):
        """Returns connection information for a serial console."""

        LOG.debug("Getting serial console", instance=instance)

        if not CONF.serial_console.enabled:
            raise exception.ConsoleTypeUnavailable(console_type=console_type)

        context = context.elevated()

        try:
            # Retrieve connect info from driver, and then decorate with our
            # access info token
            console = self.driver.get_serial_console(context, instance)
            console_auth = objects.ConsoleAuthToken(
                context=context,
                console_type=console_type,
                host=console.host,
                port=console.port,
                internal_access_path=console.internal_access_path,
                instance_uuid=instance.uuid,
                access_url_base=CONF.serial_console.base_url,
            )
            console_auth.authorize(CONF.consoleauth.token_ttl)
            connect_info = console.get_connection_info(
                console_auth.token, console_auth.access_url)

        except exception.InstanceNotFound:
            if instance.vm_state != vm_states.BUILDING:
                raise
            raise exception.InstanceNotReady(instance_id=instance.uuid)

        return connect_info

    @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
                                   exception.InstanceNotReady,
                                   exception.InstanceNotFound)
    @wrap_exception()
    @wrap_instance_fault
    def validate_console_port(self, ctxt, instance, port, console_type):
        if console_type == "spice-html5":
            console_info = self.driver.get_spice_console(ctxt, instance)
        elif console_type == "rdp-html5":
            console_info = self.driver.get_rdp_console(ctxt, instance)
        elif console_type == "serial":
            console_info = self.driver.get_serial_console(ctxt, instance)
        elif console_type == "webmks":
            console_info = self.driver.get_mks_console(ctxt, instance)
        else:
            console_info = self.driver.get_vnc_console(ctxt, instance)

        # Some drivers may return an int on console_info.port but the port
        # variable in this method is a string, so cast to be sure we are
        # comparing the correct types.
        return str(console_info.port) == port

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_fault
    def reserve_block_device_name(self, context, instance, device,
                                  volume_id, disk_bus, device_type, tag,
                                  multiattach):
        if (tag and not
                self.driver.capabilities.get('supports_tagged_attach_volume',
                                             False)):
            raise exception.VolumeTaggedAttachNotSupported()

        if (multiattach and not
                self.driver.capabilities.get('supports_multiattach', False)):
            raise exception.MultiattachNotSupportedByVirtDriver(
                volume_id=volume_id)

        @utils.synchronized(instance.uuid)
        def do_reserve():
            bdms = (
                objects.BlockDeviceMappingList.get_by_instance_uuid(
                    context, instance.uuid))

            # Now that we have the lock check that we haven't raced another
            # request and ensure there is no existing attachment
            if any(b for b in bdms if b.volume_id == volume_id):
                msg = _("volume %s already attached") % volume_id
                raise exception.InvalidVolume(reason=msg)

            # NOTE(ndipanov): We need to explicitly set all the fields on the
            #                 object so that obj_load_attr does not fail
            new_bdm = objects.BlockDeviceMapping(
                    context=context,
                    source_type='volume', destination_type='volume',
                    instance_uuid=instance.uuid, boot_index=None,
                    volume_id=volume_id,
                    device_name=device, guest_format=None,
                    disk_bus=disk_bus, device_type=device_type, tag=tag)

            new_bdm.device_name = self._get_device_name_for_instance(
                    instance, bdms, new_bdm)

            # NOTE(vish): create bdm here to avoid race condition
            new_bdm.create()
            return new_bdm

        return do_reserve()

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def attach_volume(self, context, instance, bdm):
        """Attach a volume to an instance."""
        driver_bdm = driver_block_device.convert_volume(bdm)

        @utils.synchronized(instance.uuid)
        def do_attach_volume(context, instance, driver_bdm):
            try:
                return self._attach_volume(context, instance, driver_bdm)
            except Exception:
                with excutils.save_and_reraise_exception():
                    bdm.destroy()

        do_attach_volume(context, instance, driver_bdm)

    def _attach_volume(self, context, instance, bdm):
        context = context.elevated()
        LOG.info('Attaching volume %(volume_id)s to %(mountpoint)s',
                 {'volume_id': bdm.volume_id,
                  'mountpoint': bdm['mount_device']},
                 instance=instance)
        compute_utils.notify_about_volume_attach_detach(
            context, instance, self.host,
            action=fields.NotificationAction.VOLUME_ATTACH,
            phase=fields.NotificationPhase.START,
            volume_id=bdm.volume_id)
        try:
            bdm.attach(context, instance, self.volume_api, self.driver,
                       do_driver_attach=True)
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.exception("Failed to attach %(volume_id)s "
                              "at %(mountpoint)s",
                              {'volume_id': bdm.volume_id,
                               'mountpoint': bdm['mount_device']},
                              instance=instance)
                if bdm['attachment_id']:
                    # Try to delete the attachment to make the volume
                    # available again. Note that DriverVolumeBlockDevice
                    # may have already deleted the attachment so ignore
                    # VolumeAttachmentNotFound.
                    try:
                        self.volume_api.attachment_delete(
                            context, bdm['attachment_id'])
                    except exception.VolumeAttachmentNotFound as exc:
                        LOG.debug('Ignoring VolumeAttachmentNotFound: %s',
                                  exc, instance=instance)
                else:
                    self.volume_api.unreserve_volume(context, bdm.volume_id)
                compute_utils.notify_about_volume_attach_detach(
                    context, instance, self.host,
                    action=fields.NotificationAction.VOLUME_ATTACH,
                    phase=fields.NotificationPhase.ERROR,
                    exception=e,
                    volume_id=bdm.volume_id)

        info = {'volume_id': bdm.volume_id}
        self._notify_about_instance_usage(
            context, instance, "volume.attach", extra_usage_info=info)
        compute_utils.notify_about_volume_attach_detach(
            context, instance, self.host,
            action=fields.NotificationAction.VOLUME_ATTACH,
            phase=fields.NotificationPhase.END,
            volume_id=bdm.volume_id)

    def _notify_volume_usage_detach(self, context, instance, bdm):
        if CONF.volume_usage_poll_interval <= 0:
            return

        mp = bdm.device_name
        # Handle bootable volumes which will not contain /dev/
        if '/dev/' in mp:
            mp = mp[5:]
        try:
            vol_stats = self.driver.block_stats(instance, mp)
            if vol_stats is None:
                return
        except NotImplementedError:
            return

        LOG.debug("Updating volume usage cache with totals", instance=instance)
        rd_req, rd_bytes, wr_req, wr_bytes, flush_ops = vol_stats
        vol_usage = objects.VolumeUsage(context)
        vol_usage.volume_id = bdm.volume_id
        vol_usage.instance_uuid = instance.uuid
        vol_usage.project_id = instance.project_id
        vol_usage.user_id = instance.user_id
        vol_usage.availability_zone = instance.availability_zone
        vol_usage.curr_reads = rd_req
        vol_usage.curr_read_bytes = rd_bytes
        vol_usage.curr_writes = wr_req
        vol_usage.curr_write_bytes = wr_bytes
        vol_usage.save(update_totals=True)
        self.notifier.info(context, 'volume.usage', vol_usage.to_dict())
        compute_utils.notify_about_volume_usage(context, vol_usage, self.host)

    def _detach_volume(self, context, bdm, instance, destroy_bdm=True,
                       attachment_id=None):
        """Detach a volume from an instance.

        :param context: security context
        :param bdm: nova.objects.BlockDeviceMapping volume bdm to detach
        :param instance: the Instance object to detach the volume from
        :param destroy_bdm: if True, the corresponding BDM entry will be marked
                            as deleted. Disabling this is useful for operations
                            like rebuild, when we don't want to destroy BDM
        :param attachment_id: The volume attachment_id for the given instance
                              and volume.
        """
        volume_id = bdm.volume_id
        compute_utils.notify_about_volume_attach_detach(
            context, instance, self.host,
            action=fields.NotificationAction.VOLUME_DETACH,
            phase=fields.NotificationPhase.START,
            volume_id=volume_id)

        self._notify_volume_usage_detach(context, instance, bdm)

        LOG.info('Detaching volume %(volume_id)s',
                 {'volume_id': volume_id}, instance=instance)

        driver_bdm = driver_block_device.convert_volume(bdm)
        driver_bdm.detach(context, instance, self.volume_api, self.driver,
                          attachment_id=attachment_id, destroy_bdm=destroy_bdm)

        info = dict(volume_id=volume_id)
        self._notify_about_instance_usage(
            context, instance, "volume.detach", extra_usage_info=info)
        compute_utils.notify_about_volume_attach_detach(
            context, instance, self.host,
            action=fields.NotificationAction.VOLUME_DETACH,
            phase=fields.NotificationPhase.END,
            volume_id=volume_id)

        if 'tag' in bdm and bdm.tag:
            self._delete_disk_metadata(instance, bdm)
        if destroy_bdm:
            bdm.destroy()

    def _delete_disk_metadata(self, instance, bdm):
        for device in instance.device_metadata.devices:
            if isinstance(device, objects.DiskMetadata):
                if 'serial' in device:
                    if device.serial == bdm.volume_id:
                        instance.device_metadata.devices.remove(device)
                        instance.save()
                        break
                else:
                    # NOTE(artom) We log the entire device object because all
                    # fields are nullable and may not be set
                    LOG.warning('Unable to determine whether to clean up '
                                'device metadata for disk %s', device,
                                instance=instance)

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def detach_volume(self, context, volume_id, instance, attachment_id):
        """Detach a volume from an instance.

        :param context: security context
        :param volume_id: the volume id
        :param instance: the Instance object to detach the volume from
        :param attachment_id: The volume attachment_id for the given instance
                              and volume.

        """
        @utils.synchronized(instance.uuid)
        def do_detach_volume(context, volume_id, instance, attachment_id):
            bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
                    context, volume_id, instance.uuid)
            self._detach_volume(context, bdm, instance,
                                attachment_id=attachment_id)

        do_detach_volume(context, volume_id, instance, attachment_id)

    def _init_volume_connection(self, context, new_volume,
                                old_volume_id, connector, bdm,
                                new_attachment_id, mountpoint):
        new_volume_id = new_volume['id']
        if new_attachment_id is None:
            # We're dealing with an old-style attachment so initialize the
            # connection so we can get the connection_info.
            new_cinfo = self.volume_api.initialize_connection(context,
                                                              new_volume_id,
                                                              connector)
        else:
            # Check for multiattach on the new volume and if True, check to
            # see if the virt driver supports multiattach.
            # TODO(mriedem): This is copied from DriverVolumeBlockDevice
            # and should be consolidated into some common code at some point.
            vol_multiattach = new_volume.get('multiattach', False)
            virt_multiattach = self.driver.capabilities.get(
                'supports_multiattach', False)
            if vol_multiattach and not virt_multiattach:
                raise exception.MultiattachNotSupportedByVirtDriver(
                    volume_id=new_volume_id)

            # This is a new style attachment and the API created the new
            # volume attachment and passed the id to the compute over RPC.
            # At this point we need to update the new volume attachment with
            # the host connector, which will give us back the new attachment
            # connection_info.
            new_cinfo = self.volume_api.attachment_update(
                context, new_attachment_id, connector,
                mountpoint)['connection_info']

            if vol_multiattach:
                # This will be used by the volume driver to determine the
                # proper disk configuration.
                new_cinfo['multiattach'] = True

        old_cinfo = jsonutils.loads(bdm['connection_info'])
        if old_cinfo and 'serial' not in old_cinfo:
            old_cinfo['serial'] = old_volume_id
        # NOTE(lyarwood): serial is not always present in the returned
        # connection_info so set it if it is missing as we do in
        # DriverVolumeBlockDevice.attach().
        if 'serial' not in new_cinfo:
            new_cinfo['serial'] = new_volume_id
        return (old_cinfo, new_cinfo)

    def _swap_volume(self, context, instance, bdm, connector,
                     old_volume_id, new_volume, resize_to,
                     new_attachment_id, is_cinder_migration):
        new_volume_id = new_volume['id']
        mountpoint = bdm['device_name']
        failed = False
        new_cinfo = None
        try:
            old_cinfo, new_cinfo = self._init_volume_connection(
                context, new_volume, old_volume_id, connector,
                bdm, new_attachment_id, mountpoint)
            # NOTE(lyarwood): The Libvirt driver, the only virt driver
            # currently implementing swap_volume, will modify the contents of
            # new_cinfo when connect_volume is called. This is then saved to
            # the BDM in swap_volume for future use outside of this flow.
            msg = ("swap_volume: Calling driver volume swap with "
                   "connection infos: new: %(new_cinfo)s; "
                   "old: %(old_cinfo)s" %
                   {'new_cinfo': new_cinfo, 'old_cinfo': old_cinfo})
            # Both new and old info might contain password
            LOG.debug(strutils.mask_password(msg), instance=instance)

            self.driver.swap_volume(context, old_cinfo, new_cinfo, instance,
                                    mountpoint, resize_to)
            if new_attachment_id:
                self.volume_api.attachment_complete(context, new_attachment_id)
            msg = ("swap_volume: Driver volume swap returned, new "
                   "connection_info is now : %(new_cinfo)s" %
                   {'new_cinfo': new_cinfo})
            LOG.debug(strutils.mask_password(msg))
        except Exception as ex:
            failed = True
            with excutils.save_and_reraise_exception():
                compute_utils.notify_about_volume_swap(
                    context, instance, self.host,
                    fields.NotificationPhase.ERROR,
                    old_volume_id, new_volume_id, ex)
                if new_cinfo:
                    msg = ("Failed to swap volume %(old_volume_id)s "
                           "for %(new_volume_id)s")
                    LOG.exception(msg, {'old_volume_id': old_volume_id,
                                        'new_volume_id': new_volume_id},
                                  instance=instance)
                else:
                    msg = ("Failed to connect to volume %(volume_id)s "
                           "with volume at %(mountpoint)s")
                    LOG.exception(msg, {'volume_id': new_volume_id,
                                        'mountpoint': bdm['device_name']},
                                  instance=instance)

                # The API marked the volume as 'detaching' for the old volume
                # so we need to roll that back so the volume goes back to
                # 'in-use' state.
                self.volume_api.roll_detaching(context, old_volume_id)

                if new_attachment_id is None:
                    # The API reserved the new volume so it would be in
                    # 'attaching' status, so we need to unreserve it so it
                    # goes back to 'available' status.
                    self.volume_api.unreserve_volume(context, new_volume_id)
                else:
                    # This is a new style attachment for the new volume, which
                    # was created in the API. We just need to delete it here
                    # to put the new volume back into 'available' status.
                    self.volume_api.attachment_delete(
                        context, new_attachment_id)
        finally:
            # TODO(mriedem): This finally block is terribly confusing and is
            # trying to do too much. We should consider removing the finally
            # block and move whatever needs to happen on success and failure
            # into the blocks above for clarity, even if it means a bit of
            # redundant code.
            conn_volume = new_volume_id if failed else old_volume_id
            if new_cinfo:
                LOG.debug("swap_volume: removing Cinder connection "
                          "for volume %(volume)s", {'volume': conn_volume},
                          instance=instance)
                if bdm.attachment_id is None:
                    # This is the pre-3.44 flow for new-style volume
                    # attachments so just terminate the connection.
                    self.volume_api.terminate_connection(context,
                                                         conn_volume,
                                                         connector)
                else:
                    # This is a new style volume attachment. If we failed, then
                    # the new attachment was already deleted above in the
                    # exception block and we have nothing more to do here. If
                    # swap_volume was successful in the driver, then we need to
                    # "detach" the original attachment by deleting it.
                    if not failed:
                        self.volume_api.attachment_delete(
                            context, bdm.attachment_id)

            # Need to make some decisions based on whether this was
            # a Cinder initiated migration or not. The callback to
            # migration completion isn't needed in the case of a
            # nova initiated simple swap of two volume
            # "volume-update" call so skip that. The new attachment
            # scenarios will give us a new attachment record and
            # that's what we want.
            if bdm.attachment_id and not is_cinder_migration:
                # we don't callback to cinder
                comp_ret = {'save_volume_id': new_volume_id}
            else:
                # NOTE(lyarwood): The following call to
                # os-migrate-volume-completion returns a dict containing
                # save_volume_id, this volume id has two possible values :
                # 1. old_volume_id if we are migrating (retyping) volumes
                # 2. new_volume_id if we are swapping between two existing
                #    volumes
                # This volume id is later used to update the volume_id and
                # connection_info['serial'] of the BDM.
                comp_ret = self.volume_api.migrate_volume_completion(
                                                          context,
                                                          old_volume_id,
                                                          new_volume_id,
                                                          error=failed)
                LOG.debug("swap_volume: Cinder migrate_volume_completion "
                          "returned: %(comp_ret)s", {'comp_ret': comp_ret},
                          instance=instance)

        return (comp_ret, new_cinfo)

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def swap_volume(self, context, old_volume_id, new_volume_id, instance,
                    new_attachment_id):
        """Replace the old volume with the new volume within the active server

        :param context: User request context
        :param old_volume_id: Original volume id
        :param new_volume_id: New volume id being swapped to
        :param instance: Instance with original_volume_id attached
        :param new_attachment_id: ID of the new attachment for new_volume_id
        """
        @utils.synchronized(instance.uuid)
        def _do_locked_swap_volume(context, old_volume_id, new_volume_id,
                                   instance, new_attachment_id):
            self._do_swap_volume(context, old_volume_id, new_volume_id,
                                 instance, new_attachment_id)
        _do_locked_swap_volume(context, old_volume_id, new_volume_id, instance,
                               new_attachment_id)

    def _do_swap_volume(self, context, old_volume_id, new_volume_id,
                        instance, new_attachment_id):
        """Replace the old volume with the new volume within the active server

        :param context: User request context
        :param old_volume_id: Original volume id
        :param new_volume_id: New volume id being swapped to
        :param instance: Instance with original_volume_id attached
        :param new_attachment_id: ID of the new attachment for new_volume_id
        """
        context = context.elevated()
        compute_utils.notify_about_volume_swap(
            context, instance, self.host,
            fields.NotificationPhase.START,
            old_volume_id, new_volume_id)

        bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
                context, old_volume_id, instance.uuid)
        connector = self.driver.get_volume_connector(instance)

        resize_to = 0
        old_volume = self.volume_api.get(context, old_volume_id)
        # Yes this is a tightly-coupled state check of what's going on inside
        # cinder, but we need this while we still support old (v1/v2) and
        # new style attachments (v3.44). Once we drop support for old style
        # attachments we could think about cleaning up the cinder-initiated
        # swap volume API flows.
        is_cinder_migration = False
        if 'migration_status' in old_volume:
            is_cinder_migration = old_volume['migration_status'] == 'migrating'
        old_vol_size = old_volume['size']
        new_volume = self.volume_api.get(context, new_volume_id)
        new_vol_size = new_volume['size']
        if new_vol_size > old_vol_size:
            resize_to = new_vol_size

        LOG.info('Swapping volume %(old_volume)s for %(new_volume)s',
                 {'old_volume': old_volume_id, 'new_volume': new_volume_id},
                 instance=instance)
        comp_ret, new_cinfo = self._swap_volume(context,
                                                instance,
                                                bdm,
                                                connector,
                                                old_volume_id,
                                                new_volume,
                                                resize_to,
                                                new_attachment_id,
                                                is_cinder_migration)

        # NOTE(lyarwood): Update the BDM with the modified new_cinfo and
        # correct volume_id returned by Cinder.
        save_volume_id = comp_ret['save_volume_id']

        # NOTE(lyarwood): Overwrite the possibly stale serial and volume_id in
        # the connection_info with the volume_id returned from Cinder. This
        # could be the case during a volume migration where the new_cinfo here
        # refers to the temporary volume *before* Cinder renames it to the
        # original volume UUID at the end of the migration.
        new_cinfo['serial'] = save_volume_id
        new_cinfo['volume_id'] = save_volume_id
        if 'data' in new_cinfo:
            new_cinfo['data']['volume_id'] = save_volume_id
        values = {
            'connection_info': jsonutils.dumps(new_cinfo),
            'source_type': 'volume',
            'destination_type': 'volume',
            'snapshot_id': None,
            'volume_id': save_volume_id,
            'no_device': None}

        if resize_to:
            values['volume_size'] = resize_to

        if new_attachment_id is not None:
            # This was a volume swap for a new-style attachment so we
            # need to update the BDM attachment_id for the new attachment.
            values['attachment_id'] = new_attachment_id

        LOG.debug("swap_volume: Updating volume %(volume_id)s BDM record with "
                  "%(updates)s", {'volume_id': bdm.volume_id,
                                  'updates': values},
                  instance=instance)
        bdm.update(values)
        bdm.save()

        compute_utils.notify_about_volume_swap(
            context, instance, self.host,
            fields.NotificationPhase.END,
            old_volume_id, new_volume_id)

    @wrap_exception()
    def remove_volume_connection(self, context, volume_id, instance):
        """Remove the volume connection on this host

        Detach the volume from this instance on this host, and if this is
        the cinder v2 flow, call cinder to terminate the connection.
        """
        try:
            # NOTE(mriedem): If the BDM was just passed directly we would not
            # need to do this DB query, but this is an RPC interface so
            # changing that requires some care.
            bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
                    context, volume_id, instance.uuid)
            # NOTE(mriedem): Normally we would pass delete_attachment=True to
            # _remove_volume_connection to delete a v3 style volume attachment,
            # but this method is RPC called from _rollback_live_migration which
            # already deletes the attachment, so because of that tight coupling
            # we cannot simply delete a v3 style attachment here without
            # needing to do some behavior modification of that
            # _rollback_live_migration flow which gets messy.
            self._remove_volume_connection(context, bdm, instance)
        except exception.NotFound:
            pass

    def _remove_volume_connection(self, context, bdm, instance,
                                  delete_attachment=False):
        """Remove the volume connection on this host

        Detach the volume from this instance on this host.

        :param context: nova auth request context
        :param bdm: BlockDeviceMapping object for a volume attached to the
            instance
        :param instance: Instance object with a volume attached represented
            by ``bdm``
        :param delete_attachment: If ``bdm.attachment_id`` is not None the
            attachment was made as a cinder v3 style attachment and if True,
            then deletes the volume attachment, otherwise just terminates
            the connection for a cinder legacy style connection.
        """
        driver_bdm = driver_block_device.convert_volume(bdm)
        driver_bdm.driver_detach(context, instance,
                                 self.volume_api, self.driver)
        if bdm.attachment_id is None:
            # cinder v2 api flow
            connector = self.driver.get_volume_connector(instance)
            self.volume_api.terminate_connection(context, bdm.volume_id,
                                                 connector)
        elif delete_attachment:
            # cinder v3 api flow
            self.volume_api.attachment_delete(context, bdm.attachment_id)

    def _deallocate_port_resource_for_instance(
        self,
        context: nova.context.RequestContext,
        instance: 'objects.Instance',
        port_id: str,
        port_allocation: ty.Dict[str, ty.Dict[str, ty.Dict[str, int]]],
    ) -> None:

        if not port_allocation:
            return

        try:
            client = self.reportclient
            client.remove_resources_from_instance_allocation(
                context, instance.uuid, port_allocation)
        except Exception as ex:
            # We always raise here as it is not a race condition where
            # somebody has already deleted the port we want to cleanup.
            # Here we see that the port exists, the allocation exists,
            # but we cannot clean it up so we will actually leak
            # allocations.
            with excutils.save_and_reraise_exception():
                LOG.warning(
                    'Failed to remove resource allocation of port %(port_id)s '
                    'for instance. Error: %(error)s',
                    {'port_id': port_id, 'error': ex},
                    instance=instance)

    def _deallocate_port_for_instance(
            self, context, instance, port_id, raise_on_failure=False,
            pci_device=None):
        try:
            result = self.network_api.deallocate_port_for_instance(
                context, instance, port_id)
            __, port_allocation = result
        except Exception as ex:
            with excutils.save_and_reraise_exception(
                    reraise=raise_on_failure):
                LOG.warning('Failed to deallocate port %(port_id)s '
                            'for instance. Error: %(error)s',
                            {'port_id': port_id, 'error': ex},
                            instance=instance)
        else:
            if pci_device:
                self.rt.unclaim_pci_devices(context, pci_device, instance)
                instance.remove_pci_device_and_request(pci_device)

            # Deallocate the resources in placement that were used by the
            # detached port.
            self._deallocate_port_resource_for_instance(
                context, instance, port_id, port_allocation)

    def _claim_pci_device_for_interface_attach(
        self,
        context: nova.context.RequestContext,
        instance: 'objects.Instance',
        pci_reqs: 'objects.InstancePCIRequests',
    ) -> ty.Optional['objects.PciDevice']:
        """Claim PCI devices if there are PCI requests

        :param context: nova.context.RequestContext
        :param instance: the objects.Instance to where the interface is being
            attached
        :param pci_reqs: A InstancePCIRequests object describing the
            needed PCI devices
        :raises InterfaceAttachPciClaimFailed: if the PCI device claim fails
        :returns: An objects.PciDevice describing the claimed PCI device for
            the interface or None if no device is requested
        """

        if not pci_reqs.requests:
            return None

        try:
            devices = self.rt.claim_pci_devices(
                context, pci_reqs, instance.numa_topology)
        except exception.PciDeviceRequestFailed:
            LOG.info('Failed to claim PCI devices during interface attach '
                     'for PCI request %s', pci_reqs, instance=instance)
            raise exception.InterfaceAttachPciClaimFailed(
                instance_uuid=instance.uuid)

        # NOTE(gibi): We assume that maximum one PCI devices is attached per
        # interface attach request.
        device = devices[0]
        instance.pci_devices.objects.append(device)

        return device

    def _allocate_port_resource_for_instance(
        self,
        context: nova.context.RequestContext,
        instance: 'objects.Instance',
        pci_reqs: 'objects.InstancePCIRequests',
        request_groups: ty.List['objects.RequestGroup'],
        request_level_params: 'objects.RequestLevelParams',
    ) -> ty.Tuple[ty.Optional[ty.Dict[str, ty.List[str]]],
                  ty.Optional[ty.Dict[str, ty.Dict[str, ty.Dict[str, int]]]]]:
        """Allocate resources for the request in placement

        :param context: nova.context.RequestContext
        :param instance: the objects.Instance to where the interface is being
            attached
        :param pci_reqs: A list of InstancePCIRequest objects describing the
            needed PCI devices
        :param request_groups: A list of RequestGroup objects describing the
            resources the port requests from placement
        :param request_level_params: A RequestLevelParams object describing the
            non group specific request of the port.
        :raises InterfaceAttachResourceAllocationFailed: if we failed to
            allocate resource in placement for the request
        :returns: A tuple of provider mappings and allocated resources or
            (None, None) if no resource allocation was needed for the request
        """

        if not request_groups:
            return None, None

        # restrict the resource request to the current compute node. The
        # compute node uuid is the uuid of the root provider of the node in
        # placement
        compute_node_uuid = objects.ComputeNode.get_by_nodename(
            context, instance.node).uuid
        # we can have multiple request groups, it would be enough to restrict
        # only one of them to the compute tree but for symetry we restrict
        # all of them
        for request_group in request_groups:
            request_group.in_tree = compute_node_uuid

        # NOTE(gibi): group policy is mandatory in a resource request if there
        # are multiple groups. The policy can only come from the flavor today
        # and a new flavor is not provided with an interface attach request and
        # the instance's current flavor might not have a policy. Still we are
        # attaching a single port where currently the two possible groups
        # (one for bandwidth and one for packet rate) will always be allocated
        # from different providers. So both possible policies (none, isolated)
        # are always fulfilled for this single port. We still has to specify
        # one so we specify the least restrictive now.
        rr = scheduler_utils.ResourceRequest.from_request_groups(
            request_groups, request_level_params, group_policy='none')
        res = self.reportclient.get_allocation_candidates(context, rr)
        alloc_reqs, provider_sums, version = res

        if not alloc_reqs:
            # no allocation candidates available, we run out of free resources
            raise exception.InterfaceAttachResourceAllocationFailed(
                instance_uuid=instance.uuid)

        # select one of the candidates and update the instance
        # allocation
        # TODO(gibi): We could loop over all possible candidates
        # if the first one selected here does not work due to race or due
        # to not having free PCI devices. However the latter is only
        # detected later in the interface attach code path.
        alloc_req = alloc_reqs[0]
        resources = alloc_req['allocations']
        provider_mappings = alloc_req['mappings']
        try:
            self.reportclient.add_resources_to_instance_allocation(
                context, instance.uuid, resources)
        except exception.AllocationUpdateFailed as e:
            # We lost a race. We could retry another candidate
            raise exception.InterfaceAttachResourceAllocationFailed(
                instance_uuid=instance.uuid) from e
        except (
            exception.ConsumerAllocationRetrievalFailed,
            keystone_exception.ClientException,
        ) as e:
            # These are non-recoverable errors so we should not retry
            raise exception.InterfaceAttachResourceAllocationFailed(
                instance_uuid=instance.uuid) from e

        try:
            update = (
                compute_utils.
                    update_pci_request_spec_with_allocated_interface_name)
            update(
                context, self.reportclient, pci_reqs.requests,
                provider_mappings)
        except (
            exception.AmbiguousResourceProviderForPCIRequest,
            exception.UnexpectedResourceProviderNameForPCIRequest
        ):
            # These are programing errors. So we clean up an re-raise to let
            # the request fail
            with excutils.save_and_reraise_exception():
                self.reportclient.remove_resources_from_instance_allocation(
                    context, instance.uuid, resources)

        return provider_mappings, resources

    # TODO(mriedem): There are likely race failures which can result in
    # NotFound and QuotaError exceptions getting traced as well.
    @messaging.expected_exceptions(
        # Do not log a traceback for user errors. We use Invalid generically
        # since this method can raise lots of different exceptions:
        # AttachInterfaceNotSupported
        # NetworkInterfaceTaggedAttachNotSupported
        # NetworkAmbiguous
        # PortNotUsable
        # PortInUse
        # PortNotUsableDNS
        # AttachSRIOVPortNotSupported
        # NetworksWithQoSPolicyNotSupported
        # InterfaceAttachResourceAllocationFailed
        exception.Invalid)
    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def attach_interface(self, context, instance, network_id, port_id,
                         requested_ip, tag):
        """Use hotplug to add an network adapter to an instance."""
        lockname = 'interface-%s-%s' % (instance.uuid, port_id)

        @utils.synchronized(lockname)
        def do_attach_interface(context, instance, network_id, port_id,
                                requested_ip, tag):
            return self._attach_interface(context, instance, network_id,
                                port_id, requested_ip, tag)

        return do_attach_interface(context, instance, network_id, port_id,
                                   requested_ip, tag)

    def _attach_interface(self, context, instance, network_id, port_id,
                          requested_ip, tag):
        if not self.driver.capabilities.get('supports_attach_interface',
                                            False):
            raise exception.AttachInterfaceNotSupported(
                instance_uuid=instance.uuid)
        if (tag and not
            self.driver.capabilities.get('supports_tagged_attach_interface',
                                         False)):
            raise exception.NetworkInterfaceTaggedAttachNotSupported()

        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.INTERFACE_ATTACH,
            phase=fields.NotificationPhase.START)

        bind_host_id = self.driver.network_binding_host_id(context, instance)

        requested_networks = objects.NetworkRequestList(
            objects=[
                objects.NetworkRequest(
                    network_id=network_id,
                    port_id=port_id,
                    address=requested_ip,
                    tag=tag,
                )
            ]
        )

        if len(requested_networks) != 1:
            LOG.warning(
                "Interface attach only supports one interface per attach "
                "request", instance=instance)
            raise exception.InterfaceAttachFailed(instance_uuid=instance.uuid)

        pci_numa_affinity_policy = hardware.get_pci_numa_policy_constraint(
            instance.flavor, instance.image_meta)
        pci_reqs = objects.InstancePCIRequests(
            requests=[], instance_uuid=instance.uuid)
        _, request_groups, req_lvl_params = (
            self.network_api.create_resource_requests(
                context,
                requested_networks,
                pci_reqs,
                affinity_policy=pci_numa_affinity_policy
            )
        )

        result = self._allocate_port_resource_for_instance(
            context, instance, pci_reqs, request_groups, req_lvl_params)
        provider_mappings, resources = result

        try:
            pci_device = self._claim_pci_device_for_interface_attach(
                context, instance, pci_reqs)
        except exception.InterfaceAttachPciClaimFailed:
            with excutils.save_and_reraise_exception():
                if resources:
                    # TODO(gibi): Instead of giving up we could try another
                    # allocation candidate from _allocate_resources() if any
                    self._deallocate_port_resource_for_instance(
                        context, instance, port_id, resources)

        instance.pci_requests.requests.extend(pci_reqs.requests)

        network_info = self.network_api.allocate_for_instance(
            context,
            instance,
            requested_networks,
            bind_host_id=bind_host_id,
            resource_provider_mapping=provider_mappings,
        )

        if len(network_info) != 1:
            LOG.error('allocate_for_instance returned %(ports)s '
                      'ports', {'ports': len(network_info)})
            # TODO(elod.illes): an instance.interface_attach.error notification
            # should be sent here
            raise exception.InterfaceAttachFailed(
                    instance_uuid=instance.uuid)
        image_meta = objects.ImageMeta.from_instance(instance)

        try:
            self.driver.attach_interface(context, instance, image_meta,
                                         network_info[0])
        except exception.NovaException as ex:
            port_id = network_info[0].get('id')
            LOG.warning("attach interface failed , try to deallocate "
                        "port %(port_id)s, reason: %(msg)s",
                        {'port_id': port_id, 'msg': ex},
                        instance=instance)
            self._deallocate_port_for_instance(
                context, instance, port_id, pci_device=pci_device)

            compute_utils.notify_about_instance_action(
                context, instance, self.host,
                action=fields.NotificationAction.INTERFACE_ATTACH,
                phase=fields.NotificationPhase.ERROR,
                exception=ex)

            raise exception.InterfaceAttachFailed(
                instance_uuid=instance.uuid)

        if pci_device:
            # NOTE(gibi): The _claim_pci_device_for_interface_attach() call
            # found a pci device but it only marked the device as claimed. The
            # periodic update_available_resource would move the device to
            # allocated state. But as driver.attach_interface() has been
            # succeeded we now know that the interface is also allocated
            # (used by) to the instance. So make sure the pci tracker also
            # tracks this device as allocated. This way we can avoid a possible
            # race condition when a detach arrives for a device that is only
            # in claimed state.
            self.rt.allocate_pci_devices_for_instance(context, instance)

        instance.save()

        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.INTERFACE_ATTACH,
            phase=fields.NotificationPhase.END)

        return network_info[0]

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def detach_interface(self, context, instance, port_id):
        """Detach a network adapter from an instance."""
        lockname = 'interface-%s-%s' % (instance.uuid, port_id)

        @utils.synchronized(lockname)
        def do_detach_interface(context, instance, port_id):
            self._detach_interface(context, instance, port_id)

        do_detach_interface(context, instance, port_id)

    def _detach_interface(self, context, instance, port_id):
        # NOTE(aarents): we need to refresh info cache from DB here,
        # as previous detach/attach lock holder just updated it.
        compute_utils.refresh_info_cache_for_instance(context, instance)
        network_info = instance.info_cache.network_info
        condemned = None
        for vif in network_info:
            if vif['id'] == port_id:
                condemned = vif
                break
        if condemned is None:
            raise exception.PortNotFound(_("Port %s is not "
                                           "attached") % port_id)

        pci_req = pci_req_module.get_instance_pci_request_from_vif(
            context, instance, condemned)

        pci_device = None
        if pci_req:
            pci_devices = [pci_device
                           for pci_device in instance.pci_devices.objects
                           if pci_device.request_id == pci_req.request_id]

            if not pci_devices:
                LOG.warning(
                    "Detach interface failed, port_id=%(port_id)s, "
                    "reason: PCI device not found for PCI request %(pci_req)s",
                    {'port_id': port_id, 'pci_req': pci_req})
                raise exception.InterfaceDetachFailed(
                    instance_uuid=instance.uuid)

            pci_device = pci_devices[0]

        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.INTERFACE_DETACH,
            phase=fields.NotificationPhase.START)

        try:
            self.driver.detach_interface(context, instance, condemned)
        except exception.NovaException as ex:
            # If the instance was deleted before the interface was detached,
            # just log it at debug.
            log_level = (logging.DEBUG
                         if isinstance(ex, exception.InstanceNotFound)
                         else logging.WARNING)
            LOG.log(log_level,
                    "Detach interface failed, port_id=%(port_id)s, reason: "
                    "%(msg)s", {'port_id': port_id, 'msg': ex},
                    instance=instance)
            raise exception.InterfaceDetachFailed(instance_uuid=instance.uuid)
        else:
            self._deallocate_port_for_instance(
                context, instance, port_id, raise_on_failure=True,
                pci_device=pci_device)

        instance.save()

        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.INTERFACE_DETACH,
            phase=fields.NotificationPhase.END)

    def _get_compute_info(self, context, host):
        return objects.ComputeNode.get_first_node_by_host_for_old_compat(
            context, host)

    @wrap_exception()
    def check_instance_shared_storage(self, ctxt, data):
        """Check if the instance files are shared

        :param ctxt: security context
        :param data: result of driver.check_instance_shared_storage_local

        Returns True if instance disks located on shared storage and
        False otherwise.
        """
        return self.driver.check_instance_shared_storage_remote(ctxt, data)

    def _dest_can_numa_live_migrate(self, dest_check_data, migration):
        # TODO(artom) If we have a libvirt driver we expect it to set
        # dst_supports_numa_live_migration, but we have to remove it if we
        # did not get a migration from the conductor, indicating that it
        # cannot send RPC 5.3. This check can be removed in RPC 6.0.
        if ('dst_supports_numa_live_migration' in dest_check_data and
                dest_check_data.dst_supports_numa_live_migration and
                not migration):
            delattr(dest_check_data, 'dst_supports_numa_live_migration')
        return dest_check_data

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def check_can_live_migrate_destination(self, ctxt, instance,
                                           block_migration, disk_over_commit,
                                           migration, limits):
        """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: dict of instance data
        :param block_migration: if true, prepare for block migration
                                if None, calculate it in driver
        :param disk_over_commit: if true, allow disk over commit
                                 if None, ignore disk usage checking
        :param migration: objects.Migration object for this live migration.
        :param limits: objects.SchedulerLimits object for this live migration.
        :returns: a LiveMigrateData object (hypervisor-dependent)
        """

        # Error out if this host cannot accept the new instance due
        # to anti-affinity. This check at this moment is not very accurate, as
        # multiple requests may be happening concurrently and miss the lock,
        # but when it works it provides a better user experience by failing
        # earlier. Also, it should be safe to explode here, error becomes
        # NoValidHost and instance status remains ACTIVE.
        try:
            self._validate_instance_group_policy(ctxt, instance)
        except exception.RescheduledException as e:
            msg = ("Failed to validate instance group policy "
                   "due to: {}".format(e))
            raise exception.MigrationPreCheckError(reason=msg)

        src_compute_info = obj_base.obj_to_primitive(
            self._get_compute_info(ctxt, instance.host))
        dst_compute_info = obj_base.obj_to_primitive(
            self._get_compute_info(ctxt, self.host))
        dest_check_data = self.driver.check_can_live_migrate_destination(ctxt,
            instance, src_compute_info, dst_compute_info,
            block_migration, disk_over_commit)
        dest_check_data = self._dest_can_numa_live_migrate(dest_check_data,
                                                           migration)
        LOG.debug('destination check data is %s', dest_check_data)
        try:
            allocs = self.reportclient.get_allocations_for_consumer(
                ctxt, instance.uuid)
            migrate_data = self.compute_rpcapi.check_can_live_migrate_source(
                ctxt, instance, dest_check_data)
            if ('src_supports_numa_live_migration' in migrate_data and
                    migrate_data.src_supports_numa_live_migration):
                migrate_data = self._live_migration_claim(
                    ctxt, instance, migrate_data, migration, limits, allocs)
            elif 'dst_supports_numa_live_migration' in dest_check_data:
                LOG.info('Destination was ready for NUMA live migration, '
                         'but source is either too old, or is set to an '
                         'older upgrade level.', instance=instance)
            if self.network_api.has_port_binding_extension(ctxt):
                # Create migrate_data vifs if not provided by driver.
                if 'vifs' not in migrate_data:
                    migrate_data.vifs = (
                        migrate_data_obj.
                        VIFMigrateData.create_skeleton_migrate_vifs(
                            instance.get_network_info()))
                # Claim PCI devices for VIFs on destination (if needed)
                port_id_to_pci = self._claim_pci_for_instance_vifs(
                    ctxt, instance)
                # Update migrate VIFs with the newly claimed PCI devices
                self._update_migrate_vifs_profile_with_pci(
                    migrate_data.vifs, port_id_to_pci)
        finally:
            self.driver.cleanup_live_migration_destination_check(ctxt,
                    dest_check_data)
        return migrate_data

    def _live_migration_claim(self, ctxt, instance, migrate_data,
                              migration, limits, allocs):
        """Runs on the destination and does a resources claim, if necessary.
        Currently, only NUMA live migrations require it.

        :param ctxt: Request context
        :param instance: The Instance being live migrated
        :param migrate_data: The MigrateData object for this live migration
        :param migration: The Migration object for this live migration
        :param limits: The SchedulerLimits object for this live migration
        :returns: migrate_data with dst_numa_info set if necessary
        """
        try:
            # NOTE(artom) We might have gotten here from _find_destination() in
            # the conductor live migrate task. At that point,
            # migration.dest_node is not set yet (nor should it be, we're still
            # looking for a destination, after all). Therefore, we cannot use
            # migration.dest_node here and must use self._get_nodename().
            claim = self.rt.live_migration_claim(
                ctxt, instance, self._get_nodename(instance), migration,
                limits, allocs)
            LOG.debug('Created live migration claim.', instance=instance)
        except exception.ComputeResourcesUnavailable as e:
            raise exception.MigrationPreCheckError(
                reason=e.format_message())
        return self.driver.post_claim_migrate_data(ctxt, instance,
                                                   migrate_data, claim)

    def _source_can_numa_live_migrate(self, ctxt, dest_check_data,
                                      source_check_data):
        # TODO(artom) Our virt driver may have told us that it supports NUMA
        # live migration. However, the following other conditions must be met
        # for a NUMA live migration to happen:
        # 1. We got a True dst_supports_numa_live_migration in
        #    dest_check_data, indicating that the dest virt driver supports
        #    NUMA live migration and that the conductor can send RPC 5.3 and
        #    that the destination compute manager can receive it.
        # 2. Ourselves, the source, can send RPC 5.3. There's no
        #    sentinel/parameter for this, so we just ask our rpcapi directly.
        # If any of these are not met, we need to remove the
        # src_supports_numa_live_migration flag from source_check_data to avoid
        # incorrectly initiating a NUMA live migration.
        # All of this can be removed in RPC 6.0/objects 2.0.
        can_numa_live_migrate = (
            'dst_supports_numa_live_migration' in dest_check_data and
            dest_check_data.dst_supports_numa_live_migration and
            self.compute_rpcapi.supports_numa_live_migration(ctxt))
        if ('src_supports_numa_live_migration' in source_check_data and
                source_check_data.src_supports_numa_live_migration and
                not can_numa_live_migrate):
            delattr(source_check_data, 'src_supports_numa_live_migration')
        return source_check_data

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def check_can_live_migrate_source(self, ctxt, instance, dest_check_data):
        """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 ctxt: security context
        :param instance: dict of instance data
        :param dest_check_data: result of check_can_live_migrate_destination
        :returns: a LiveMigrateData object
        """
        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
            ctxt, instance.uuid)
        is_volume_backed = compute_utils.is_volume_backed_instance(
            ctxt, instance, bdms)
        dest_check_data.is_volume_backed = is_volume_backed
        block_device_info = self._get_instance_block_device_info(
                            ctxt, instance, refresh_conn_info=False, bdms=bdms)
        result = self.driver.check_can_live_migrate_source(ctxt, instance,
                                                           dest_check_data,
                                                           block_device_info)
        result = self._source_can_numa_live_migrate(ctxt, dest_check_data,
                                                    result)
        LOG.debug('source check data is %s', result)
        return result

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def pre_live_migration(self, context, instance, disk, migrate_data):
        """Preparations for live migration at dest host.

        :param context: security context
        :param instance: dict of instance data
        :param disk: disk info of instance
        :param migrate_data: A dict or LiveMigrateData object holding data
                             required for live migration without shared
                             storage.
        :returns: migrate_data containing additional migration info
        """
        LOG.debug('pre_live_migration data is %s', migrate_data)

        # Error out if this host cannot accept the new instance due
        # to anti-affinity. At this point the migration is already in-progress,
        # so this is the definitive moment to abort due to the policy
        # violation. Also, it should be safe to explode here. The instance
        # status remains ACTIVE, migration status failed.
        self._validate_instance_group_policy(context, instance)

        migrate_data.old_vol_attachment_ids = {}
        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
            context, instance.uuid)
        network_info = self.network_api.get_instance_nw_info(context, instance)
        self._notify_about_instance_usage(
            context, instance, "live_migration.pre.start",
            network_info=network_info)
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_PRE,
            phase=fields.NotificationPhase.START, bdms=bdms)

        connector = None
        try:
            for bdm in bdms:
                if bdm.is_volume and bdm.attachment_id is not None:
                    # This bdm uses the new cinder v3.44 API.
                    # We will create a new attachment for this
                    # volume on this migration destination host. The old
                    # attachment will be deleted on the source host
                    # when the migration succeeds. The old attachment_id
                    # is stored in dict with the key being the bdm.volume_id
                    # so it can be restored on rollback.
                    #
                    # Also note that attachment_update is not needed as we
                    # are providing the connector in the create call.
                    if connector is None:
                        connector = self.driver.get_volume_connector(instance)
                    attach_ref = self.volume_api.attachment_create(
                        context, bdm.volume_id, bdm.instance_uuid,
                        connector=connector, mountpoint=bdm.device_name)

                    # save current attachment so we can detach it on success,
                    # or restore it on a rollback.
                    # NOTE(mdbooth): This data is no longer used by the source
                    # host since change Ibe9215c0. We can't remove it until we
                    # are sure the source host has been upgraded.
                    migrate_data.old_vol_attachment_ids[bdm.volume_id] = \
                        bdm.attachment_id

                    # update the bdm with the new attachment_id.
                    bdm.attachment_id = attach_ref['id']
                    bdm.save()

            block_device_info = self._get_instance_block_device_info(
                                context, instance, refresh_conn_info=True,
                                bdms=bdms)

            # The driver pre_live_migration will plug vifs on the host
            migrate_data = self.driver.pre_live_migration(context,
                                           instance,
                                           block_device_info,
                                           network_info,
                                           disk,
                                           migrate_data)
            LOG.debug('driver pre_live_migration data is %s', migrate_data)
            # driver.pre_live_migration is what plugs vifs on the destination
            # host so now we can set the wait_for_vif_plugged flag in the
            # migrate_data object which the source compute will use to
            # determine if it should wait for a 'network-vif-plugged' event
            # from neutron before starting the actual guest transfer in the
            # hypervisor
            using_multiple_port_bindings = (
                'vifs' in migrate_data and migrate_data.vifs)
            migrate_data.wait_for_vif_plugged = (
                CONF.compute.live_migration_wait_for_vif_plug and
                using_multiple_port_bindings
            )

            # NOTE(tr3buchet): setup networks on destination host
            self.network_api.setup_networks_on_host(context, instance,
                                                             self.host)

            # NOTE(lyarwood): The above call to driver.pre_live_migration
            # can result in the virt drivers attempting to stash additional
            # metadata into the connection_info of the underlying bdm.
            # Ensure this is saved to the database by calling .save() against
            # the driver BDMs we passed down via block_device_info.
            for driver_bdm in block_device_info['block_device_mapping']:
                driver_bdm.save()

        except Exception:
            # If we raise, migrate_data with the updated attachment ids
            # will not be returned to the source host for rollback.
            # So we need to rollback new attachments here.
            with excutils.save_and_reraise_exception():
                old_attachments = migrate_data.old_vol_attachment_ids
                for bdm in bdms:
                    if (bdm.is_volume and bdm.attachment_id is not None and
                            bdm.volume_id in old_attachments):
                        self.volume_api.attachment_delete(context,
                                                          bdm.attachment_id)
                        bdm.attachment_id = old_attachments[bdm.volume_id]
                        bdm.save()

        # Volume connections are complete, tell cinder that all the
        # attachments have completed.
        for bdm in bdms:
            if bdm.is_volume and bdm.attachment_id is not None:
                self.volume_api.attachment_complete(context,
                                                    bdm.attachment_id)

        self._notify_about_instance_usage(
                     context, instance, "live_migration.pre.end",
                     network_info=network_info)
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_PRE,
            phase=fields.NotificationPhase.END, bdms=bdms)

        LOG.debug('pre_live_migration result data is %s', migrate_data)
        return migrate_data

    @staticmethod
    def _neutron_failed_live_migration_callback(event_name, instance):
        msg = ('Neutron reported failure during live migration '
               'with %(event)s for instance %(uuid)s')
        msg_args = {'event': event_name, 'uuid': instance.uuid}
        if CONF.vif_plugging_is_fatal:
            raise exception.VirtualInterfacePlugException(msg % msg_args)
        LOG.error(msg, msg_args)

    @staticmethod
    def _get_neutron_events_for_live_migration(instance):
        # We don't generate events if CONF.vif_plugging_timeout=0
        # meaning that the operator disabled using them.
        if CONF.vif_plugging_timeout:
            return (instance.get_network_info()
                    .get_live_migration_plug_time_events())
        else:
            return []

    def _cleanup_pre_live_migration(self, context, dest, instance,
                                    migration, migrate_data, source_bdms):
        """Helper method for when pre_live_migration fails

        Sets the migration status to "error" and rolls back the live migration
        setup on the destination host.

        :param context: The user request context.
        :type context: nova.context.RequestContext
        :param dest: The live migration destination hostname.
        :type dest: str
        :param instance: The instance being live migrated.
        :type instance: nova.objects.Instance
        :param migration: The migration record tracking this live migration.
        :type migration: nova.objects.Migration
        :param migrate_data: Data about the live migration, populated from
                             the destination host.
        :type migrate_data: Subclass of nova.objects.LiveMigrateData
        :param source_bdms: BDMs prior to modification by the destination
                            compute host. Set by _do_live_migration and not
                            part of the callback interface, so this is never
                            None
        """
        self._set_migration_status(migration, 'error')
        # Make sure we set this for _rollback_live_migration()
        # so it can find it, as expected if it was called later
        migrate_data.migration = migration
        self._rollback_live_migration(context, instance, dest,
                                      migrate_data=migrate_data,
                                      source_bdms=source_bdms,
                                      pre_live_migration=True)

    def _do_pre_live_migration_from_source(self, context, dest, instance,
                                           block_migration, migration,
                                           migrate_data, source_bdms):
        """Prepares for pre-live-migration on the source host and calls dest

        Will setup a callback networking event handler (if configured) and
        then call the dest host's pre_live_migration method to prepare the
        dest host for live migration (plugs vifs, connect volumes, etc).

        _rollback_live_migration (on the source) will be called if
        pre_live_migration (on the dest) fails.

        :param context: nova auth request context for this operation
        :param dest: name of the destination compute service host
        :param instance: Instance object being live migrated
        :param block_migration: If true, prepare for block migration.
        :param migration: Migration object tracking this operation
        :param migrate_data: MigrateData object for this operation populated
            by the destination host compute driver as part of the
            check_can_live_migrate_destination call.
        :param source_bdms: BlockDeviceMappingList of BDMs currently attached
            to the instance from the source host.
        :returns: MigrateData object which is a modified version of the
            ``migrate_data`` argument from the compute driver on the dest
            host during the ``pre_live_migration`` call.
        :raises: MigrationError if waiting for the network-vif-plugged event
            timed out and is fatal.
        """
        class _BreakWaitForInstanceEvent(Exception):
            """Used as a signal to stop waiting for the network-vif-plugged
            event when we discover that
            [compute]/live_migration_wait_for_vif_plug is not set on the
            destination.
            """
            pass

        events = self._get_neutron_events_for_live_migration(instance)
        try:
            if ('block_migration' in migrate_data and
                    migrate_data.block_migration):
                block_device_info = self._get_instance_block_device_info(
                    context, instance, bdms=source_bdms)
                disk = self.driver.get_instance_disk_info(
                    instance, block_device_info=block_device_info)
            else:
                disk = None

            deadline = CONF.vif_plugging_timeout
            error_cb = self._neutron_failed_live_migration_callback
            # In order to avoid a race with the vif plugging that the virt
            # driver does on the destination host, we register our events
            # to wait for before calling pre_live_migration. Then if the
            # dest host reports back that we shouldn't wait, we can break
            # out of the context manager using _BreakWaitForInstanceEvent.
            with self.virtapi.wait_for_instance_event(
                    instance, events, deadline=deadline,
                    error_callback=error_cb):
                with timeutils.StopWatch() as timer:
                    # TODO(mriedem): The "block_migration" parameter passed
                    # here is not actually used in pre_live_migration but it
                    # is not optional in the RPC interface either.
                    migrate_data = self.compute_rpcapi.pre_live_migration(
                        context, instance,
                        block_migration, disk, dest, migrate_data)
                LOG.info('Took %0.2f seconds for pre_live_migration on '
                         'destination host %s.',
                         timer.elapsed(), dest, instance=instance)
                wait_for_vif_plugged = (
                    'wait_for_vif_plugged' in migrate_data and
                    migrate_data.wait_for_vif_plugged)
                if events and not wait_for_vif_plugged:
                    raise _BreakWaitForInstanceEvent
        except _BreakWaitForInstanceEvent:
            if events:
                LOG.debug('Not waiting for events after pre_live_migration: '
                          '%s. ', events, instance=instance)
        except exception.VirtualInterfacePlugException:
            with excutils.save_and_reraise_exception():
                LOG.exception('Failed waiting for network virtual interfaces '
                              'to be plugged on the destination host %s.',
                              dest, instance=instance)
                self._cleanup_pre_live_migration(
                    context, dest, instance, migration, migrate_data,
                    source_bdms)
        except eventlet.timeout.Timeout:
            # We only get here if wait_for_vif_plugged is True which means
            # live_migration_wait_for_vif_plug=True on the destination host.
            msg = (
                'Timed out waiting for events: %(events)s. If these timeouts '
                'are a persistent issue it could mean the networking backend '
                'on host %(dest)s does not support sending these events '
                'unless there are port binding host changes which does not '
                'happen at this point in the live migration process. You may '
                'need to disable the live_migration_wait_for_vif_plug option '
                'on host %(dest)s.')
            subs = {'events': events, 'dest': dest}
            LOG.warning(msg, subs, instance=instance)
            if CONF.vif_plugging_is_fatal:
                self._cleanup_pre_live_migration(
                    context, dest, instance, migration, migrate_data,
                    source_bdms)
                raise exception.MigrationError(reason=msg % subs)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception('Pre live migration failed at %s',
                              dest, instance=instance)
                self._cleanup_pre_live_migration(
                    context, dest, instance, migration, migrate_data,
                    source_bdms)
        return migrate_data

    def _do_live_migration(self, context, dest, instance, block_migration,
                           migration, migrate_data):
        # NOTE(danms): We should enhance the RT to account for migrations
        # and use the status field to denote when the accounting has been
        # done on source/destination. For now, this is just here for status
        # reporting
        self._set_migration_status(migration, 'preparing')
        source_bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                context, instance.uuid)

        migrate_data = self._do_pre_live_migration_from_source(
            context, dest, instance, block_migration, migration, migrate_data,
            source_bdms)

        # Set migrate_data.migration because that is how _post_live_migration
        # and _rollback_live_migration get the migration object for cleanup.
        # Yes this is gross but changing the _post_live_migration and
        # _rollback_live_migration interfaces would also mean changing how the
        # virt drivers call them from the driver.live_migration method, i.e.
        # we would have to pass the migration object through the driver (or
        # consider using a partial but some do not like that pattern).
        migrate_data.migration = migration

        # NOTE(Kevin_Zheng): Pop the migration from the waiting queue
        # if it exist in the queue, then we are good to moving on, if
        # not, some other process must have aborted it, then we should
        # rollback.
        try:
            self._waiting_live_migrations.pop(instance.uuid)
        except KeyError:
            LOG.debug('Migration %s aborted by another process, rollback.',
                      migration.uuid, instance=instance)
            self._rollback_live_migration(context, instance, dest,
                                          migrate_data, 'cancelled',
                                          source_bdms=source_bdms)
            self._notify_live_migrate_abort_end(context, instance)
            return

        self._set_migration_status(migration, 'running')

        # NOTE(mdbooth): pre_live_migration will update connection_info and
        # attachment_id on all volume BDMS to reflect the new destination
        # host attachment. We fetch BDMs before that to retain connection_info
        # and attachment_id relating to the source host for post migration
        # cleanup.
        post_live_migration = functools.partial(
            self._post_live_migration_update_host, source_bdms=source_bdms
            )
        rollback_live_migration = functools.partial(
            self._rollback_live_migration, source_bdms=source_bdms)

        LOG.debug('live_migration data is %s', migrate_data)
        try:
            self.driver.live_migration(context, instance, dest,
                                       post_live_migration,
                                       rollback_live_migration,
                                       block_migration, migrate_data)
        except Exception:
            LOG.exception('Live migration failed.', instance=instance)
            with excutils.save_and_reraise_exception():
                # Put instance and migration into error state,
                # as its almost certainly too late to rollback
                self._set_migration_status(migration, 'error')
                # first refresh instance as it may have got updated by
                # post_live_migration_at_destination
                instance.refresh()
                self._set_instance_obj_error_state(instance,
                                                   clean_task_state=True)

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @errors_out_migration
    @wrap_instance_fault
    def live_migration(self, context, dest, instance, block_migration,
                       migration, migrate_data):
        """Executing live migration.

        :param context: security context
        :param dest: destination host
        :param instance: a nova.objects.instance.Instance object
        :param block_migration: if true, prepare for block migration
        :param migration: an nova.objects.Migration object
        :param migrate_data: implementation specific params

        """
        self._set_migration_status(migration, 'queued')
        # NOTE(Kevin_Zheng): Submit the live_migration job to the pool and
        # put the returned Future object into dict mapped with migration.uuid
        # in order to be able to track and abort it in the future.
        self._waiting_live_migrations[instance.uuid] = (None, None)
        try:
            future = self._live_migration_executor.submit(
                self._do_live_migration, context, dest, instance,
                block_migration, migration, migrate_data)
            self._waiting_live_migrations[instance.uuid] = (migration, future)
        except RuntimeError:
            # GreenThreadPoolExecutor.submit will raise RuntimeError if the
            # pool is shutdown, which happens in
            # _cleanup_live_migrations_in_pool.
            LOG.info('Migration %s failed to submit as the compute service '
                     'is shutting down.', migration.uuid, instance=instance)
            raise exception.LiveMigrationNotSubmitted(
                migration_uuid=migration.uuid, instance_uuid=instance.uuid)

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def live_migration_force_complete(self, context, instance):
        """Force live migration to complete.

        :param context: Security context
        :param instance: The instance that is being migrated
        """

        self._notify_about_instance_usage(
            context, instance, 'live.migration.force.complete.start')
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_FORCE_COMPLETE,
            phase=fields.NotificationPhase.START)
        self.driver.live_migration_force_complete(instance)
        self._notify_about_instance_usage(
            context, instance, 'live.migration.force.complete.end')
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_FORCE_COMPLETE,
            phase=fields.NotificationPhase.END)

    def _notify_live_migrate_abort_end(self, context, instance):
        self._notify_about_instance_usage(
            context, instance, 'live.migration.abort.end')
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_ABORT,
            phase=fields.NotificationPhase.END)

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def live_migration_abort(self, context, instance, migration_id):
        """Abort an in-progress live migration.

        :param context: Security context
        :param instance: The instance that is being migrated
        :param migration_id: ID of in-progress live migration

        """
        self._notify_about_instance_usage(
            context, instance, 'live.migration.abort.start')
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_ABORT,
            phase=fields.NotificationPhase.START)
        # NOTE(Kevin_Zheng): Pop the migration out from the queue, this might
        # lead to 3 scenarios:
        # 1. The selected migration is still in queue, and the future.cancel()
        #    succeed, then the abort action is succeed, mark the migration
        #    status to 'cancelled'.
        # 2. The selected migration is still in queue, but the future.cancel()
        #    failed, then the _do_live_migration() has started executing, and
        #    the migration status is 'preparing', then we just pop it from the
        #    queue, and the migration process will handle it later. And the
        #    migration status couldn't be 'running' in this scenario because
        #    if _do_live_migration has started executing and we've already
        #    popped it from the queue and set the migration status to
        #    'running' at this point, popping it here will raise KeyError at
        #    which point we check if it's running and if so, we abort the old
        #    way.
        # 3. The selected migration is not in the queue, then the migration
        #    status is 'running', let the driver handle it.
        try:
            migration, future = (
                self._waiting_live_migrations.pop(instance.uuid))
            if future and future.cancel():
                # If we got here, we've successfully dropped a queued
                # migration from the queue, so _do_live_migration won't run
                # and we only need to revert minor changes introduced by Nova
                # control plane (port bindings, resource allocations and
                # instance's PCI devices), restore VM's state, set the
                # migration's status to cancelled and send the notification.
                # If Future.cancel() fails, it means _do_live_migration is
                # running and the migration status is preparing, and
                # _do_live_migration() itself will attempt to pop the queued
                # migration, hit a KeyError, and rollback, set the migration
                # to cancelled and send the live.migration.abort.end
                # notification.
                self._revert_allocation(context, instance, migration)
                try:
                    # This call will delete any inactive destination host
                    # port bindings.
                    self.network_api.setup_networks_on_host(
                        context, instance, host=migration.dest_compute,
                        teardown=True)
                except exception.PortBindingDeletionFailed as e:
                    # Removing the inactive port bindings from the destination
                    # host is not critical so just log an error but don't fail.
                    LOG.error(
                        'Network cleanup failed for destination host %s '
                        'during live migration rollback. You may need to '
                        'manually clean up resources in the network service. '
                        'Error: %s', migration.dest_compute, str(e))
                except Exception:
                    with excutils.save_and_reraise_exception():
                        LOG.exception(
                            'An error occurred while cleaning up networking '
                            'during live migration rollback.',
                            instance=instance)
                instance.task_state = None
                instance.save(expected_task_state=[task_states.MIGRATING])
                self._set_migration_status(migration, 'cancelled')
        except KeyError:
            migration = objects.Migration.get_by_id(context, migration_id)
            if migration.status != 'running':
                raise exception.InvalidMigrationState(
                    migration_id=migration_id, instance_uuid=instance.uuid,
                    state=migration.status, method='abort live migration')
            self.driver.live_migration_abort(instance)
        self._notify_live_migrate_abort_end(context, instance)

    def _live_migration_cleanup_flags(self, migrate_data, migr_ctxt=None):
        """Determine whether disks, instance path or other resources
        need to be cleaned up after live migration (at source on success,
        at destination on rollback)

        Block migration needs empty image at destination host before migration
        starts, so if any failure occurs, any empty images has to be deleted.

        Also Volume backed live migration w/o shared storage needs to delete
        newly created instance-xxx dir on the destination as a part of its
        rollback process

        There may be other resources which need cleanup; currently this is
        limited to vPMEM devices with the libvirt driver.

        :param migrate_data: implementation specific data
        :param migr_ctxt: specific resources stored in migration_context
        :returns: (bool, bool) -- do_cleanup, destroy_disks
        """
        # NOTE(pkoniszewski): block migration specific params are set inside
        # migrate_data objects for drivers that expose block live migration
        # information (i.e. Libvirt, HyperV). For other drivers cleanup is not
        # needed.
        do_cleanup = False
        destroy_disks = False
        if isinstance(migrate_data, migrate_data_obj.LibvirtLiveMigrateData):
            has_vpmem = False
            if migr_ctxt and migr_ctxt.old_resources:
                for resource in migr_ctxt.old_resources:
                    if ('metadata' in resource and
                        isinstance(resource.metadata,
                                   objects.LibvirtVPMEMDevice)):
                        has_vpmem = True
                        break
            # No instance booting at source host, but instance dir
            # must be deleted for preparing next block migration
            # must be deleted for preparing next live migration w/o shared
            # storage
            # vpmem must be cleaned
            do_cleanup = not migrate_data.is_shared_instance_path or has_vpmem
            destroy_disks = not migrate_data.is_shared_block_storage
        elif isinstance(migrate_data, migrate_data_obj.HyperVLiveMigrateData):
            # NOTE(claudiub): We need to cleanup any zombie Planned VM.
            do_cleanup = True
            destroy_disks = not migrate_data.is_shared_instance_path

        return (do_cleanup, destroy_disks)

    def _post_live_migration_remove_source_vol_connections(
            self, context, instance, source_bdms):
        """Disconnect volume connections from the source host during
        _post_live_migration.

        :param context: nova auth RequestContext
        :param instance: Instance object being live migrated
        :param source_bdms: BlockDeviceMappingList representing the attached
            volumes with connection_info set for the source host
        """
        # Detaching volumes.
        connector = None
        for bdm in source_bdms:
            if bdm.is_volume:
                # Detaching volumes is a call to an external API that can fail.
                # If it does, we need to handle it gracefully so that the call
                # to post_live_migration_at_destination - where we set instance
                # host and task state - still happens. We need to rethink the
                # current approach of setting instance host and task state
                # AFTER a whole bunch of things that could fail in unhandled
                # ways, but that is left as a TODO(artom).
                try:
                    if bdm.attachment_id is None:
                        # Prior to cinder v3.44:
                        # We don't want to actually mark the volume detached,
                        # or delete the bdm, just remove the connection from
                        # this host.
                        #
                        # remove the volume connection without detaching from
                        # hypervisor because the instance is not running
                        # anymore on the current host
                        if connector is None:
                            connector = self.driver.get_volume_connector(
                                instance)
                        self.volume_api.terminate_connection(context,
                                                             bdm.volume_id,
                                                             connector)
                    else:
                        # cinder v3.44 api flow - delete the old attachment
                        # for the source host
                        self.volume_api.attachment_delete(context,
                                                          bdm.attachment_id)

                except Exception as e:
                    if bdm.attachment_id is None:
                        LOG.error('Connection for volume %s not terminated on '
                                  'source host %s during post_live_migration: '
                                  '%s', bdm.volume_id, self.host,
                                  str(e), instance=instance)
                    else:
                        LOG.error('Volume attachment %s not deleted on source '
                                  'host %s during post_live_migration: %s',
                                  bdm.attachment_id, self.host,
                                  str(e), instance=instance)

    # TODO(sean-k-mooney): add typing
    def _post_live_migration_update_host(
        self, ctxt, instance, dest, block_migration=False,
        migrate_data=None, source_bdms=None
    ):
        try:
            self._post_live_migration(
                ctxt, instance, dest, block_migration, migrate_data,
                source_bdms)
        except Exception:
            # Restore the instance object
            node_name = None
            try:
                # get node name of compute, where instance will be
                # running after migration, that is destination host
                compute_node = self._get_compute_info(ctxt, dest)
                node_name = compute_node.hypervisor_hostname
            except exception.ComputeHostNotFound:
                LOG.exception('Failed to get compute_info for %s', dest)

            # we can never rollback from post live migration and we can only
            # get here if the instance is running on the dest so we ensure
            # the instance.host is set correctly and reraise the original
            # exception unmodified.
            if instance.host != dest:
                # apply saves the new fields while drop actually removes the
                # migration context from the instance, so migration persists.
                instance.apply_migration_context()
                instance.drop_migration_context()
                instance.host = dest
                instance.task_state = None
                instance.node = node_name
                instance.progress = 0
                instance.save()
            raise

    @wrap_exception()
    @wrap_instance_fault
    def _post_live_migration(self, ctxt, instance, dest,
                             block_migration=False, migrate_data=None,
                             source_bdms=None):
        """Post operations for live migration.

        This method is called from live_migration
        and mainly updating database record.

        :param ctxt: security context
        :param instance: instance object
        :param dest: destination host
        :param block_migration: if true, prepare for block migration
        :param migrate_data: if not None, it is a dict which has data
        :param source_bdms: BDMs prior to modification by the destination
                            compute host. Set by _do_live_migration and not
                            part of the callback interface, so this is never
                            None
        required for live migration without shared storage

        """
        LOG.info('_post_live_migration() is started..',
                 instance=instance)

        # Cleanup source host post live-migration
        block_device_info = self._get_instance_block_device_info(
                            ctxt, instance, bdms=source_bdms)
        self.driver.post_live_migration(ctxt, instance, block_device_info,
                                        migrate_data)

        # Disconnect volumes from this (the source) host.
        self._post_live_migration_remove_source_vol_connections(
            ctxt, instance, source_bdms)

        # NOTE(artom) At this point in time we have not bound the ports to the
        # destination host yet (this happens in migrate_instance_start()
        # below). Therefore, the "old" source network info that's still in the
        # instance info cache is safe to use here, since it'll be used below
        # during driver.post_live_migration_at_source() to unplug the VIFs on
        # the source.
        network_info = instance.get_network_info()

        self._notify_about_instance_usage(ctxt, instance,
                                          "live_migration._post.start",
                                          network_info=network_info)
        compute_utils.notify_about_instance_action(
            ctxt, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_POST,
            phase=fields.NotificationPhase.START)

        migration = objects.Migration(
            source_compute=self.host, dest_compute=dest,
        )
        # For neutron, migrate_instance_start will activate the destination
        # host port bindings, if there are any created by conductor before live
        # migration started.
        self.network_api.migrate_instance_start(ctxt,
                                                instance,
                                                migration)

        destroy_vifs = False
        try:
            # It's possible that the vif type changed on the destination
            # host and is already bound and active, so we need to use the
            # stashed source vifs in migrate_data.vifs (if present) to unplug
            # on the source host.
            unplug_nw_info = network_info
            if migrate_data and 'vifs' in migrate_data:
                nw_info = []
                for migrate_vif in migrate_data.vifs:
                    nw_info.append(migrate_vif.source_vif)
                unplug_nw_info = network_model.NetworkInfo.hydrate(nw_info)
                LOG.debug('Calling driver.post_live_migration_at_source '
                          'with original source VIFs from migrate_data: %s',
                          unplug_nw_info, instance=instance)
            self.driver.post_live_migration_at_source(ctxt, instance,
                                                      unplug_nw_info)
        except NotImplementedError as ex:
            LOG.debug(ex, instance=instance)
            # For all hypervisors other than libvirt, there is a possibility
            # they are unplugging networks from source node in the cleanup
            # method
            destroy_vifs = True

        # Free instance allocations on source before claims are allocated on
        # destination node
        self.rt.free_pci_device_allocations_for_instance(ctxt, instance)
        # NOTE(danms): Save source node before calling post method on
        # destination, which will update it
        source_node = instance.node

        do_cleanup, destroy_disks = self._live_migration_cleanup_flags(
            migrate_data, migr_ctxt=instance.migration_context)

        if do_cleanup:
            LOG.debug('Calling driver.cleanup from _post_live_migration',
                      instance=instance)
            self.driver.cleanup(ctxt, instance, unplug_nw_info,
                                destroy_disks=destroy_disks,
                                migrate_data=migrate_data,
                                destroy_vifs=destroy_vifs)

        # Define domain at destination host, without doing it,
        # pause/suspend/terminate do not work.
        post_at_dest_success = True
        try:
            self.compute_rpcapi.post_live_migration_at_destination(ctxt,
                    instance, block_migration, dest)
        except Exception as error:
            post_at_dest_success = False
            # We don't want to break _post_live_migration() if
            # post_live_migration_at_destination() fails as it should never
            # affect cleaning up source node.
            LOG.exception("Post live migration at destination %s failed",
                          dest, instance=instance, error=error)

        self.instance_events.clear_events_for_instance(instance)

        # NOTE(timello): make sure we update available resources on source
        # host even before next periodic task.
        self.update_available_resource(ctxt)

        self._update_scheduler_instance_info(ctxt, instance)
        self._notify_about_instance_usage(ctxt, instance,
                                          "live_migration._post.end",
                                          network_info=network_info)
        compute_utils.notify_about_instance_action(
            ctxt, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_POST,
            phase=fields.NotificationPhase.END)
        if post_at_dest_success:
            LOG.info('Migrating instance to %s finished successfully.',
                     dest, instance=instance)

        self._clean_instance_console_tokens(ctxt, instance)
        if migrate_data and migrate_data.obj_attr_is_set('migration'):
            migrate_data.migration.status = 'completed'
            migrate_data.migration.save()
            self._delete_allocation_after_move(ctxt,
                                               instance,
                                               migrate_data.migration)
        else:
            # We didn't have data on a migration, which means we can't
            # look up to see if we had new-style migration-based
            # allocations. This should really only happen in cases of
            # a buggy virt driver. Log a warning so we know it happened.
            LOG.warning('Live migration ended with no migrate_data '
                        'record. Unable to clean up migration-based '
                        'allocations for node %s which is almost certainly '
                        'not an expected situation.', source_node,
                        instance=instance)

    def _consoles_enabled(self):
        """Returns whether a console is enable."""
        return (CONF.vnc.enabled or CONF.spice.enabled or
                CONF.rdp.enabled or CONF.serial_console.enabled or
                CONF.mks.enabled)

    def _clean_instance_console_tokens(self, ctxt, instance):
        """Clean console tokens stored for an instance."""
        # If the database backend isn't in use, don't bother trying to clean
        # tokens.
        if self._consoles_enabled():
            objects.ConsoleAuthToken.\
                clean_console_auths_for_instance(ctxt, instance.uuid)

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def post_live_migration_at_destination(self, context, instance,
                                           block_migration):
        """Post operations for live migration .

        :param context: security context
        :param instance: Instance dict
        :param block_migration: if true, prepare for block migration

        """
        LOG.info('Post operation of migration started',
                 instance=instance)

        # NOTE(tr3buchet): setup networks on destination host
        #                  this is called a second time because
        #                  multi_host does not create the bridge in
        #                  plug_vifs
        # NOTE(mriedem): This is a no-op for neutron.
        self.network_api.setup_networks_on_host(context, instance,
                                                         self.host)
        migration = objects.Migration(
            source_compute=instance.host,
            dest_compute=self.host,
            migration_type=fields.MigrationType.LIVE_MIGRATION)
        self.network_api.migrate_instance_finish(
            context, instance, migration, provider_mappings=None)

        network_info = self.network_api.get_instance_nw_info(context, instance)
        self._notify_about_instance_usage(
                     context, instance, "live_migration.post.dest.start",
                     network_info=network_info)
        compute_utils.notify_about_instance_action(context, instance,
                self.host,
                action=fields.NotificationAction.LIVE_MIGRATION_POST_DEST,
                phase=fields.NotificationPhase.START)
        block_device_info = self._get_instance_block_device_info(context,
                                                                 instance)
        # Allocate the claimed PCI resources at destination.
        self.rt.allocate_pci_devices_for_instance(context, instance)

        try:
            self.driver.post_live_migration_at_destination(
                context, instance, network_info, block_migration,
                block_device_info)
        except Exception:
            with excutils.save_and_reraise_exception():
                instance.vm_state = vm_states.ERROR
                LOG.error('Unexpected error during post live migration at '
                          'destination host.', instance=instance)
        finally:
            # Restore instance state and update host
            current_power_state = self._get_power_state(instance)
            node_name = None
            prev_host = instance.host
            try:
                compute_node = self._get_compute_info(context, self.host)
                node_name = compute_node.hypervisor_hostname
            except exception.ComputeHostNotFound:
                LOG.exception('Failed to get compute_info for %s', self.host)
            finally:
                # NOTE(artom) We need to apply the migration context here
                # regardless of whether the driver's
                # post_live_migration_at_destination succeeded or not: the
                # instance is on the destination, potentially with a new NUMA
                # topology and resource usage. We need to persist that.
                # NOTE(artom) Apply followed by drop looks weird, but apply
                # just saves the new fields while drop actually removes the
                # migration context from the instance.
                instance.apply_migration_context()
                instance.drop_migration_context()
                instance.host = self.host
                instance.power_state = current_power_state
                instance.task_state = None
                instance.node = node_name
                instance.progress = 0
                instance.save(expected_task_state=task_states.MIGRATING)

        # NOTE(tr3buchet): tear down networks on source host (nova-net)
        # NOTE(mriedem): For neutron, this will delete any inactive source
        # host port bindings.
        try:
            self.network_api.setup_networks_on_host(context, instance,
                                                    prev_host, teardown=True)
        except exception.PortBindingDeletionFailed as e:
            # Removing the inactive port bindings from the source host is not
            # critical so just log an error but don't fail.
            LOG.error('Network cleanup failed for source host %s during post '
                      'live migration. You may need to manually clean up '
                      'resources in the network service. Error: %s',
                      prev_host, str(e))
        # NOTE(vish): this is necessary to update dhcp for nova-network
        # NOTE(mriedem): This is a no-op for neutron.
        self.network_api.setup_networks_on_host(context, instance, self.host)
        self._notify_about_instance_usage(
                     context, instance, "live_migration.post.dest.end",
                     network_info=network_info)
        compute_utils.notify_about_instance_action(context, instance,
                self.host,
                action=fields.NotificationAction.LIVE_MIGRATION_POST_DEST,
                phase=fields.NotificationPhase.END)

    def _remove_remote_volume_connections(self, context, dest, bdms, instance):
        """Rollback remote volume connections on the dest"""
        for bdm in bdms:
            try:
                # remove the connection on the destination host
                # NOTE(lyarwood): This actually calls the cinderv2
                # os-terminate_connection API if required.
                self.compute_rpcapi.remove_volume_connection(
                        context, instance, bdm.volume_id, dest)
            except Exception:
                LOG.warning("Ignoring exception while attempting "
                            "to rollback volume connections for "
                            "volume %s on host %s.", bdm.volume_id,
                            dest, instance=instance)

    def _rollback_volume_bdms(self, context, bdms, original_bdms, instance):
        """Rollback the connection_info and attachment_id for each bdm"""
        original_bdms_by_volid = {bdm.volume_id: bdm for bdm in original_bdms
                                  if bdm.is_volume}
        for bdm in bdms:
            try:
                original_bdm = original_bdms_by_volid[bdm.volume_id]
                # NOTE(lyarwood): Only delete the referenced attachment if it
                # is different to the original in order to avoid accidentally
                # removing the source host volume attachment after it has
                # already been rolled back by a failure in pre_live_migration.
                if (bdm.attachment_id and original_bdm.attachment_id and
                    bdm.attachment_id != original_bdm.attachment_id):
                    # NOTE(lyarwood): 3.44 cinder api flow. Delete the
                    # attachment used by the bdm and reset it to that of
                    # the original bdm.
                    self.volume_api.attachment_delete(context,
                                                      bdm.attachment_id)
                    bdm.attachment_id = original_bdm.attachment_id
                # NOTE(lyarwood): Reset the connection_info to the original
                bdm.connection_info = original_bdm.connection_info
                bdm.save()
            except cinder_exception.ClientException:
                LOG.warning("Ignoring cinderclient exception when "
                            "attempting to delete attachment %s for volume "
                            "%s while rolling back volume bdms.",
                            bdm.attachment_id, bdm.volume_id,
                            instance=instance)
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception("Exception while attempting to rollback "
                                  "BDM for volume %s.", bdm.volume_id,
                                  instance=instance)

    @wrap_exception()
    @wrap_instance_fault
    def _rollback_live_migration(self, context, instance,
                                 dest, migrate_data=None,
                                 migration_status='failed',
                                 source_bdms=None,
                                 pre_live_migration=False):
        """Recovers Instance/volume state from migrating -> running.

        :param context: security context
        :param instance: nova.objects.instance.Instance object
        :param dest:
            This method is called from live migration src host.
            This param specifies destination host.
        :param migrate_data:
            if not none, contains implementation specific data.
        :param migration_status:
            Contains the status we want to set for the migration object
        :param source_bdms: BDMs prior to modification by the destination
                            compute host. Set by _do_live_migration and not
                            part of the callback interface, so this is never
                            None

        """
        # NOTE(gibi): We need to refresh pci_requests of the instance as it
        # might be changed by the conductor during scheduling based on the
        # selected destination host. If the instance has SRIOV ports with
        # resource request then the LiveMigrationTask._find_destination call
        # updated the instance.pci_requests.requests[].spec with the SRIOV PF
        # device name to be used on the destination host. As the migration is
        # rolling back to the source host now we don't want to persist the
        # destination host related changes in the DB.
        instance.pci_requests = \
            objects.InstancePCIRequests.get_by_instance_uuid(
                context, instance.uuid)

        if (isinstance(migrate_data, migrate_data_obj.LiveMigrateData) and
              migrate_data.obj_attr_is_set('migration')):
            migration = migrate_data.migration
        else:
            migration = None

        if migration:
            # Remove allocations created in Placement for the dest node.
            # If migration is None, the virt driver didn't pass it which is
            # a bug.
            self._revert_allocation(context, instance, migration)
        else:
            LOG.error('Unable to revert allocations during live migration '
                      'rollback; compute driver did not provide migrate_data',
                      instance=instance)

        # NOTE(tr3buchet): setup networks on source host (really it's re-setup
        #                  for nova-network)
        # NOTE(mriedem): This is a no-op for neutron.
        self.network_api.setup_networks_on_host(context, instance, self.host)

        # NOTE(erlon): We should make sure that rollback_live_migration_at_src
        # is not called in the pre_live_migration rollback as that will trigger
        # the src host to re-attach interfaces which were not detached
        # previously.
        if not pre_live_migration:
            self.driver.rollback_live_migration_at_source(context, instance,
                                                          migrate_data)

        # NOTE(lyarwood): Fetch the current list of BDMs, disconnect any
        # connected volumes from the dest and delete any volume attachments
        # used by the destination host before rolling back to the original
        # still valid source host volume attachments.
        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                context, instance.uuid)
        # TODO(lyarwood): Turn the following into a lookup method within
        # BlockDeviceMappingList.
        vol_bdms = [bdm for bdm in bdms if bdm.is_volume]
        self._remove_remote_volume_connections(context, dest, vol_bdms,
                                               instance)
        self._rollback_volume_bdms(context, vol_bdms, source_bdms, instance)

        self._notify_about_instance_usage(context, instance,
                                          "live_migration._rollback.start")
        compute_utils.notify_about_instance_action(context, instance,
                self.host,
                action=fields.NotificationAction.LIVE_MIGRATION_ROLLBACK,
                phase=fields.NotificationPhase.START,
                bdms=bdms)

        do_cleanup, destroy_disks = self._live_migration_cleanup_flags(
                migrate_data, migr_ctxt=instance.migration_context)

        if do_cleanup:
            self.compute_rpcapi.rollback_live_migration_at_destination(
                    context, instance, dest, destroy_disks=destroy_disks,
                    migrate_data=migrate_data)
        else:
            # The port binding profiles need to be cleaned up.
            with errors_out_migration_ctxt(migration):
                try:
                    # This call will delete any inactive destination host
                    # port bindings.
                    self.network_api.setup_networks_on_host(
                        context, instance, host=dest, teardown=True)
                except exception.PortBindingDeletionFailed as e:
                    # Removing the inactive port bindings from the destination
                    # host is not critical so just log an error but don't fail.
                    LOG.error(
                        'Network cleanup failed for destination host %s '
                        'during live migration rollback. You may need to '
                        'manually clean up resources in the network service. '
                        'Error: %s', dest, str(e))
                except Exception:
                    with excutils.save_and_reraise_exception():
                        LOG.exception(
                            'An error occurred while cleaning up networking '
                            'during live migration rollback.',
                            instance=instance)

        # NOTE(luyao): We drop move_claim and migration_context after cleanup
        # is complete, to ensure the specific resources claimed on destination
        # are released safely.
        # TODO(artom) drop_move_claim_at_destination() is new in RPC 5.3, only
        # call it if we performed a NUMA-aware live migration (which implies us
        # being able to send RPC 5.3). To check this, we can use the
        # src_supports_numa_live_migration flag, as it will be set if and only
        # if:
        # - dst_supports_numa_live_migration made its way to the source
        #   (meaning both dest and source are new and conductor can speak
        #   RPC 5.3)
        # - src_supports_numa_live_migration was set by the source driver and
        #   passed the send-RPC-5.3 check.
        # This check can be removed in RPC 6.0.
        if ('src_supports_numa_live_migration' in migrate_data and
                migrate_data.src_supports_numa_live_migration):
            LOG.debug('Calling destination to drop move claim.',
                      instance=instance)
            self.compute_rpcapi.drop_move_claim_at_destination(context,
                                                               instance, dest)

        # NOTE(luyao): We only update instance info after rollback operations
        # are complete
        instance.task_state = None
        instance.progress = 0
        instance.drop_migration_context()
        instance.save(expected_task_state=[task_states.MIGRATING])

        self._notify_about_instance_usage(context, instance,
                                          "live_migration._rollback.end")
        compute_utils.notify_about_instance_action(context, instance,
                self.host,
                action=fields.NotificationAction.LIVE_MIGRATION_ROLLBACK,
                phase=fields.NotificationPhase.END,
                bdms=bdms)

        # NOTE(luyao): we have cleanup everything and get instance
        # back to normal status, now set migration status to 'failed'
        self._set_migration_status(migration, migration_status)

    @wrap_exception()
    @wrap_instance_fault
    def drop_move_claim_at_destination(self, context, instance):
        """Called by the source of a live migration during rollback to ask the
        destination to drop the MoveClaim object that was created for the live
        migration on the destination.
        """
        nodename = self._get_nodename(instance)
        LOG.debug('Dropping live migration resource claim on destination '
                  'node %s', nodename, instance=instance)
        self.rt.drop_move_claim(
            context, instance, nodename, flavor=instance.flavor)

    @wrap_exception()
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def rollback_live_migration_at_destination(self, context, instance,
                                               destroy_disks,
                                               migrate_data):
        """Cleaning up image directory that is created pre_live_migration.

        :param context: security context
        :param instance: a nova.objects.instance.Instance object sent over rpc
        :param destroy_disks: whether to destroy volumes or not
        :param migrate_data: contains migration info
        """
        network_info = self.network_api.get_instance_nw_info(context, instance)
        self._notify_about_instance_usage(
                      context, instance, "live_migration.rollback.dest.start",
                      network_info=network_info)
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_ROLLBACK_DEST,
            phase=fields.NotificationPhase.START)
        try:
            # NOTE(tr3buchet): tear down networks on dest host (nova-net)
            # NOTE(mriedem): For neutron, this call will delete any
            # destination host port bindings.
            # TODO(mriedem): We should eventually remove this call from
            # this method (rollback_live_migration_at_destination) since this
            # method is only called conditionally based on whether or not the
            # instance is running on shared storage. _rollback_live_migration
            # already calls this method for neutron if we are running on
            # shared storage.
            self.network_api.setup_networks_on_host(context, instance,
                                                    self.host, teardown=True)
        except exception.PortBindingDeletionFailed as e:
            # Removing the inactive port bindings from the destination
            # host is not critical so just log an error but don't fail.
            LOG.error(
                'Network cleanup failed for destination host %s '
                'during live migration rollback. You may need to '
                'manually clean up resources in the network service. '
                'Error: %s', self.host, str(e))
        except Exception:
            with excutils.save_and_reraise_exception():
                # NOTE(tdurakov): even if teardown networks fails driver
                # should try to rollback live migration on destination.
                LOG.exception('An error occurred while deallocating network.',
                              instance=instance)
        finally:
            # always run this even if setup_networks_on_host fails
            # NOTE(vish): The mapping is passed in so the driver can disconnect
            #             from remote volumes if necessary
            block_device_info = self._get_instance_block_device_info(context,
                                                                     instance)
            # free any instance PCI claims done on destination during
            # check_can_live_migrate_destination()
            self.rt.free_pci_device_claims_for_instance(context, instance)

            # NOTE(luyao): Apply migration_context temporarily since it's
            # on destination host, we rely on instance object to cleanup
            # specific resources like vpmem
            with instance.mutated_migration_context():
                self.driver.rollback_live_migration_at_destination(
                    context, instance, network_info, block_device_info,
                    destroy_disks=destroy_disks, migrate_data=migrate_data)

        self._notify_about_instance_usage(
                        context, instance, "live_migration.rollback.dest.end",
                        network_info=network_info)
        compute_utils.notify_about_instance_action(
            context, instance, self.host,
            action=fields.NotificationAction.LIVE_MIGRATION_ROLLBACK_DEST,
            phase=fields.NotificationPhase.END)

    def _require_nw_info_update(self, context, instance):
        """Detect whether there is a mismatch in binding:host_id, or
        binding_failed or unbound binding:vif_type for any of the instances
        ports.
        """
        # Only update port bindings if compute manager does manage port
        # bindings instead of the compute driver. For example IronicDriver
        # manages the port binding for baremetal instance ports, hence,
        # external intervention with the binding is not desired.
        if self.driver.manages_network_binding_host_id():
            return False

        search_opts = {'device_id': instance.uuid,
                       'fields': ['binding:host_id', 'binding:vif_type']}
        ports = self.network_api.list_ports(context, **search_opts)
        for p in ports['ports']:
            if p.get('binding:host_id') != self.host:
                return True
            vif_type = p.get('binding:vif_type')
            if (vif_type == network_model.VIF_TYPE_UNBOUND or
                    vif_type == network_model.VIF_TYPE_BINDING_FAILED):
                return True
        return False

    @periodic_task.periodic_task(
        spacing=CONF.heal_instance_info_cache_interval)
    def _heal_instance_info_cache(self, context):
        """Called periodically.  On every call, try to update the
        info_cache's network information for another instance by
        calling to the network manager.

        This is implemented by keeping a cache of uuids of instances
        that live on this host.  On each call, we pop one off of a
        list, pull the DB record, and try the call to the network API.
        If anything errors don't fail, as it's possible the instance
        has been deleted, etc.
        """
        heal_interval = CONF.heal_instance_info_cache_interval
        if not heal_interval:
            return

        instance_uuids = getattr(self, '_instance_uuids_to_heal', [])
        instance = None

        LOG.debug('Starting heal instance info cache')

        if not instance_uuids:
            # The list of instances to heal is empty so rebuild it
            LOG.debug('Rebuilding the list of instances to heal')
            db_instances = objects.InstanceList.get_by_host(
                context, self.host, expected_attrs=[], use_slave=True)
            for inst in db_instances:
                # We don't want to refresh the cache for instances
                # which are building or deleting so don't put them
                # in the list. If they are building they will get
                # added to the list next time we build it.
                if (inst.vm_state == vm_states.BUILDING):
                    LOG.debug('Skipping network cache update for instance '
                              'because it is Building.', instance=inst)
                    continue
                if (inst.task_state == task_states.DELETING):
                    LOG.debug('Skipping network cache update for instance '
                              'because it is being deleted.', instance=inst)
                    continue

                if not instance:
                    # Save the first one we find so we don't
                    # have to get it again
                    instance = inst
                else:
                    instance_uuids.append(inst['uuid'])

            self._instance_uuids_to_heal = instance_uuids
        else:
            # Find the next valid instance on the list
            while instance_uuids:
                try:
                    inst = objects.Instance.get_by_uuid(
                            context, instance_uuids.pop(0),
                            expected_attrs=['system_metadata', 'info_cache',
                                            'flavor'],
                            use_slave=True)
                except exception.InstanceNotFound:
                    # Instance is gone.  Try to grab another.
                    continue

                # Check the instance hasn't been migrated
                if inst.host != self.host:
                    LOG.debug('Skipping network cache update for instance '
                              'because it has been migrated to another '
                              'host.', instance=inst)
                # Check the instance isn't being deleting
                elif inst.task_state == task_states.DELETING:
                    LOG.debug('Skipping network cache update for instance '
                              'because it is being deleted.', instance=inst)
                else:
                    instance = inst
                    break

        if instance:
            # We have an instance now to refresh
            try:
                # Fix potential mismatch in port binding if evacuation failed
                # after reassigning the port binding to the dest host but
                # before the instance host is changed.
                # Do this only when instance has no pending task.
                if instance.task_state is None and \
                        self._require_nw_info_update(context, instance):
                    LOG.info("Updating ports in neutron", instance=instance)
                    self.network_api.setup_instance_network_on_host(
                        context, instance, self.host)
                # Call to network API to get instance info.. this will
                # force an update to the instance's info_cache
                self.network_api.get_instance_nw_info(
                    context, instance, force_refresh=True)
                LOG.debug('Updated the network info_cache for instance',
                          instance=instance)
            except exception.InstanceNotFound:
                # Instance is gone.
                LOG.debug('Instance no longer exists. Unable to refresh',
                          instance=instance)
                return
            except exception.InstanceInfoCacheNotFound:
                # InstanceInfoCache is gone.
                LOG.debug('InstanceInfoCache no longer exists. '
                          'Unable to refresh', instance=instance)
            except Exception:
                LOG.error('An error occurred while refreshing the network '
                          'cache.', instance=instance, exc_info=True)
        else:
            LOG.debug("Didn't find any instances for network info cache "
                      "update.")

    @periodic_task.periodic_task
    def _poll_rebooting_instances(self, context):
        if CONF.reboot_timeout > 0:
            filters = {'task_state':
                       [task_states.REBOOTING,
                        task_states.REBOOT_STARTED,
                        task_states.REBOOT_PENDING],
                       'host': self.host}
            rebooting = objects.InstanceList.get_by_filters(
                context, filters, expected_attrs=[], use_slave=True)

            to_poll = []
            for instance in rebooting:
                if timeutils.is_older_than(instance.updated_at,
                                           CONF.reboot_timeout):
                    to_poll.append(instance)

            self.driver.poll_rebooting_instances(CONF.reboot_timeout, to_poll)

    @periodic_task.periodic_task
    def _poll_rescued_instances(self, context):
        if CONF.rescue_timeout > 0:
            filters = {'vm_state': vm_states.RESCUED,
                       'host': self.host}
            rescued_instances = objects.InstanceList.get_by_filters(
                context, filters, expected_attrs=["system_metadata"],
                use_slave=True)

            to_unrescue = []
            for instance in rescued_instances:
                if timeutils.is_older_than(instance.launched_at,
                                           CONF.rescue_timeout):
                    to_unrescue.append(instance)

            for instance in to_unrescue:
                self.compute_api.unrescue(context, instance)

    @periodic_task.periodic_task
    def _poll_unconfirmed_resizes(self, context):
        if CONF.resize_confirm_window == 0:
            return

        migrations = objects.MigrationList.get_unconfirmed_by_dest_compute(
                context, CONF.resize_confirm_window, self.host,
                use_slave=True)

        migrations_info = dict(migration_count=len(migrations),
                confirm_window=CONF.resize_confirm_window)

        if migrations_info["migration_count"] > 0:
            LOG.info("Found %(migration_count)d unconfirmed migrations "
                     "older than %(confirm_window)d seconds",
                     migrations_info)

        def _set_migration_to_error(migration, reason, **kwargs):
            LOG.warning("Setting migration %(migration_id)s to error: "
                        "%(reason)s",
                        {'migration_id': migration.id, 'reason': reason},
                        **kwargs)
            migration.status = 'error'
            migration.save()

        for migration in migrations:
            instance_uuid = migration.instance_uuid
            LOG.info("Automatically confirming migration "
                     "%(migration_id)s for instance %(instance_uuid)s",
                     {'migration_id': migration.id,
                      'instance_uuid': instance_uuid})
            expected_attrs = ['metadata', 'system_metadata']
            try:
                instance = objects.Instance.get_by_uuid(context,
                            instance_uuid, expected_attrs=expected_attrs,
                            use_slave=True)
            except exception.InstanceNotFound:
                reason = (_("Instance %s not found") %
                          instance_uuid)
                _set_migration_to_error(migration, reason)
                continue
            if instance.vm_state == vm_states.ERROR:
                reason = _("In ERROR state")
                _set_migration_to_error(migration, reason,
                                        instance=instance)
                continue
            # race condition: The instance in DELETING state should not be
            # set the migration state to error, otherwise the instance in
            # to be deleted which is in RESIZED state
            # will not be able to confirm resize
            if instance.task_state in [task_states.DELETING,
                                       task_states.SOFT_DELETING]:
                msg = ("Instance being deleted or soft deleted during resize "
                       "confirmation. Skipping.")
                LOG.debug(msg, instance=instance)
                continue

            # race condition: This condition is hit when this method is
            # called between the save of the migration record with a status of
            # finished and the save of the instance object with a state of
            # RESIZED. The migration record should not be set to error.
            if instance.task_state == task_states.RESIZE_FINISH:
                msg = ("Instance still resizing during resize "
                       "confirmation. Skipping.")
                LOG.debug(msg, instance=instance)
                continue

            vm_state = instance.vm_state
            task_state = instance.task_state
            if vm_state != vm_states.RESIZED or task_state is not None:
                reason = (_("In states %(vm_state)s/%(task_state)s, not "
                           "RESIZED/None") %
                          {'vm_state': vm_state,
                           'task_state': task_state})
                _set_migration_to_error(migration, reason,
                                        instance=instance)
                continue
            try:
                self.compute_api.confirm_resize(context, instance,
                                                migration=migration)
            except Exception as e:
                LOG.info("Error auto-confirming resize: %s. "
                         "Will retry later.", e, instance=instance)

    @periodic_task.periodic_task(spacing=CONF.shelved_poll_interval)
    def _poll_shelved_instances(self, context):

        if CONF.shelved_offload_time <= 0:
            return

        filters = {'vm_state': vm_states.SHELVED,
                   'task_state': None,
                   'host': self.host}
        shelved_instances = objects.InstanceList.get_by_filters(
            context, filters=filters, expected_attrs=['system_metadata'],
            use_slave=True)

        to_gc = []
        for instance in shelved_instances:
            sys_meta = instance.system_metadata
            shelved_at = timeutils.parse_strtime(sys_meta['shelved_at'])
            if timeutils.is_older_than(shelved_at, CONF.shelved_offload_time):
                to_gc.append(instance)

        cyclient = cyborg.get_client(context)
        for instance in to_gc:
            try:
                instance.task_state = task_states.SHELVING_OFFLOADING
                instance.save(expected_task_state=(None,))
                accel_uuids = []
                if instance.flavor.extra_specs.get('accel:device_profile'):
                    # TODO(brinzhang): After cyborg support batch query ARQs
                    # for more than one instances, we will improve efficiency
                    # with this implemention.
                    accel_uuids = cyclient.get_arq_uuids_for_instance(instance)
                self.shelve_offload_instance(
                    context, instance, clean_shutdown=False,
                    accel_uuids=accel_uuids)
            except Exception:
                LOG.exception('Periodic task failed to offload instance.',
                              instance=instance)

    @periodic_task.periodic_task
    def _instance_usage_audit(self, context):
        if not CONF.instance_usage_audit:
            return

        begin, end = utils.last_completed_audit_period()
        if objects.TaskLog.get(context, 'instance_usage_audit', begin, end,
                               self.host):
            return

        instances = objects.InstanceList.get_active_by_window_joined(
            context, begin, end, host=self.host,
            expected_attrs=['system_metadata', 'info_cache', 'metadata',
                            'flavor'],
            use_slave=True)
        num_instances = len(instances)
        errors = 0
        successes = 0
        LOG.info("Running instance usage audit for host %(host)s "
                 "from %(begin_time)s to %(end_time)s. "
                 "%(number_instances)s instances.",
                 {'host': self.host,
                  'begin_time': begin,
                  'end_time': end,
                  'number_instances': num_instances})
        start_time = time.time()
        task_log = objects.TaskLog(context)
        task_log.task_name = 'instance_usage_audit'
        task_log.period_beginning = begin
        task_log.period_ending = end
        task_log.host = self.host
        task_log.task_items = num_instances
        task_log.message = 'Instance usage audit started...'
        task_log.begin_task()
        for instance in instances:
            try:
                compute_utils.notify_usage_exists(
                    self.notifier, context, instance, self.host,
                    ignore_missing_network_data=False)
                successes += 1
            except Exception:
                LOG.exception('Failed to generate usage '
                              'audit for instance '
                              'on host %s', self.host,
                              instance=instance)
                errors += 1
        task_log.errors = errors
        task_log.message = (
            'Instance usage audit ran for host %s, %s instances in %s seconds.'
            % (self.host, num_instances, time.time() - start_time))
        task_log.end_task()

    def _get_host_volume_bdms(self, context, use_slave=False):
        """Return all block device mappings on a compute host."""
        compute_host_bdms = []
        instances = objects.InstanceList.get_by_host(context, self.host,
            use_slave=use_slave)
        for instance in instances:
            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                    context, instance.uuid, use_slave=use_slave)
            instance_bdms = [bdm for bdm in bdms if bdm.is_volume]
            compute_host_bdms.append(dict(instance=instance,
                                          instance_bdms=instance_bdms))

        return compute_host_bdms

    def _update_volume_usage_cache(self, context, vol_usages):
        """Updates the volume usage cache table with a list of stats."""
        for usage in vol_usages:
            # Allow switching of greenthreads between queries.
            greenthread.sleep(0)
            vol_usage = objects.VolumeUsage(context)
            vol_usage.volume_id = usage['volume']
            vol_usage.instance_uuid = usage['instance'].uuid
            vol_usage.project_id = usage['instance'].project_id
            vol_usage.user_id = usage['instance'].user_id
            vol_usage.availability_zone = usage['instance'].availability_zone
            vol_usage.curr_reads = usage['rd_req']
            vol_usage.curr_read_bytes = usage['rd_bytes']
            vol_usage.curr_writes = usage['wr_req']
            vol_usage.curr_write_bytes = usage['wr_bytes']
            vol_usage.save()
            self.notifier.info(context, 'volume.usage', vol_usage.to_dict())
            compute_utils.notify_about_volume_usage(context, vol_usage,
                                                    self.host)

    @periodic_task.periodic_task(spacing=CONF.volume_usage_poll_interval)
    def _poll_volume_usage(self, context):
        if CONF.volume_usage_poll_interval == 0:
            return

        compute_host_bdms = self._get_host_volume_bdms(context,
                                                       use_slave=True)
        if not compute_host_bdms:
            return

        LOG.debug("Updating volume usage cache")
        try:
            vol_usages = self.driver.get_all_volume_usage(context,
                                                          compute_host_bdms)
        except NotImplementedError:
            return

        self._update_volume_usage_cache(context, vol_usages)

    @periodic_task.periodic_task(spacing=CONF.sync_power_state_interval,
                                 run_immediately=True)
    def _sync_power_states(self, context):
        """Align power states between the database and the hypervisor.

        To sync power state data we make a DB call to get the number of
        virtual machines known by the hypervisor and if the number matches the
        number of virtual machines known by the database, we proceed in a lazy
        loop, one database record at a time, checking if the hypervisor has the
        same power state as is in the database.
        """
        db_instances = objects.InstanceList.get_by_host(context, self.host,
                                                        expected_attrs=[],
                                                        use_slave=True)

        try:
            num_vm_instances = self.driver.get_num_instances()
        except exception.VirtDriverNotReady as e:
            # If the virt driver is not ready, like ironic-api not being up
            # yet in the case of ironic, just log it and exit.
            LOG.info('Skipping _sync_power_states periodic task due to: %s', e)
            return

        num_db_instances = len(db_instances)

        if num_vm_instances != num_db_instances:
            LOG.warning("While synchronizing instance power states, found "
                        "%(num_db_instances)s instances in the database "
                        "and %(num_vm_instances)s instances on the "
                        "hypervisor.",
                        {'num_db_instances': num_db_instances,
                         'num_vm_instances': num_vm_instances})

        def _sync(db_instance):
            # NOTE(melwitt): This must be synchronized as we query state from
            #                two separate sources, the driver and the database.
            #                They are set (in stop_instance) and read, in sync.
            @utils.synchronized(db_instance.uuid)
            def query_driver_power_state_and_sync():
                self._query_driver_power_state_and_sync(context, db_instance)

            try:
                query_driver_power_state_and_sync()
            except Exception:
                LOG.exception("Periodic sync_power_state task had an "
                              "error while processing an instance.",
                              instance=db_instance)

            self._syncs_in_progress.pop(db_instance.uuid)

        for db_instance in db_instances:
            # process syncs asynchronously - don't want instance locking to
            # block entire periodic task thread
            uuid = db_instance.uuid
            if uuid in self._syncs_in_progress:
                LOG.debug('Sync already in progress for %s', uuid)
            else:
                LOG.debug('Triggering sync for uuid %s', uuid)
                self._syncs_in_progress[uuid] = True
                self._sync_power_pool.spawn_n(_sync, db_instance)

    def _query_driver_power_state_and_sync(self, context, db_instance):
        if db_instance.task_state is not None:
            LOG.info("During sync_power_state the instance has a "
                     "pending task (%(task)s). Skip.",
                     {'task': db_instance.task_state}, instance=db_instance)
            return
        # No pending tasks. Now try to figure out the real vm_power_state.
        try:
            vm_instance = self.driver.get_info(db_instance)
            vm_power_state = vm_instance.state
        except exception.InstanceNotFound:
            vm_power_state = power_state.NOSTATE
        # Note(maoy): the above get_info call might take a long time,
        # for example, because of a broken libvirt driver.
        try:
            self._sync_instance_power_state(context,
                                            db_instance,
                                            vm_power_state,
                                            use_slave=True)
        except exception.InstanceNotFound:
            # NOTE(hanlind): If the instance gets deleted during sync,
            # silently ignore.
            pass

    def _stop_unexpected_shutdown_instance(self, context, vm_state,
                                           db_instance, orig_db_power_state):
        # this is an exceptional case; make sure our data is up
        # to date before slamming through a power off
        vm_instance = self.driver.get_info(db_instance,
                                           use_cache=False)
        vm_power_state = vm_instance.state

        # if it still looks off, go ahead and call stop()
        if vm_power_state in (power_state.SHUTDOWN,
                              power_state.CRASHED):

            LOG.warning("Instance shutdown by itself. Calling the "
                        "stop API. Current vm_state: %(vm_state)s, "
                        "current task_state: %(task_state)s, "
                        "original DB power_state: %(db_power_state)s, "
                        "current VM power_state: %(vm_power_state)s",
                        {'vm_state': vm_state,
                         'task_state': db_instance.task_state,
                         'db_power_state': orig_db_power_state,
                         'vm_power_state': vm_power_state},
                        instance=db_instance)
            try:
                # Note(maoy): here we call the API instead of
                # brutally updating the vm_state in the database
                # to allow all the hooks and checks to be performed.
                if db_instance.shutdown_terminate:
                    self.compute_api.delete(context, db_instance)
                else:
                    self.compute_api.stop(context, db_instance)
            except Exception:
                # Note(maoy): there is no need to propagate the error
                # because the same power_state will be retrieved next
                # time and retried.
                # For example, there might be another task scheduled.
                LOG.exception("error during stop() in sync_power_state.",
                              instance=db_instance)

    def _sync_instance_power_state(self, context, db_instance, vm_power_state,
                                   use_slave=False):
        """Align instance power state between the database and hypervisor.

        If the instance is not found on the hypervisor, but is in the database,
        then a stop() API will be called on the instance.
        """

        # We re-query the DB to get the latest instance info to minimize
        # (not eliminate) race condition.
        db_instance.refresh(use_slave=use_slave)
        db_power_state = db_instance.power_state
        vm_state = db_instance.vm_state

        if self.host != db_instance.host:
            # on the sending end of nova-compute _sync_power_state
            # may have yielded to the greenthread performing a live
            # migration; this in turn has changed the resident-host
            # for the VM; However, the instance is still active, it
            # is just in the process of migrating to another host.
            # This implies that the compute source must relinquish
            # control to the compute destination.
            LOG.info("During the sync_power process the "
                     "instance has moved from "
                     "host %(src)s to host %(dst)s",
                     {'src': db_instance.host,
                      'dst': self.host},
                     instance=db_instance)
            return
        elif db_instance.task_state is not None:
            # on the receiving end of nova-compute, it could happen
            # that the DB instance already report the new resident
            # but the actual VM has not showed up on the hypervisor
            # yet. In this case, let's allow the loop to continue
            # and run the state sync in a later round
            LOG.info("During sync_power_state the instance has a "
                     "pending task (%(task)s). Skip.",
                     {'task': db_instance.task_state},
                     instance=db_instance)
            return

        orig_db_power_state = db_power_state
        if vm_power_state != db_power_state:
            LOG.info('During _sync_instance_power_state the DB '
                     'power_state (%(db_power_state)s) does not match '
                     'the vm_power_state from the hypervisor '
                     '(%(vm_power_state)s). Updating power_state in the '
                     'DB to match the hypervisor.',
                     {'db_power_state': db_power_state,
                      'vm_power_state': vm_power_state},
                     instance=db_instance)
            # power_state is always updated from hypervisor to db
            db_instance.power_state = vm_power_state
            db_instance.save()
            db_power_state = vm_power_state

        # Note(maoy): Now resolve the discrepancy between vm_state and
        # vm_power_state. We go through all possible vm_states.
        if vm_state in (vm_states.BUILDING,
                        vm_states.RESCUED,
                        vm_states.RESIZED,
                        vm_states.SUSPENDED,
                        vm_states.ERROR):
            # TODO(maoy): we ignore these vm_state for now.
            pass
        elif vm_state == vm_states.ACTIVE:
            # The only rational power state should be RUNNING
            if vm_power_state in (power_state.SHUTDOWN,
                                  power_state.CRASHED):
                self._stop_unexpected_shutdown_instance(
                    context, vm_state, db_instance, orig_db_power_state)
            elif vm_power_state == power_state.SUSPENDED:
                LOG.warning("Instance is suspended unexpectedly. Calling "
                            "the stop API.", instance=db_instance)
                try:
                    self.compute_api.stop(context, db_instance)
                except Exception:
                    LOG.exception("error during stop() in sync_power_state.",
                                  instance=db_instance)
            elif vm_power_state == power_state.PAUSED:
                # Note(maoy): a VM may get into the paused state not only
                # because the user request via API calls, but also
                # due to (temporary) external instrumentations.
                # Before the virt layer can reliably report the reason,
                # we simply ignore the state discrepancy. In many cases,
                # the VM state will go back to running after the external
                # instrumentation is done. See bug 1097806 for details.
                LOG.warning("Instance is paused unexpectedly. Ignore.",
                            instance=db_instance)
            elif vm_power_state == power_state.NOSTATE:
                # Occasionally, depending on the status of the hypervisor,
                # which could be restarting for example, an instance may
                # not be found.  Therefore just log the condition.
                LOG.warning("Instance is unexpectedly not found. Ignore.",
                            instance=db_instance)
        elif vm_state == vm_states.STOPPED:
            if vm_power_state not in (power_state.NOSTATE,
                                      power_state.SHUTDOWN,
                                      power_state.CRASHED):
                LOG.warning("Instance is not stopped. Calling "
                            "the stop API. Current vm_state: %(vm_state)s,"
                            " current task_state: %(task_state)s, "
                            "original DB power_state: %(db_power_state)s, "
                            "current VM power_state: %(vm_power_state)s",
                            {'vm_state': vm_state,
                             'task_state': db_instance.task_state,
                             'db_power_state': orig_db_power_state,
                             'vm_power_state': vm_power_state},
                            instance=db_instance)
                try:
                    # NOTE(russellb) Force the stop, because normally the
                    # compute API would not allow an attempt to stop a stopped
                    # instance.
                    self.compute_api.force_stop(context, db_instance)
                except Exception:
                    LOG.exception("error during stop() in sync_power_state.",
                                  instance=db_instance)
        elif vm_state == vm_states.PAUSED:
            if vm_power_state in (power_state.SHUTDOWN,
                                  power_state.CRASHED):
                LOG.warning("Paused instance shutdown by itself. Calling "
                            "the stop API.", instance=db_instance)
                try:
                    self.compute_api.force_stop(context, db_instance)
                except Exception:
                    LOG.exception("error during stop() in sync_power_state.",
                                  instance=db_instance)
        elif vm_state in (vm_states.SOFT_DELETED,
                          vm_states.DELETED):
            if vm_power_state not in (power_state.NOSTATE,
                                      power_state.SHUTDOWN):
                # Note(maoy): this should be taken care of periodically in
                # _cleanup_running_deleted_instances().
                LOG.warning("Instance is not (soft-)deleted.",
                            instance=db_instance)

    @periodic_task.periodic_task
    def _reclaim_queued_deletes(self, context):
        """Reclaim instances that are queued for deletion."""
        interval = CONF.reclaim_instance_interval
        if interval <= 0:
            LOG.debug("CONF.reclaim_instance_interval <= 0, skipping...")
            return

        filters = {'vm_state': vm_states.SOFT_DELETED,
                   'task_state': None,
                   'host': self.host}
        instances = objects.InstanceList.get_by_filters(
            context, filters,
            expected_attrs=objects.instance.INSTANCE_DEFAULT_FIELDS,
            use_slave=True)
        for instance in instances:
            if self._deleted_old_enough(instance, interval):
                bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                        context, instance.uuid)
                LOG.info('Reclaiming deleted instance', instance=instance)
                try:
                    self._delete_instance(context, instance, bdms)
                except Exception as e:
                    LOG.warning("Periodic reclaim failed to delete "
                                "instance: %s",
                                e, instance=instance)

    def _get_nodename(self, instance, refresh=False):
        """Helper method to get the name of the first available node
        on this host. This method should not be used with any operations
        on ironic instances since it does not handle multiple nodes.
        """
        node = self.driver.get_available_nodes(refresh=refresh)[0]
        LOG.debug("No node specified, defaulting to %s", node,
                  instance=instance)
        return node

    def _update_available_resource_for_node(self, context, nodename,
                                            startup=False):

        try:
            self.rt.update_available_resource(context, nodename,
                                              startup=startup)
        except exception.ComputeHostNotFound:
            LOG.warning("Compute node '%s' not found in "
                        "update_available_resource.", nodename)
        except exception.ReshapeFailed:
            # We're only supposed to get here on startup, if a reshape was
            # needed, was attempted, and failed. We want to kill the service.
            with excutils.save_and_reraise_exception():
                LOG.critical("Resource provider data migration failed "
                             "fatally during startup for node %s.", nodename)
        except exception.ReshapeNeeded:
            # This exception should only find its way here if the virt driver's
            # update_provider_tree raised it incorrectly: either
            # a) After the resource tracker already caught it once and
            # reinvoked update_provider_tree with allocations. At this point
            # the driver is just supposed to *do* the reshape, so if it raises
            # ReshapeNeeded, it's a bug, and we want to kill the compute
            # service.
            # b) On periodic rather than startup (we only allow reshapes to
            # happen on startup). In this case we'll just make the logs red and
            # go again at the next periodic interval, where the same thing may
            # or may not happen again. Depending on the previous and intended
            # shape of the providers/inventories, this may not actually cause
            # any immediately visible symptoms (in terms of scheduling, etc.)
            # If this becomes a problem, we may wish to make it pop immediately
            # (e.g. disable the service).
            with excutils.save_and_reraise_exception():
                LOG.exception("ReshapeNeeded exception is unexpected here!")
        except exception.PlacementPciException:
            # If we are at startup and the Placement PCI inventory handling
            # failed then probably there is a configuration error. Propagate
            # the error up to kill the service.
            if startup:
                raise
            # If we are not at startup then we can assume that the
            # configuration was correct at startup so the error is probably
            # transient. Anyhow we cannot kill the service any more so just
            # log the error and continue.
            LOG.exception(
                "Error updating PCI resources for node %(node)s.",
                {'node': nodename})
        except Exception:
            LOG.exception("Error updating resources for node %(node)s.",
                          {'node': nodename})

    @periodic_task.periodic_task(spacing=CONF.update_resources_interval)
    def update_available_resource(self, context, startup=False):
        """See driver.get_available_resource()

        Periodic process that keeps that the compute host's understanding of
        resource availability and usage in sync with the underlying hypervisor.

        :param context: security context
        :param startup: True if this is being called when the nova-compute
            service is starting, False otherwise.
        """
        try:
            nodenames = set(self.driver.get_available_nodes())
        except exception.VirtDriverNotReady:
            LOG.warning("Virt driver is not ready.")
            return

        compute_nodes_in_db = self._get_compute_nodes_in_db(context,
                                                            nodenames,
                                                            use_slave=True,
                                                            startup=startup)

        self.rt.clean_compute_node_cache(compute_nodes_in_db)

        # Delete orphan compute node not reported by driver but still in db
        for cn in compute_nodes_in_db:
            if cn.hypervisor_hostname not in nodenames:
                LOG.info("Deleting orphan compute node %(id)s "
                         "hypervisor host is %(hh)s, "
                         "nodes are %(nodes)s",
                         {'id': cn.id, 'hh': cn.hypervisor_hostname,
                          'nodes': nodenames})
                try:
                    cn.destroy()
                except exception.ObjectActionError:
                    # NOTE(mgoddard): it's possible that another compute
                    # service took ownership of this compute node since we
                    # queried it due to a rebalance, and this will cause the
                    # deletion to fail. Ignore the error in that case.
                    LOG.info("Ignoring failure to delete orphan compute node "
                             "%(id)s on hypervisor host %(hh)s due to "
                             "possible node rebalance",
                             {'id': cn.id, 'hh': cn.hypervisor_hostname})
                    self.rt.remove_node(cn.hypervisor_hostname)
                    self.reportclient.invalidate_resource_provider(cn.uuid)
                else:
                    self.rt.remove_node(cn.hypervisor_hostname)
                    # Delete the corresponding resource provider in placement,
                    # along with any associated allocations.
                    try:
                        self.reportclient.delete_resource_provider(
                            context, cn, cascade=True)
                    except keystone_exception.ClientException as e:
                        LOG.error(
                            "Failed to delete compute node resource provider "
                            "for compute node %s: %s", cn.uuid, str(e))

        for nodename in nodenames:
            self._update_available_resource_for_node(context, nodename,
                                                     startup=startup)

    def _get_compute_nodes_in_db(self, context, nodenames, use_slave=False,
                                 startup=False):
        try:
            return objects.ComputeNodeList.get_all_by_host(context, self.host,
                                                           use_slave=use_slave)
        except exception.NotFound:
            # If the driver is not reporting any nodenames we should not
            # expect there to be compute nodes so we just return in that case.
            # For example, this could be an ironic compute and it is not
            # managing any nodes yet.
            if nodenames:
                if startup:
                    LOG.warning(
                        "No compute node record found for host %s. If this is "
                        "the first time this service is starting on this "
                        "host, then you can ignore this warning.", self.host)
                else:
                    LOG.error("No compute node record for host %s", self.host)
            return []

    @periodic_task.periodic_task(
        spacing=CONF.running_deleted_instance_poll_interval,
        run_immediately=True)
    def _cleanup_running_deleted_instances(self, context):
        """Cleanup any instances which are erroneously still running after
        having been deleted.

        Valid actions to take are:

            1. noop - do nothing
            2. log - log which instances are erroneously running
            3. reap - shutdown and cleanup any erroneously running instances
            4. shutdown - power off *and disable* any erroneously running
                          instances

        The use-case for this cleanup task is: for various reasons, it may be
        possible for the database to show an instance as deleted but for that
        instance to still be running on a host machine (see bug
        https://bugs.launchpad.net/nova/+bug/911366).

        This cleanup task is a cross-hypervisor utility for finding these
        zombied instances and either logging the discrepancy (likely what you
        should do in production), or automatically reaping the instances (more
        appropriate for dev environments).
        """
        action = CONF.running_deleted_instance_action

        if action == "noop":
            return

        # NOTE(sirp): admin contexts don't ordinarily return deleted records
        with utils.temporary_mutation(context, read_deleted="yes"):

            try:
                instances = self._running_deleted_instances(context)
            except exception.VirtDriverNotReady:
                # Since this task runs immediately on startup, if the
                # hypervisor is not yet ready handle it gracefully.
                LOG.debug('Unable to check for running deleted instances '
                          'at this time since the hypervisor is not ready.')
                return

            for instance in instances:
                if action == "log":
                    LOG.warning("Detected instance with name label "
                                "'%s' which is marked as "
                                "DELETED but still present on host.",
                                instance.name, instance=instance)

                elif action == 'shutdown':
                    LOG.info("Powering off instance with name label "
                             "'%s' which is marked as "
                             "DELETED but still present on host.",
                             instance.name, instance=instance)
                    try:
                        self.driver.power_off(instance)
                    except Exception:
                        LOG.warning("Failed to power off instance",
                                    instance=instance, exc_info=True)

                elif action == 'reap':
                    LOG.info("Destroying instance with name label "
                             "'%s' which is marked as "
                             "DELETED but still present on host.",
                             instance.name, instance=instance)
                    bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                        context, instance.uuid, use_slave=True)
                    self.instance_events.clear_events_for_instance(instance)
                    try:
                        self._shutdown_instance(context, instance, bdms,
                                                notify=False)
                        self._cleanup_volumes(context, instance, bdms,
                                              detach=False)
                    except Exception as e:
                        LOG.warning("Periodic cleanup failed to delete "
                                    "instance: %s",
                                    e, instance=instance)
                else:
                    raise Exception(_("Unrecognized value '%s'"
                                      " for CONF.running_deleted_"
                                      "instance_action") % action)

    def _running_deleted_instances(self, context):
        """Returns a list of instances nova thinks is deleted,
        but the hypervisor thinks is still running.
        """
        timeout = CONF.running_deleted_instance_timeout
        filters = {'deleted': True,
                   'soft_deleted': False}
        instances = self._get_instances_on_driver(context, filters)
        return [i for i in instances if self._deleted_old_enough(i, timeout)]

    def _deleted_old_enough(self, instance, timeout):
        deleted_at = instance.deleted_at
        if deleted_at:
            deleted_at = deleted_at.replace(tzinfo=None)
        return (not deleted_at or timeutils.is_older_than(deleted_at, timeout))

    @contextlib.contextmanager
    def _error_out_instance_on_exception(self, context, instance,
                                         instance_state=vm_states.ACTIVE):
        """Context manager to set instance.vm_state after some operation raises

        Used to handle NotImplementedError and InstanceFaultRollback errors
        and reset the instance vm_state and task_state. The vm_state is set
        to the $instance_state parameter and task_state is set to None.
        For all other types of exceptions, the vm_state is set to ERROR and
        the task_state is left unchanged (although most callers will have the
        @reverts_task_state decorator which will set the task_state to None).

        Re-raises the original exception *except* in the case of
        InstanceFaultRollback in which case the wrapped `inner_exception` is
        re-raised.

        :param context: The nova auth request context for the operation.
        :param instance: The instance to update. The vm_state will be set by
            this context manager when an exception is raised.
        :param instance_state: For NotImplementedError and
            InstanceFaultRollback this is the vm_state to set the instance to
            when handling one of those types of exceptions. By default the
            instance will be set to ACTIVE, but the caller should control this
            in case there have been no changes to the running state of the
            instance. For example, resizing a stopped server where prep_resize
            fails early and does not change the power state of the guest should
            not set the instance status to ACTIVE but remain STOPPED.
            This parameter is ignored for all other types of exceptions and the
            instance vm_state is set to ERROR.
        """
        # NOTE(mriedem): Why doesn't this method just save off the
        # original instance.vm_state here rather than use a parameter? Or use
        # instance_state=None as an override but default to the current
        # vm_state when rolling back.
        instance_uuid = instance.uuid
        try:
            yield
        except (NotImplementedError, exception.InstanceFaultRollback) as error:
            # Use reraise=False to determine if we want to raise the original
            # exception or something else.
            with excutils.save_and_reraise_exception(reraise=False) as ctxt:
                LOG.info("Setting instance back to %(state)s after: %(error)s",
                         {'state': instance_state, 'error': error},
                         instance_uuid=instance_uuid)
                self._instance_update(context, instance,
                                      vm_state=instance_state,
                                      task_state=None)
                if isinstance(error, exception.InstanceFaultRollback):
                    # Raise the wrapped exception.
                    raise error.inner_exception
                # Else re-raise the NotImplementedError.
                ctxt.reraise = True
        except Exception:
            LOG.exception('Setting instance vm_state to ERROR',
                          instance_uuid=instance_uuid)
            with excutils.save_and_reraise_exception():
                # NOTE(mriedem): Why don't we pass clean_task_state=True here?
                self._set_instance_obj_error_state(instance)

    def _process_instance_event(self, instance, event):
        _event = self.instance_events.pop_instance_event(instance, event)
        if _event:
            LOG.debug('Processing event %(event)s',
                      {'event': event.key}, instance=instance)
            _event.send(event)
        else:
            # If it's a network-vif-unplugged event and the instance is being
            # deleted or live migrated then we don't need to make this a
            # warning as it's expected. There are other expected things which
            # could trigger this event like detaching an interface, but we
            # don't have a task state for that.
            # TODO(mriedem): We have other move operations and things like
            # hard reboot (probably rebuild as well) which trigger this event
            # but nothing listens for network-vif-unplugged. We should either
            # handle those other known cases or consider just not logging a
            # warning if we get this event and the instance is undergoing some
            # task state transition.
            if (event.name == 'network-vif-unplugged' and
                    instance.task_state in (
                        task_states.DELETING, task_states.MIGRATING)):
                LOG.debug('Received event %s for instance with task_state %s.',
                          event.key, instance.task_state, instance=instance)
            else:
                LOG.warning('Received unexpected event %(event)s for '
                            'instance with vm_state %(vm_state)s and '
                            'task_state %(task_state)s.',
                            {'event': event.key,
                             'vm_state': instance.vm_state,
                             'task_state': instance.task_state},
                            instance=instance)

    def _process_instance_vif_deleted_event(self, context, instance,
                                            deleted_vif_id):
        # If an attached port is deleted by neutron, it needs to
        # be detached from the instance.
        # And info cache needs to be updated.
        network_info = instance.info_cache.network_info
        for index, vif in enumerate(network_info):
            if vif['id'] == deleted_vif_id:
                LOG.info('Neutron deleted interface %(intf)s; '
                         'detaching it from the instance and '
                         'deleting it from the info cache',
                         {'intf': vif['id']},
                         instance=instance)
                profile = vif.get('profile', {}) or {}  # profile can be None
                rps = profile.get('allocation')
                if rps:
                    if isinstance(rps, dict):
                        # if extended resource request extension is enabled
                        # then we have a dict of providers, flatten it for the
                        # log.
                        rps = ','.join(rps.values())
                    LOG.error(
                        'The bound port %(port_id)s is deleted in Neutron but '
                        'the resource allocation on the resource providers '
                        '%(rp_uuid)s are leaked until the server '
                        '%(server_uuid)s is deleted.',
                        {'port_id': vif['id'],
                         'rp_uuid': rps,
                         'server_uuid': instance.uuid})

                del network_info[index]
                neutron.update_instance_cache_with_nw_info(
                    self.network_api, context, instance, nw_info=network_info)
                try:
                    self.driver.detach_interface(context, instance, vif)
                except NotImplementedError:
                    # Not all virt drivers support attach/detach of interfaces
                    # yet (like Ironic), so just ignore this.
                    pass
                except exception.NovaException as ex:
                    # If the instance was deleted before the interface was
                    # detached, just log it at debug.
                    log_level = (logging.DEBUG
                                 if isinstance(ex, exception.InstanceNotFound)
                                 else logging.WARNING)
                    LOG.log(log_level,
                            "Detach interface failed, "
                            "port_id=%(port_id)s, reason: %(msg)s",
                            {'port_id': deleted_vif_id, 'msg': ex},
                            instance=instance)
                break

    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def extend_volume(self, context, instance, extended_volume_id):

        # If an attached volume is extended by cinder, it needs to
        # be extended by virt driver so host can detect its new size.
        # And bdm needs to be updated.
        LOG.debug('Handling volume-extended event for volume %(vol)s',
                  {'vol': extended_volume_id}, instance=instance)

        try:
            bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
                   context, extended_volume_id, instance.uuid)
        except exception.NotFound:
            LOG.warning('Extend volume failed, '
                        'volume %(vol)s is not attached to instance.',
                        {'vol': extended_volume_id},
                        instance=instance)
            return

        LOG.info('Cinder extended volume %(vol)s; '
                 'extending it to detect new size',
                 {'vol': extended_volume_id},
                 instance=instance)
        volume = self.volume_api.get(context, bdm.volume_id)

        if bdm.connection_info is None:
            LOG.warning('Extend volume failed, '
                        'attached volume %(vol)s has no connection_info',
                        {'vol': extended_volume_id},
                        instance=instance)
            return

        connection_info = jsonutils.loads(bdm.connection_info)
        bdm.volume_size = volume['size']
        bdm.save()

        if not self.driver.capabilities.get('supports_extend_volume', False):
            raise exception.ExtendVolumeNotSupported()

        try:
            self.driver.extend_volume(context, connection_info, instance,
                                      bdm.volume_size * units.Gi)
        except Exception as ex:
            LOG.warning('Extend volume failed, '
                        'volume_id=%(volume_id)s, reason: %(msg)s',
                        {'volume_id': extended_volume_id, 'msg': ex},
                        instance=instance)
            raise

    @staticmethod
    def _is_state_valid_for_power_update_event(instance, target_power_state):
        """Check if the current state of the instance allows it to be
        a candidate for the power-update event.

        :param instance: The nova instance object.
        :param target_power_state: The desired target power state; this should
                                   either be "POWER_ON" or "POWER_OFF".
        :returns Boolean: True if the instance can be subjected to the
                          power-update event.
        """
        if ((target_power_state == external_event_obj.POWER_ON and
                instance.task_state is None and
                instance.vm_state == vm_states.STOPPED and
                instance.power_state == power_state.SHUTDOWN) or
            (target_power_state == external_event_obj.POWER_OFF and
                instance.task_state is None and
                instance.vm_state == vm_states.ACTIVE and
                instance.power_state == power_state.RUNNING)):
            return True
        return False

    @wrap_exception()
    @reverts_task_state
    @wrap_instance_event(prefix='compute')
    @wrap_instance_fault
    def power_update(self, context, instance, target_power_state):
        """Power update of an instance prompted by an external event.
        :param context: The API request context.
        :param instance: The nova instance object.
        :param target_power_state: The desired target power state;
                                   this should either be "POWER_ON" or
                                   "POWER_OFF".
        """

        @utils.synchronized(instance.uuid)
        def do_power_update():
            LOG.debug('Handling power-update event with target_power_state %s '
                      'for instance', target_power_state, instance=instance)
            if not self._is_state_valid_for_power_update_event(
                    instance, target_power_state):
                pow_state = fields.InstancePowerState.from_index(
                    instance.power_state)
                LOG.info('The power-update %(tag)s event for instance '
                         '%(uuid)s is a no-op since the instance is in '
                         'vm_state %(vm_state)s, task_state '
                         '%(task_state)s and power_state '
                         '%(power_state)s.',
                         {'tag': target_power_state, 'uuid': instance.uuid,
                         'vm_state': instance.vm_state,
                         'task_state': instance.task_state,
                         'power_state': pow_state})
                return
            LOG.debug("Trying to %s instance",
                      target_power_state, instance=instance)
            if target_power_state == external_event_obj.POWER_ON:
                action = fields.NotificationAction.POWER_ON
                notification_name = "power_on."
                instance.task_state = task_states.POWERING_ON
            else:
                # It's POWER_OFF
                action = fields.NotificationAction.POWER_OFF
                notification_name = "power_off."
                instance.task_state = task_states.POWERING_OFF
                instance.progress = 0

            try:
                # Note that the task_state is set here rather than the API
                # because this is a best effort operation and deferring
                # updating the task_state until we get to the compute service
                # avoids error handling in the API and needing to account for
                # older compute services during rolling upgrades from Stein.
                # If we lose a race, UnexpectedTaskStateError is handled
                # below.
                instance.save(expected_task_state=[None])
                self._notify_about_instance_usage(context, instance,
                                                  notification_name + "start")
                compute_utils.notify_about_instance_action(context, instance,
                    self.host, action=action,
                    phase=fields.NotificationPhase.START)
                # UnexpectedTaskStateError raised from the driver will be
                # handled below and not result in a fault, error notification
                # or failure of the instance action. Other driver errors like
                # NotImplementedError will be record a fault, send an error
                # notification and mark the instance action as failed.
                self.driver.power_update_event(instance, target_power_state)
                self._notify_about_instance_usage(context, instance,
                                                  notification_name + "end")
                compute_utils.notify_about_instance_action(context, instance,
                    self.host, action=action,
                    phase=fields.NotificationPhase.END)
            except exception.UnexpectedTaskStateError as e:
                # Handling the power-update event is best effort and if we lost
                # a race with some other action happening to the instance we
                # just log it and return rather than fail the action.
                LOG.info("The power-update event was possibly preempted: %s ",
                         e.format_message(), instance=instance)
                return
        do_power_update()

    @wrap_exception()
    def external_instance_event(self, context, instances, events):
        # NOTE(danms): Some event types are handled by the manager, such
        # as when we're asked to update the instance's info_cache. If it's
        # not one of those, look for some thread(s) waiting for the event and
        # unblock them if so.
        for event in events:
            instance = [inst for inst in instances
                        if inst.uuid == event.instance_uuid][0]
            LOG.debug('Received event %(event)s',
                      {'event': event.key},
                      instance=instance)
            if event.name == 'network-changed':
                try:
                    LOG.debug('Refreshing instance network info cache due to '
                              'event %s.', event.key, instance=instance)
                    self.network_api.get_instance_nw_info(
                        context, instance, refresh_vif_id=event.tag)
                except exception.NotFound as e:
                    LOG.info('Failed to process external instance event '
                             '%(event)s due to: %(error)s',
                             {'event': event.key, 'error': str(e)},
                             instance=instance)
            elif event.name == 'network-vif-deleted':
                try:
                    self._process_instance_vif_deleted_event(context,
                                                             instance,
                                                             event.tag)
                except exception.NotFound as e:
                    LOG.info('Failed to process external instance event '
                             '%(event)s due to: %(error)s',
                             {'event': event.key, 'error': str(e)},
                             instance=instance)
            elif event.name == 'volume-extended':
                self.extend_volume(context, instance, event.tag)
            elif event.name == 'power-update':
                self.power_update(context, instance, event.tag)
            else:
                self._process_instance_event(instance, event)

    @periodic_task.periodic_task(spacing=CONF.image_cache.manager_interval,
                                 external_process_ok=True)
    def _run_image_cache_manager_pass(self, context):
        """Run a single pass of the image cache manager."""

        if not self.driver.capabilities.get("has_imagecache", False):
            return

        # Determine what other nodes use this storage
        storage_users.register_storage_use(CONF.instances_path, CONF.host)
        nodes = storage_users.get_storage_users(CONF.instances_path)

        # Filter all_instances to only include those nodes which share this
        # storage path.
        # TODO(mikal): this should be further refactored so that the cache
        # cleanup code doesn't know what those instances are, just a remote
        # count, and then this logic should be pushed up the stack.
        filters = {'deleted': False,
                   'soft_deleted': True,
                   'host': nodes}
        filtered_instances = objects.InstanceList.get_by_filters(context,
                                 filters, expected_attrs=[], use_slave=True)

        self.driver.manage_image_cache(context, filtered_instances)

    def cache_images(self, context, image_ids):
        """Ask the virt driver to pre-cache a set of base images.

        :param context: The RequestContext
        :param image_ids: The image IDs to be cached
        :return: A dict, keyed by image-id where the values are one of:
                 'cached' if the image was downloaded,
                 'existing' if the image was already in the cache,
                 'unsupported' if the virt driver does not support caching,
                 'error' if the virt driver raised an exception.
        """

        results = {}

        LOG.info('Caching %i image(s) by request', len(image_ids))
        for image_id in image_ids:
            try:
                cached = self.driver.cache_image(context, image_id)
                if cached:
                    results[image_id] = 'cached'
                else:
                    results[image_id] = 'existing'
            except NotImplementedError:
                LOG.warning('Virt driver does not support image pre-caching;'
                            ' ignoring request')
                # NOTE(danms): Yes, technically we could short-circuit here to
                # avoid trying the rest of the images, but it's very cheap to
                # just keep hitting the NotImplementedError to keep the logic
                # clean.
                results[image_id] = 'unsupported'
            except Exception as e:
                results[image_id] = 'error'
                LOG.error('Failed to cache image %(image_id)s: %(err)s',
                          {'image_id': image_id,
                           'err': e})

        return results

    @periodic_task.periodic_task(spacing=CONF.instance_delete_interval)
    def _run_pending_deletes(self, context):
        """Retry any pending instance file deletes."""
        LOG.debug('Cleaning up deleted instances')
        filters = {'deleted': True,
                   'soft_deleted': False,
                   'host': CONF.host,
                   'cleaned': False}
        attrs = ['system_metadata']
        with utils.temporary_mutation(context, read_deleted='yes'):
            instances = objects.InstanceList.get_by_filters(
                context, filters, expected_attrs=attrs, use_slave=True)
        LOG.debug('There are %d instances to clean', len(instances))

        for instance in instances:
            attempts = int(instance.system_metadata.get('clean_attempts', '0'))
            LOG.debug('Instance has had %(attempts)s of %(max)s '
                      'cleanup attempts',
                      {'attempts': attempts,
                       'max': CONF.maximum_instance_delete_attempts},
                      instance=instance)
            if attempts < CONF.maximum_instance_delete_attempts:
                success = self.driver.delete_instance_files(instance)

                instance.system_metadata['clean_attempts'] = str(attempts + 1)
                if success:
                    instance.cleaned = True
                with utils.temporary_mutation(context, read_deleted='yes'):
                    instance.save()

    @periodic_task.periodic_task(spacing=CONF.instance_delete_interval)
    def _cleanup_incomplete_migrations(self, context):
        """Cleanup on failed resize/revert-resize operation and
        failed rollback live migration operation.

        During resize/revert-resize operation, or after a failed rollback
        live migration operation, if that instance gets deleted then instance
        files might remain either on source or destination compute node and
        other specific resources might not be cleaned up because of the race
        condition.
        """
        LOG.debug('Cleaning up deleted instances with incomplete migration ')
        migration_filters = {'host': CONF.host,
                             'status': 'error'}
        migrations = objects.MigrationList.get_by_filters(context,
                                                          migration_filters)

        if not migrations:
            return

        inst_uuid_from_migrations = set([migration.instance_uuid for migration
                                         in migrations])

        inst_filters = {'deleted': True, 'soft_deleted': False,
                        'uuid': inst_uuid_from_migrations}
        attrs = ['info_cache', 'security_groups', 'system_metadata']
        with utils.temporary_mutation(context, read_deleted='yes'):
            instances = objects.InstanceList.get_by_filters(
                context, inst_filters, expected_attrs=attrs, use_slave=True)

        for instance in instances:
            if instance.host == CONF.host:
                continue
            for migration in migrations:
                if instance.uuid != migration.instance_uuid:
                    continue
                self.driver.delete_instance_files(instance)
                # we are not sure whether the migration_context is applied
                # during incompleted migrating, we need to apply/revert
                # migration_context to get instance object content matching
                # current host.
                revert = (True if migration.source_compute == CONF.host
                          else False)
                with instance.mutated_migration_context(revert=revert):
                    self.driver.cleanup_lingering_instance_resources(instance)

                try:
                    migration.status = 'failed'
                    migration.save()
                except exception.MigrationNotFound:
                    LOG.warning("Migration %s is not found.",
                                migration.id,
                                instance=instance)
                break

    @messaging.expected_exceptions(exception.InstanceQuiesceNotSupported,
                                   exception.QemuGuestAgentNotEnabled,
                                   exception.NovaException,
                                   NotImplementedError)
    @wrap_exception()
    def quiesce_instance(self, context, instance):
        """Quiesce an instance on this host."""
        context = context.elevated()
        image_meta = objects.ImageMeta.from_instance(instance)
        self.driver.quiesce(context, instance, image_meta)

    def _wait_for_snapshots_completion(self, context, mapping):
        for mapping_dict in mapping:
            if mapping_dict.get('source_type') == 'snapshot':

                def _wait_snapshot():
                    snapshot = self.volume_api.get_snapshot(
                        context, mapping_dict['snapshot_id'])
                    if snapshot.get('status') != 'creating':
                        raise loopingcall.LoopingCallDone()

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

    @messaging.expected_exceptions(exception.InstanceQuiesceNotSupported,
                                   exception.QemuGuestAgentNotEnabled,
                                   exception.NovaException,
                                   NotImplementedError)
    @wrap_exception()
    def unquiesce_instance(self, context, instance, mapping=None):
        """Unquiesce an instance on this host.

        If snapshots' image mapping is provided, it waits until snapshots are
        completed before unqueiscing.
        """
        context = context.elevated()
        if mapping:
            try:
                self._wait_for_snapshots_completion(context, mapping)
            except Exception as error:
                LOG.exception("Exception while waiting completion of "
                              "volume snapshots: %s",
                              error, instance=instance)
        image_meta = objects.ImageMeta.from_instance(instance)
        self.driver.unquiesce(context, instance, image_meta)

    @periodic_task.periodic_task(spacing=CONF.instance_delete_interval)
    def _cleanup_expired_console_auth_tokens(self, context):
        """Remove all expired console auth tokens.

        Console authorization tokens and their connection data are stored
        in the database when a user asks for a console connection to an
        instance. After a time they expire. We periodically remove any expired
        tokens from the database.
        """
        objects.ConsoleAuthToken.clean_expired_console_auths(context)

    def _claim_pci_for_instance_vifs(self, ctxt, instance):
        """Claim PCI devices for the instance's VIFs on the compute node

        :param ctxt: Context
        :param instance: Instance object
        :return: <port ID: PciDevice> mapping for the VIFs that yielded a
                PCI claim on the compute node
        """
        pci_req_id_to_port_id = {}
        pci_reqs = []
        port_id_to_pci_dev = {}

        for vif in instance.get_network_info():
            pci_req = pci_req_module.get_instance_pci_request_from_vif(
                ctxt,
                instance,
                vif)
            if pci_req:
                pci_req_id_to_port_id[pci_req.request_id] = vif['id']
                pci_reqs.append(pci_req)

        if pci_reqs:
            # Create PCI requests and claim against PCI resource tracker
            # NOTE(adrianc): We claim against the same requests as on the
            # source node.
            vif_pci_requests = objects.InstancePCIRequests(
                requests=pci_reqs,
                instance_uuid=instance.uuid)

            # if we are called during the live migration with NUMA topology
            # support the PCI claim needs to consider the destination NUMA
            # topology that is then stored in the migration_context
            dest_topo = None
            if instance.migration_context:
                dest_topo = instance.migration_context.new_numa_topology

            claimed_pci_devices_objs = self.rt.claim_pci_devices(
                ctxt, vif_pci_requests, dest_topo)

            # Update VIFMigrateData profile with the newly claimed PCI
            # device
            for pci_dev in claimed_pci_devices_objs:
                LOG.debug("PCI device: %s Claimed on destination node",
                          pci_dev.address)
                port_id = pci_req_id_to_port_id[pci_dev.request_id]
                port_id_to_pci_dev[port_id] = pci_dev

        return port_id_to_pci_dev

    def _update_migrate_vifs_profile_with_pci(self,
                                              migrate_vifs,
                                              port_id_to_pci_dev):
        """Update migrate vifs profile with the claimed PCI devices

        :param migrate_vifs: list of VIFMigrateData objects
        :param port_id_to_pci_dev: a <port_id: PciDevice> mapping
        :return: None.
        """
        for mig_vif in migrate_vifs:
            port_id = mig_vif.port_id
            if port_id not in port_id_to_pci_dev:
                continue

            pci_dev = port_id_to_pci_dev[port_id]
            profile = copy.deepcopy(mig_vif.source_vif['profile'])
            profile['pci_slot'] = pci_dev.address
            profile['pci_vendor_info'] = ':'.join([pci_dev.vendor_id,
                                                   pci_dev.product_id])
            if profile.get('card_serial_number'):
                # Assume it is there since Nova makes sure that PCI devices
                # tagged as remote-managed have a serial in PCI VPD.
                profile['card_serial_number'] = pci_dev.card_serial_number
            if profile.get('pf_mac_address'):
                profile['pf_mac_address'] = pci_dev.sriov_cap['pf_mac_address']
            if profile.get('vf_num'):
                profile['vf_num'] = pci_dev.sriov_cap['vf_num']

            if pci_dev.mac_address:
                profile['device_mac_address'] = pci_dev.mac_address

            mig_vif.profile = profile
            LOG.debug("Updating migrate VIF profile for port %(port_id)s:"
                      "%(profile)s", {'port_id': port_id,
                                      'profile': profile})


# TODO(sbauza): Remove this proxy class in the X release once we drop the 5.x
# support.
# NOTE(sbauza): This proxy class will support the existing <=5.13 RPC calls
# from any RPC client but will also make sure that the new 6.0 RPC calls will
# be supported.
class _ComputeV5Proxy(object):

    target = messaging.Target(version='5.13')

    def __init__(self, manager):
        self.manager = manager

    def __getattr__(self, name):
        # NOTE(sbauza): Proxying all the other methods but the V5 ones.
        return getattr(self.manager, name)

    # 5.0 support for block_migration argument
    def pre_live_migration(self, context, instance, block_migration, disk,
                           migrate_data):
        return self.manager.pre_live_migration(context, instance, disk,
                                               migrate_data)

    # 5.1 support for legacy request_spec argument
    def prep_resize(self, context, image, instance, instance_type,
                    request_spec, filter_properties, node,
                    clean_shutdown, migration, host_list):
        if not isinstance(request_spec, objects.RequestSpec):
            # Prior to compute RPC API 5.1 conductor would pass a legacy dict
            # version of the request spec to compute and since Stein compute
            # could be sending that back to conductor on reschedule, so if we
            # got a dict convert it to an object.
            # TODO(mriedem): We can drop this compat code when we only support
            # compute RPC API >=6.0.
            request_spec = objects.RequestSpec.from_primitives(
                context, request_spec, filter_properties)
            # We don't have to set the new flavor on the request spec because
            # if we got here it was due to a reschedule from the compute and
            # the request spec would already have the new flavor in it from the
            # else block below.
        self.manager.prep_resize(context, image, instance, instance_type,
                                 request_spec, filter_properties, node,
                                 clean_shutdown, migration, host_list)

    # 5.2 support for optional request_spec argument
    def resize_instance(self, context, instance, image,
                        migration, instance_type, clean_shutdown,
                        request_spec=None):
        self.manager.resize_instance(context, instance, image,
                                    migration, instance_type, clean_shutdown,
                                    request_spec)

    # 5.2 support for optional request_spec argument
    def finish_resize(self, context, disk_info, image, instance,
                      migration, request_spec=None):
        self.manager.finish_resize(context, disk_info, image, instance,
                                   migration, request_spec)

    # 5.2 support for optional request_spec argument
    def revert_resize(self, context, instance, migration, request_spec=None):
        self.manager.revert_resize(context, instance, migration, request_spec)

    # 5.2 support for optional request_spec argument
    def finish_revert_resize(
            self, context, instance, migration, request_spec=None):
        self.manager.finish_revert_resize(context, instance, migration,
                                          request_spec)

    # 5.2 support for optional request_spec argument
    # 5.13 support for optional accel_uuids argument
    def unshelve_instance(self, context, instance, image, filter_properties,
                          node, request_spec=None, accel_uuids=None):
        self.manager.unshelve_instance(context, instance, image,
                                       filter_properties, node, request_spec,
                                       accel_uuids or [])

    # 5.3 support for optional migration and limits arguments
    def check_can_live_migrate_destination(self, ctxt, instance,
                                           block_migration, disk_over_commit,
                                           migration=None, limits=None):
        return self.manager.check_can_live_migrate_destination(
            ctxt, instance, block_migration, disk_over_commit,
            migration, limits)

    # 5.11 support for optional accel_uuids argument
    def build_and_run_instance(self, context, instance, image, request_spec,
                     filter_properties, admin_password=None,
                     injected_files=None, requested_networks=None,
                     security_groups=None, block_device_mapping=None,
                     node=None, limits=None, host_list=None, accel_uuids=None):
        self.manager.build_and_run_instance(
            context, instance, image, request_spec,
            filter_properties, accel_uuids, admin_password,
            injected_files, requested_networks,
            security_groups, block_device_mapping,
            node, limits, host_list)

    # 5.12 support for optional accel_uuids argument
    def rebuild_instance(self, context, instance, orig_image_ref, image_ref,
                         injected_files, new_pass, orig_sys_metadata,
                         bdms, recreate, on_shared_storage,
                         preserve_ephemeral, migration,
                         scheduled_node, limits, request_spec,
                         accel_uuids=None):
        self.manager.rebuild_instance(
            context, instance, orig_image_ref, image_ref,
            injected_files, new_pass, orig_sys_metadata,
            bdms, recreate, on_shared_storage,
            preserve_ephemeral, migration,
            scheduled_node, limits, request_spec,
            accel_uuids, False)

    # 5.13 support for optional accel_uuids argument
    def shelve_instance(self, context, instance, image_id,
                        clean_shutdown, accel_uuids=None):
        self.manager.shelve_instance(context, instance, image_id,
                                     clean_shutdown, accel_uuids)

    # 5.13 support for optional accel_uuids argument
    def shelve_offload_instance(self, context, instance, clean_shutdown,
            accel_uuids=None):
        self.manager.shelve_offload_instance(
            context, instance, clean_shutdown, accel_uuids)

    # 6.0 drop unused request_spec argument
    def prep_snapshot_based_resize_at_dest(
            self, ctxt, instance, flavor, nodename, migration, limits,
            request_spec):
        return self.manager.prep_snapshot_based_resize_at_dest(
            ctxt, instance, flavor, nodename, migration, limits)

    # 6.0 drop unused request_spec argument
    def finish_snapshot_based_resize_at_dest(
            self, ctxt, instance, migration, snapshot_id, request_spec):
        self.manager.finish_snapshot_based_resize_at_dest(
            ctxt, instance, migration, snapshot_id)

    # 6.0 drop unused instance argument
    def check_instance_shared_storage(self, ctxt, instance, data):
        return self.manager.check_instance_shared_storage(ctxt, data)