summaryrefslogtreecommitdiff
path: root/nova/tests/unit/compute/test_api.py
blob: 809ed3b295410792b37fd41f5cb509ec9568b539 (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
#
#    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.

"""Unit tests for compute API."""

import contextlib
import datetime

import ddt
import fixtures
import iso8601
import mock
import os_traits as ot
from oslo_messaging import exceptions as oslo_exceptions
from oslo_serialization import jsonutils
from oslo_utils import fixture as utils_fixture
from oslo_utils.fixture import uuidsentinel as uuids
from oslo_utils import timeutils
from oslo_utils import uuidutils

from nova.compute import api as compute_api
from nova.compute import flavors
from nova.compute import instance_actions
from nova.compute import power_state
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 import vm_states
from nova import conductor
import nova.conf
from nova import context
from nova.db import api as db
from nova import exception
from nova.image import glance as image_api
from nova.network import constants
from nova.network import model
from nova.network import neutron as neutron_api
from nova import objects
from nova.objects import base as obj_base
from nova.objects import block_device as block_device_obj
from nova.objects import fields as fields_obj
from nova.objects import image_meta as image_meta_obj
from nova.objects import quotas as quotas_obj
from nova.objects import security_group as secgroup_obj
from nova.servicegroup import api as servicegroup_api
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.unit import fake_block_device
from nova.tests.unit import fake_build_request
from nova.tests.unit import fake_instance
from nova.tests.unit import fake_request_spec
from nova.tests.unit import fake_volume
from nova.tests.unit import matchers
from nova.tests.unit.objects import test_flavor
from nova.tests.unit.objects import test_migration
from nova import utils
from nova.volume import cinder


CONF = nova.conf.CONF

FAKE_IMAGE_REF = 'fake-image-ref'
NODENAME = 'fakenode1'
SHELVED_IMAGE = 'fake-shelved-image'
SHELVED_IMAGE_NOT_FOUND = 'fake-shelved-image-notfound'
SHELVED_IMAGE_NOT_AUTHORIZED = 'fake-shelved-image-not-authorized'
SHELVED_IMAGE_EXCEPTION = 'fake-shelved-image-exception'


@ddt.ddt
class _ComputeAPIUnitTestMixIn(object):
    def setUp(self):
        super(_ComputeAPIUnitTestMixIn, self).setUp()
        self.user_id = 'fake'
        self.project_id = 'fake'
        self.compute_api = compute_api.API()
        self.context = context.RequestContext(self.user_id,
                                              self.project_id)

    def _get_vm_states(self, exclude_states=None):
        vm_state = set([vm_states.ACTIVE, vm_states.BUILDING, vm_states.PAUSED,
                    vm_states.SUSPENDED, vm_states.RESCUED, vm_states.STOPPED,
                    vm_states.RESIZED, vm_states.SOFT_DELETED,
                    vm_states.DELETED, vm_states.ERROR, vm_states.SHELVED,
                    vm_states.SHELVED_OFFLOADED])
        if not exclude_states:
            exclude_states = set()
        return vm_state - exclude_states

    def _create_flavor(self, **updates):
        flavor = {'id': 1,
                  'flavorid': 1,
                  'name': 'm1.tiny',
                  'memory_mb': 512,
                  'vcpus': 1,
                  'vcpu_weight': None,
                  'root_gb': 1,
                  'ephemeral_gb': 0,
                  'rxtx_factor': 1,
                  'swap': 0,
                  'deleted': 0,
                  'disabled': False,
                  'is_public': True,
                  'deleted_at': None,
                  'created_at': datetime.datetime(2012, 1, 19, 18,
                                                  49, 30, 877329),
                  'updated_at': None,
                  'description': None
                 }
        if updates:
            flavor.update(updates)

        expected_attrs = None
        if 'extra_specs' in updates and updates['extra_specs']:
            expected_attrs = ['extra_specs']

        return objects.Flavor._from_db_object(
            self.context, objects.Flavor(extra_specs={}), flavor,
            expected_attrs=expected_attrs)

    def _create_instance_obj(self, params=None, flavor=None):
        """Create a test instance."""
        if not params:
            params = {}

        if flavor is None:
            flavor = self._create_flavor()

        now = timeutils.utcnow()

        instance = objects.Instance()
        instance.metadata = {}
        instance.metadata.update(params.pop('metadata', {}))
        instance.system_metadata = params.pop('system_metadata', {})
        instance._context = self.context
        instance.id = 1
        instance.uuid = uuidutils.generate_uuid()
        instance.vm_state = vm_states.ACTIVE
        instance.task_state = None
        instance.image_ref = FAKE_IMAGE_REF
        instance.reservation_id = 'r-fakeres'
        instance.user_id = self.user_id
        instance.project_id = self.project_id
        instance.host = 'fake_host'
        instance.node = NODENAME
        instance.instance_type_id = flavor.id
        instance.ami_launch_index = 0
        instance.memory_mb = 0
        instance.vcpus = 0
        instance.root_gb = 0
        instance.ephemeral_gb = 0
        instance.architecture = fields_obj.Architecture.X86_64
        instance.os_type = 'Linux'
        instance.locked = False
        instance.created_at = now
        instance.updated_at = now
        instance.launched_at = now
        instance.disable_terminate = False
        instance.info_cache = objects.InstanceInfoCache()
        instance.info_cache.network_info = model.NetworkInfo()
        instance.flavor = flavor
        instance.old_flavor = instance.new_flavor = None
        instance.numa_topology = None

        if params:
            instance.update(params)
        instance.obj_reset_changes()
        return instance

    def _create_keypair_obj(self, instance):
        """Create a test keypair."""
        keypair = objects.KeyPair()
        keypair.id = 1
        keypair.name = 'fake_key'
        keypair.user_id = instance.user_id
        keypair.fingerprint = 'fake'
        keypair.public_key = 'fake key'
        keypair.type = 'ssh'
        return keypair

    def _obj_to_list_obj(self, list_obj, obj):
        list_obj.objects = []
        list_obj.objects.append(obj)
        list_obj._context = self.context
        list_obj.obj_reset_changes()
        return list_obj

    @mock.patch('nova.objects.Quotas.check_deltas')
    @mock.patch('nova.conductor.conductor_api.ComputeTaskAPI.build_instances')
    @mock.patch('nova.compute.api.API._record_action_start')
    @mock.patch('nova.compute.api.API._check_requested_networks')
    @mock.patch('nova.objects.Quotas.limit_check')
    @mock.patch('nova.compute.api.API._get_image')
    @mock.patch('nova.compute.api.API._provision_instances')
    def test_create_with_networks_max_count_none(self, provision_instances,
                                                 get_image, check_limit,
                                                 check_requested_networks,
                                                 record_action_start,
                                                 build_instances,
                                                 check_deltas):
        # Make sure max_count is checked for None, as Python3 doesn't allow
        # comparison between NoneType and Integer, something that's allowed in
        # Python 2.
        provision_instances.return_value = []
        get_image.return_value = (None, {})
        check_requested_networks.return_value = 1

        instance_type = self._create_flavor()

        port = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
        address = '10.0.0.1'
        requested_networks = objects.NetworkRequestList(
            objects=[objects.NetworkRequest(address=address,
                                            port_id=port)])

        with mock.patch.object(self.compute_api.network_api,
                               'create_resource_requests',
                               return_value=(None, [])):
            self.compute_api.create(self.context, instance_type, 'image_id',
                                    requested_networks=requested_networks,
                                    max_count=None)

    @mock.patch('nova.objects.Quotas.get_all_by_project_and_user',
                new=mock.MagicMock())
    @mock.patch('nova.objects.Quotas.count_as_dict')
    @mock.patch('nova.objects.Quotas.limit_check')
    @mock.patch('nova.objects.Quotas.limit_check_project_and_user')
    def test_create_quota_exceeded_messages(self, mock_limit_check_pu,
                                            mock_limit_check, mock_count):
        image_href = "image_href"
        image_id = 0
        instance_type = self._create_flavor()

        quotas = {'instances': 1, 'cores': 1, 'ram': 1}
        quota_exception = exception.OverQuota(quotas=quotas,
            usages={'instances': 1, 'cores': 1, 'ram': 1},
            overs=['instances'])

        proj_count = {'instances': 1, 'cores': 1, 'ram': 1}
        user_count = proj_count.copy()
        mock_count.return_value = {'project': proj_count, 'user': user_count}
        # instances/cores/ram quota
        mock_limit_check_pu.side_effect = quota_exception

        # We don't care about network validation in this test.
        self.compute_api.network_api.validate_networks = (
            mock.Mock(return_value=40))
        with mock.patch.object(self.compute_api, '_get_image',
                               return_value=(image_id, {})) as mock_get_image:
            for min_count, message in [(20, '20-40'), (40, '40')]:
                try:
                    self.compute_api.create(self.context, instance_type,
                                            "image_href", min_count=min_count,
                                            max_count=40)
                except exception.TooManyInstances as e:
                    self.assertEqual(message, e.kwargs['req'])
                else:
                    self.fail("Exception not raised")
            mock_get_image.assert_called_with(self.context, image_href)
            self.assertEqual(2, mock_get_image.call_count)
            self.assertEqual(2, mock_limit_check_pu.call_count)

    @mock.patch('nova.objects.Quotas.limit_check')
    def test_create_volume_backed_instance_with_trusted_certs(self,
                                                              check_limit):
        # Creating an instance with no image_ref specified will result in
        # creating a volume-backed instance
        self.assertRaises(exception.CertificateValidationFailed,
                          self.compute_api.create, self.context,
                          instance_type=self._create_flavor(), image_href=None,
                          trusted_certs=['test-cert-1', 'test-cert-2'])

    @mock.patch('nova.objects.Quotas.limit_check')
    def test_create_volume_backed_instance_with_conf_trusted_certs(
            self, check_limit):
        self.flags(verify_glance_signatures=True, group='glance')
        self.flags(enable_certificate_validation=True, group='glance')
        self.flags(default_trusted_certificate_ids=['certs'], group='glance')
        # Creating an instance with no image_ref specified will result in
        # creating a volume-backed instance
        self.assertRaises(exception.CertificateValidationFailed,
                          self.compute_api.create, self.context,
                          instance_type=self._create_flavor(),
                          image_href=None)

    def _test_create_max_net_count(self, max_net_count, min_count, max_count):
        with test.nested(
            mock.patch.object(self.compute_api, '_get_image',
                              return_value=(None, {})),
            mock.patch.object(self.compute_api, '_check_auto_disk_config'),
            mock.patch.object(self.compute_api,
                              '_validate_and_build_base_options',
                              return_value=({}, max_net_count, None,
                                            ['default'], None))
        ) as (
            get_image,
            check_auto_disk_config,
            validate_and_build_base_options
        ):
            self.assertRaises(exception.PortLimitExceeded,
                self.compute_api.create, self.context, 'fake_flavor',
                'image_id', min_count=min_count, max_count=max_count)

    def test_max_net_count_zero(self):
        # Test when max_net_count is zero.
        max_net_count = 0
        min_count = 2
        max_count = 3
        self._test_create_max_net_count(max_net_count, min_count, max_count)

    def test_max_net_count_less_than_min_count(self):
        # Test when max_net_count is nonzero but less than min_count.
        max_net_count = 1
        min_count = 2
        max_count = 3
        self._test_create_max_net_count(max_net_count, min_count, max_count)

    def test_specified_port_and_multiple_instances(self):
        # Tests that if port is specified there is only one instance booting
        # (i.e max_count == 1) as we can't share the same port across multiple
        # instances.
        port = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
        address = '10.0.0.1'
        min_count = 1
        max_count = 2
        requested_networks = objects.NetworkRequestList(
            objects=[objects.NetworkRequest(address=address,
                                            port_id=port)])

        self.assertRaises(exception.MultiplePortsNotApplicable,
            self.compute_api.create, self.context, 'fake_flavor', 'image_id',
            min_count=min_count, max_count=max_count,
            requested_networks=requested_networks)

    def _test_specified_ip_and_multiple_instances_helper(self,
                                                         requested_networks):
        # Tests that if ip is specified there is only one instance booting
        # (i.e max_count == 1)
        min_count = 1
        max_count = 2
        self.assertRaises(exception.InvalidFixedIpAndMaxCountRequest,
            self.compute_api.create, self.context, "fake_flavor", 'image_id',
            min_count=min_count, max_count=max_count,
            requested_networks=requested_networks)

    def test_specified_ip_and_multiple_instances(self):
        network = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
        address = '10.0.0.1'
        requested_networks = objects.NetworkRequestList(
            objects=[objects.NetworkRequest(network_id=network,
                                            address=address)])
        self._test_specified_ip_and_multiple_instances_helper(
            requested_networks)

    # TODO(huaqiang): Remove in Wallaby
    @mock.patch('nova.compute.api.API._check_requested_networks',
                new=mock.Mock(return_value=1))
    @mock.patch('nova.virt.hardware.get_pci_numa_policy_constraint',
                return_value=None)
    def test_create_mixed_instance_compute_version_fail(self, mock_pci):
        """Ensure a 'MixedInstanceNotSupportByComputeService' exception raises
        when all 'nova-compute' nodes have not been upgraded to or after
        Victoria.
        """
        extra_specs = {
            "hw:cpu_policy": "mixed",
            "hw:cpu_dedicated_mask": "^3"
        }
        flavor = self._create_flavor(vcpus=4, extra_specs=extra_specs)

        self.assertRaises(exception.MixedInstanceNotSupportByComputeService,
                          self.compute_api.create, self.context, flavor,
                          image_href=None)
        # Ensure the exception is raised right after the call of
        # '_validate_and_build_base_options's since
        # 'get_pci_numa_policy_constraint' is only called in this method.
        mock_pci.assert_called_once()

    @mock.patch('nova.objects.BlockDeviceMapping.save')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'reserve_block_device_name')
    def test_create_volume_bdm_call_reserve_dev_name(self, mock_reserve,
                                                     mock_bdm_save):
        bdm = objects.BlockDeviceMapping(
                **fake_block_device.FakeDbBlockDeviceDict(
                {
                 'id': 1,
                 'volume_id': 1,
                 'source_type': 'volume',
                 'destination_type': 'volume',
                 'device_name': 'vda',
                 'boot_index': 1,
                 }))
        mock_reserve.return_value = bdm
        instance = self._create_instance_obj()
        volume = {'id': '1', 'multiattach': False}
        result = self.compute_api._create_volume_bdm(self.context,
                                                     instance,
                                                     'vda',
                                                     volume,
                                                     None,
                                                     None)
        self.assertTrue(mock_reserve.called)
        self.assertEqual(result, bdm)
        mock_bdm_save.assert_called_once_with()

    @mock.patch.object(objects.BlockDeviceMapping, 'create')
    def test_create_volume_bdm_local_creation(self, bdm_create):
        instance = self._create_instance_obj()
        volume_id = 'fake-vol-id'
        bdm = objects.BlockDeviceMapping(
                **fake_block_device.FakeDbBlockDeviceDict(
                {
                 'instance_uuid': instance.uuid,
                 'volume_id': volume_id,
                 'source_type': 'volume',
                 'destination_type': 'volume',
                 'device_name': 'vda',
                 'boot_index': None,
                 'disk_bus': None,
                 'device_type': None
                 }))
        result = self.compute_api._create_volume_bdm(self.context,
                                                     instance,
                                                     '/dev/vda',
                                                     {'id': volume_id},
                                                     None,
                                                     None,
                                                     is_local_creation=True)
        self.assertEqual(result.instance_uuid, bdm.instance_uuid)
        self.assertIsNone(result.device_name)
        self.assertEqual(result.volume_id, bdm.volume_id)
        self.assertTrue(bdm_create.called)

    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'reserve_block_device_name')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_volume')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'attach_volume')
    def test_attach_volume_new_flow(
        self, mock_attach, mock_get_by_volume, mock_reserve, mock_record
    ):
        mock_get_by_volume.side_effect = exception.VolumeBDMNotFound(
            volume_id='fake-volume-id')
        instance = self._create_instance_obj()
        volume = fake_volume.fake_volume(1, 'test-vol', 'test-vol',
                                         None, None, None, None, None)

        fake_bdm = mock.MagicMock(spec=objects.BlockDeviceMapping)
        mock_reserve.return_value = fake_bdm

        mock_volume_api = mock.patch.object(self.compute_api, 'volume_api',
                                            mock.MagicMock(spec=cinder.API))

        with mock_volume_api as mock_v_api:
            mock_v_api.get.return_value = volume
            mock_v_api.attachment_create.return_value = \
                {'id': uuids.attachment_id}
            self.compute_api.attach_volume(
                self.context, instance, volume['id'])
            mock_v_api.check_availability_zone.assert_called_once_with(
                self.context, volume, instance=instance)
            mock_v_api.attachment_create.assert_called_once_with(self.context,
                                                                 volume['id'],
                                                                 instance.uuid)
            mock_attach.assert_called_once_with(self.context,
                                                instance, fake_bdm)

    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'reserve_block_device_name')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_volume')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'attach_volume')
    def test_tagged_volume_attach_new_flow(
        self, mock_attach, mock_get_by_volume, mock_reserve, mock_record
    ):
        mock_get_by_volume.side_effect = exception.VolumeBDMNotFound(
            volume_id='fake-volume-id')
        instance = self._create_instance_obj()
        volume = fake_volume.fake_volume(1, 'test-vol', 'test-vol',
                                         None, None, None, None, None)

        fake_bdm = mock.MagicMock(spec=objects.BlockDeviceMapping)
        mock_reserve.return_value = fake_bdm

        mock_volume_api = mock.patch.object(self.compute_api, 'volume_api',
                                            mock.MagicMock(spec=cinder.API))

        with mock_volume_api as mock_v_api:
            mock_v_api.get.return_value = volume
            mock_v_api.attachment_create.return_value = \
                {'id': uuids.attachment_id}
            self.compute_api.attach_volume(
                self.context, instance, volume['id'], tag='foo')
            mock_reserve.assert_called_once_with(self.context, instance, None,
                                                 volume['id'],
                                                 device_type=None,
                                                 disk_bus=None, tag='foo',
                                                 multiattach=False)
            mock_v_api.check_availability_zone.assert_called_once_with(
                self.context, volume, instance=instance)
            mock_v_api.attachment_create.assert_called_once_with(
                self.context, volume['id'], instance.uuid)
            mock_attach.assert_called_once_with(self.context,
                                                instance, fake_bdm)

    @mock.patch.object(compute_rpcapi.ComputeAPI, 'reserve_block_device_name')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_volume')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'attach_volume')
    def test_attach_volume_attachment_create_fails(
        self, mock_attach, mock_get_by_volume, mock_reserve
    ):
        mock_get_by_volume.side_effect = exception.VolumeBDMNotFound(
            volume_id='fake-volume-id')
        instance = self._create_instance_obj()
        volume = fake_volume.fake_volume(1, 'test-vol', 'test-vol',
                                         None, None, None, None, None)

        fake_bdm = mock.MagicMock(spec=objects.BlockDeviceMapping)
        mock_reserve.return_value = fake_bdm

        mock_volume_api = mock.patch.object(self.compute_api, 'volume_api',
                                            mock.MagicMock(spec=cinder.API))

        with mock_volume_api as mock_v_api:
            mock_v_api.get.return_value = volume
            mock_v_api.attachment_create.side_effect = test.TestingException()
            self.assertRaises(test.TestingException,
                              self.compute_api.attach_volume,
                              self.context, instance, volume['id'])
            mock_v_api.check_availability_zone.assert_called_once_with(
                self.context, volume, instance=instance)
            mock_v_api.attachment_create.assert_called_once_with(
                self.context, volume['id'], instance.uuid)
            self.assertEqual(0, mock_attach.call_count)
            fake_bdm.destroy.assert_called_once_with()

    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_volume')
    def test_attach_volume_bdm_exists(self, mock_by_volume):
        mock_by_volume.return_value = [
            mock.Mock(
                spec=objects.BlockDeviceMapping,
                volume_id=uuids.volume,
                instance_uuid=uuids.instance_1
            ),
            mock.Mock(
                spec=objects.BlockDeviceMapping,
                volume_id=uuids.volume,
                instance_uuid=uuids.instance_2
            ),
        ]
        instance = self._create_instance_obj()
        volume = {'id': uuids.volume, 'multiattach': False}
        with mock.patch.object(
            self.compute_api, 'volume_api', mock.MagicMock(spec=cinder.API)
        ) as mock_v_api:
            mock_v_api.get.return_value = volume
            # Assert that we raise InvalidVolume when we find a bdm for the vol
            ex = self.assertRaises(
                exception.InvalidVolume,
                self.compute_api.attach_volume,
                self.context, instance, uuids.volume
            )
            self.assertIn(
                f"volume {uuids.volume} is already attached to instances: "
                f"{uuids.instance_1} {uuids.instance_2}",
                str(ex)
            )

    def test_suspend(self):
        # Ensure instance can be suspended.
        instance = self._create_instance_obj()
        self.assertEqual(instance.vm_state, vm_states.ACTIVE)
        self.assertIsNone(instance.task_state)

        rpcapi = self.compute_api.compute_rpcapi

        with test.nested(
            mock.patch.object(instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(rpcapi, 'suspend_instance')
        ) as (mock_inst_save, mock_record_action, mock_suspend_instance):
            self.compute_api.suspend(self.context, instance)
            self.assertEqual(vm_states.ACTIVE, instance.vm_state)
            self.assertEqual(task_states.SUSPENDING, instance.task_state)
            mock_inst_save.assert_called_once_with(expected_task_state=[None])
            mock_record_action.assert_called_once_with(
                self.context, instance, instance_actions.SUSPEND)
            mock_suspend_instance.assert_called_once_with(self.context,
                                                          instance)

    def _test_suspend_fails(self, vm_state):
        params = dict(vm_state=vm_state)
        instance = self._create_instance_obj(params=params)
        self.assertIsNone(instance.task_state)
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.suspend,
                          self.context, instance)

    def test_suspend_fails_invalid_states(self):
        invalid_vm_states = self._get_vm_states(set([vm_states.ACTIVE]))
        for state in invalid_vm_states:
            self._test_suspend_fails(state)

    def test_resume(self):
        # Ensure instance can be resumed (if suspended).
        instance = self._create_instance_obj(
                params=dict(vm_state=vm_states.SUSPENDED))
        self.assertEqual(instance.vm_state, vm_states.SUSPENDED)
        self.assertIsNone(instance.task_state)

        rpcapi = self.compute_api.compute_rpcapi

        with test.nested(
            mock.patch.object(instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(rpcapi, 'resume_instance')
        ) as (mock_inst_save, mock_record_action, mock_resume_instance):
            self.compute_api.resume(self.context, instance)
            self.assertEqual(vm_states.SUSPENDED, instance.vm_state)
            self.assertEqual(task_states.RESUMING,
                             instance.task_state)
            mock_inst_save.assert_called_once_with(expected_task_state=[None])
            mock_record_action.assert_called_once_with(
                self.context, instance, instance_actions.RESUME)
            mock_resume_instance.assert_called_once_with(self.context,
                                                         instance)

    def test_start(self):
        params = dict(vm_state=vm_states.STOPPED)
        instance = self._create_instance_obj(params=params)

        rpcapi = self.compute_api.compute_rpcapi

        with test.nested(
            mock.patch.object(instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(rpcapi, 'start_instance')
        ) as (mock_inst_save, mock_record_action, mock_start_instance):
            self.compute_api.start(self.context, instance)
            self.assertEqual(task_states.POWERING_ON,
                            instance.task_state)
            mock_inst_save.assert_called_once_with(expected_task_state=[None])
            mock_record_action.assert_called_once_with(
                self.context, instance, instance_actions.START)
            mock_start_instance.assert_called_once_with(self.context,
                                                        instance)

    def test_start_invalid_state(self):
        instance = self._create_instance_obj()
        self.assertEqual(instance.vm_state, vm_states.ACTIVE)
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.start,
                          self.context, instance)

    def test_start_no_host(self):
        params = dict(vm_state=vm_states.STOPPED, host='')
        instance = self._create_instance_obj(params=params)
        self.assertRaises(exception.InstanceNotReady,
                          self.compute_api.start,
                          self.context, instance)

    def _test_stop(self, vm_state, force=False, clean_shutdown=True):
        # Make sure 'progress' gets reset
        params = dict(task_state=None, progress=99, vm_state=vm_state)
        instance = self._create_instance_obj(params=params)

        rpcapi = self.compute_api.compute_rpcapi

        with test.nested(
            mock.patch.object(instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(rpcapi, 'stop_instance')
        ) as (mock_inst_save, mock_record_action, mock_stop_instance):
            if force:
                self.compute_api.force_stop(self.context, instance,
                                            clean_shutdown=clean_shutdown)
            else:
                self.compute_api.stop(self.context, instance,
                                      clean_shutdown=clean_shutdown)
            self.assertEqual(task_states.POWERING_OFF,
                             instance.task_state)
            self.assertEqual(0, instance.progress)

            mock_inst_save.assert_called_once_with(expected_task_state=[None])
            mock_record_action.assert_called_once_with(
                self.context, instance, instance_actions.STOP)
            mock_stop_instance.assert_called_once_with(
                self.context, instance, do_cast=True,
                clean_shutdown=clean_shutdown)

    def test_stop(self):
        self._test_stop(vm_states.ACTIVE)

    def test_stop_stopped_instance_with_bypass(self):
        self._test_stop(vm_states.STOPPED, force=True)

    def test_stop_forced_shutdown(self):
        self._test_stop(vm_states.ACTIVE, force=True)

    def test_stop_without_clean_shutdown(self):
        self._test_stop(vm_states.ACTIVE,
                       clean_shutdown=False)

    def test_stop_forced_without_clean_shutdown(self):
        self._test_stop(vm_states.ACTIVE, force=True,
                        clean_shutdown=False)

    def _test_stop_invalid_state(self, vm_state):
        params = dict(vm_state=vm_state)
        instance = self._create_instance_obj(params=params)
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.stop,
                          self.context, instance)

    def test_stop_fails_invalid_states(self):
        invalid_vm_states = self._get_vm_states(set([vm_states.ACTIVE,
                                                     vm_states.ERROR]))
        for state in invalid_vm_states:
            self._test_stop_invalid_state(state)

    def test_stop_a_stopped_inst(self):
        params = {'vm_state': vm_states.STOPPED}
        instance = self._create_instance_obj(params=params)

        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.stop,
                          self.context, instance)

    def test_stop_no_host(self):
        params = {'host': ''}
        instance = self._create_instance_obj(params=params)
        self.assertRaises(exception.InstanceNotReady,
                          self.compute_api.stop,
                          self.context, instance)

    @mock.patch('nova.compute.api.API._record_action_start')
    @mock.patch('nova.compute.rpcapi.ComputeAPI.trigger_crash_dump')
    def test_trigger_crash_dump(self,
                                trigger_crash_dump,
                                _record_action_start):
        instance = self._create_instance_obj()

        self.compute_api.trigger_crash_dump(self.context, instance)

        _record_action_start.assert_called_once_with(self.context, instance,
            instance_actions.TRIGGER_CRASH_DUMP)

        trigger_crash_dump.assert_called_once_with(self.context, instance)

        self.assertIsNone(instance.task_state)

    def test_trigger_crash_dump_invalid_state(self):
        params = dict(vm_state=vm_states.STOPPED)
        instance = self._create_instance_obj(params)
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.trigger_crash_dump,
                          self.context, instance)

    def test_trigger_crash_dump_no_host(self):
        params = dict(host='')
        instance = self._create_instance_obj(params=params)
        self.assertRaises(exception.InstanceNotReady,
                          self.compute_api.trigger_crash_dump,
                          self.context, instance)

    def test_trigger_crash_dump_locked(self):
        params = dict(locked=True)
        instance = self._create_instance_obj(params=params)
        self.assertRaises(exception.InstanceIsLocked,
                          self.compute_api.trigger_crash_dump,
                          self.context, instance)

    def _test_reboot_type(self, vm_state, reboot_type, task_state=None):
        # Ensure instance can be soft rebooted.
        inst = self._create_instance_obj()
        inst.vm_state = vm_state
        inst.task_state = task_state

        expected_task_state = [None]
        if reboot_type == 'HARD':
            expected_task_state = task_states.ALLOW_REBOOT

        rpcapi = self.compute_api.compute_rpcapi

        with test.nested(
            mock.patch.object(self.context, 'elevated'),
            mock.patch.object(inst, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(rpcapi, 'reboot_instance')
        ) as (mock_elevated, mock_inst_save,
              mock_record_action, mock_reboot_instance):
            self.compute_api.reboot(self.context, inst, reboot_type)

            mock_inst_save.assert_called_once_with(
                expected_task_state=expected_task_state)
            mock_record_action.assert_called_once_with(
                self.context, inst, instance_actions.REBOOT)
            mock_reboot_instance.assert_called_once_with(
                self.context, instance=inst,
                block_device_info=None, reboot_type=reboot_type)

    def _test_reboot_type_fails(self, reboot_type, **updates):
        inst = self._create_instance_obj()
        inst.update(updates)

        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.reboot,
                          self.context, inst, reboot_type)

    def test_reboot_hard_active(self):
        self._test_reboot_type(vm_states.ACTIVE, 'HARD')

    def test_reboot_hard_error(self):
        self._test_reboot_type(vm_states.ERROR, 'HARD')

    def test_reboot_hard_rebooting(self):
        self._test_reboot_type(vm_states.ACTIVE, 'HARD',
                               task_state=task_states.REBOOTING)

    def test_reboot_hard_reboot_started(self):
        self._test_reboot_type(vm_states.ACTIVE, 'HARD',
                               task_state=task_states.REBOOT_STARTED)

    def test_reboot_hard_reboot_pending(self):
        self._test_reboot_type(vm_states.ACTIVE, 'HARD',
                               task_state=task_states.REBOOT_PENDING)

    def test_reboot_hard_rescued(self):
        self._test_reboot_type_fails('HARD', vm_state=vm_states.RESCUED)

    def test_reboot_hard_resuming(self):
        self._test_reboot_type(vm_states.ACTIVE,
                               'HARD', task_state=task_states.RESUMING)

    def test_reboot_hard_unpausing(self):
        self._test_reboot_type(vm_states.ACTIVE,
                               'HARD', task_state=task_states.UNPAUSING)

    def test_reboot_hard_suspending(self):
        self._test_reboot_type(vm_states.ACTIVE,
                               'HARD', task_state=task_states.SUSPENDING)

    def test_reboot_hard_error_not_launched(self):
        self._test_reboot_type_fails('HARD', vm_state=vm_states.ERROR,
                                     launched_at=None)

    def test_reboot_soft(self):
        self._test_reboot_type(vm_states.ACTIVE, 'SOFT')

    def test_reboot_soft_error(self):
        self._test_reboot_type_fails('SOFT', vm_state=vm_states.ERROR)

    def test_reboot_soft_paused(self):
        self._test_reboot_type_fails('SOFT', vm_state=vm_states.PAUSED)

    def test_reboot_soft_stopped(self):
        self._test_reboot_type_fails('SOFT', vm_state=vm_states.STOPPED)

    def test_reboot_soft_suspended(self):
        self._test_reboot_type_fails('SOFT', vm_state=vm_states.SUSPENDED)

    def test_reboot_soft_rebooting(self):
        self._test_reboot_type_fails('SOFT', task_state=task_states.REBOOTING)

    def test_reboot_soft_rebooting_hard(self):
        self._test_reboot_type_fails('SOFT',
                                     task_state=task_states.REBOOTING_HARD)

    def test_reboot_soft_reboot_started(self):
        self._test_reboot_type_fails('SOFT',
                                     task_state=task_states.REBOOT_STARTED)

    def test_reboot_soft_reboot_pending(self):
        self._test_reboot_type_fails('SOFT',
                                     task_state=task_states.REBOOT_PENDING)

    def test_reboot_soft_rescued(self):
        self._test_reboot_type_fails('SOFT', vm_state=vm_states.RESCUED)

    def test_reboot_soft_error_not_launched(self):
        self._test_reboot_type_fails('SOFT', vm_state=vm_states.ERROR,
                                     launched_at=None)

    def test_reboot_soft_resuming(self):
        self._test_reboot_type_fails('SOFT', task_state=task_states.RESUMING)

    def test_reboot_soft_pausing(self):
        self._test_reboot_type_fails('SOFT', task_state=task_states.PAUSING)

    def test_reboot_soft_unpausing(self):
        self._test_reboot_type_fails('SOFT', task_state=task_states.UNPAUSING)

    def test_reboot_soft_suspending(self):
        self._test_reboot_type_fails('SOFT', task_state=task_states.SUSPENDING)

    def _test_delete_resizing_part(self, inst, deltas):
        old_flavor = inst.old_flavor
        deltas['cores'] = -old_flavor.vcpus
        deltas['ram'] = -old_flavor.memory_mb

    def _set_delete_shelved_part(self, inst, mock_image_delete):
        snapshot_id = inst.system_metadata.get('shelved_image_id')
        if snapshot_id == SHELVED_IMAGE:
            mock_image_delete.return_value = True
        elif snapshot_id == SHELVED_IMAGE_NOT_FOUND:
            mock_image_delete.side_effect = exception.ImageNotFound(
                image_id=snapshot_id)
        elif snapshot_id == SHELVED_IMAGE_NOT_AUTHORIZED:
            mock_image_delete.side_effect = exception.ImageNotAuthorized(
                image_id=snapshot_id)
        elif snapshot_id == SHELVED_IMAGE_EXCEPTION:
            mock_image_delete.side_effect = test.TestingException(
                "Unexpected error")

        return snapshot_id

    @mock.patch.object(compute_utils,
                       'notify_about_instance_action')
    @mock.patch.object(objects.Migration, 'get_by_instance_and_status')
    @mock.patch.object(image_api.API, 'delete')
    @mock.patch.object(objects.InstanceMapping, 'save')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    @mock.patch.object(compute_utils,
                       'notify_about_instance_usage')
    @mock.patch.object(db, 'instance_destroy')
    @mock.patch.object(db, 'instance_system_metadata_get')
    @mock.patch.object(neutron_api.API, 'deallocate_for_instance')
    @mock.patch.object(db, 'instance_update_and_get_original')
    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(servicegroup_api.API, 'service_is_up')
    @mock.patch.object(objects.Service, 'get_by_compute_host')
    @mock.patch.object(context.RequestContext, 'elevated')
    @mock.patch.object(objects.BlockDeviceMappingList,
                       'get_by_instance_uuid', return_value=[])
    @mock.patch.object(objects.Instance, 'save')
    def _test_delete(self, delete_type, mock_save, mock_bdm_get, mock_elevated,
                     mock_get_cn, mock_up, mock_record, mock_inst_update,
                     mock_deallocate, mock_inst_meta, mock_inst_destroy,
                     mock_notify_legacy, mock_get_inst,
                     mock_save_im, mock_image_delete, mock_mig_get,
                     mock_notify, **attrs):
        expected_save_calls = [mock.call()]
        expected_record_calls = []
        expected_elevated_calls = []
        inst = self._create_instance_obj()
        inst.update(attrs)
        inst._context = self.context
        deltas = {'instances': -1,
                  'cores': -inst.flavor.vcpus,
                  'ram': -inst.flavor.memory_mb}
        delete_time = datetime.datetime(1955, 11, 5, 9, 30,
                                        tzinfo=iso8601.UTC)
        self.useFixture(utils_fixture.TimeFixture(delete_time))
        task_state = (delete_type == 'soft_delete' and
                      task_states.SOFT_DELETING or task_states.DELETING)
        updates = {'progress': 0, 'task_state': task_state}
        if delete_type == 'soft_delete':
            updates['deleted_at'] = delete_time
        rpcapi = self.compute_api.compute_rpcapi
        mock_confirm = self.useFixture(
            fixtures.MockPatchObject(rpcapi, 'confirm_resize')).mock

        def _reset_task_state(context, instance, migration, src_host,
                              cast=False):
            inst.update({'task_state': None})

        # After confirm resize action, instance task_state is reset to None
        mock_confirm.side_effect = _reset_task_state

        is_shelved = inst.vm_state in (vm_states.SHELVED,
                                       vm_states.SHELVED_OFFLOADED)
        if is_shelved:
            snapshot_id = self._set_delete_shelved_part(inst,
                                                        mock_image_delete)

        mock_terminate = self.useFixture(
            fixtures.MockPatchObject(rpcapi, 'terminate_instance')).mock
        mock_soft_delete = self.useFixture(
            fixtures.MockPatchObject(rpcapi, 'soft_delete_instance')).mock

        if inst.task_state == task_states.RESIZE_FINISH:
            self._test_delete_resizing_part(inst, deltas)

        # NOTE(comstud): This is getting messy.  But what we are wanting
        # to test is:
        # * Check for downed host
        # * If downed host:
        #   * Clean up instance, destroying it, sending notifications.
        #     (Tested in _test_downed_host_part())
        # * If not downed host:
        #   * Record the action start.
        #   * Cast to compute_rpcapi.<method>

        cast = True
        is_downed_host = inst.host == 'down-host' or inst.host is None
        if inst.vm_state == vm_states.RESIZED:
            migration = objects.Migration._from_db_object(
                self.context, objects.Migration(),
                test_migration.fake_db_migration())
            mock_elevated.return_value = self.context
            expected_elevated_calls.append(mock.call())
            mock_mig_get.return_value = migration
            expected_record_calls.append(
                mock.call(self.context, inst,
                          instance_actions.CONFIRM_RESIZE))

            # After confirm resize action, instance task_state
            # is reset to None, so is the expected value. But
            # for soft delete, task_state will be again reset
            # back to soft-deleting in the code to avoid status
            # checking failure.
            updates['task_state'] = None
            if delete_type == 'soft_delete':
                expected_save_calls.append(mock.call())
                updates['task_state'] = 'soft-deleting'

        if inst.host is not None:
            mock_elevated.return_value = self.context
            expected_elevated_calls.append(mock.call())
            mock_get_cn.return_value = objects.Service()
            mock_up.return_value = (inst.host != 'down-host')

        if is_downed_host:
            mock_elevated.return_value = self.context
            expected_elevated_calls.append(mock.call())
            expected_save_calls.append(mock.call())
            state = ('soft' in delete_type and vm_states.SOFT_DELETED or
                     vm_states.DELETED)
            updates.update({'vm_state': state,
                            'task_state': None,
                            'terminated_at': delete_time,
                            'deleted_at': delete_time,
                            'deleted': True})
            fake_inst = fake_instance.fake_db_instance(**updates)
            mock_inst_destroy.return_value = fake_inst
            cell = objects.CellMapping(uuid=uuids.cell,
                                       transport_url='fake://',
                                       database_connection='fake://')
            im = objects.InstanceMapping(cell_mapping=cell)
            mock_get_inst.return_value = im
            cast = False

        if cast:
            expected_record_calls.append(mock.call(self.context, inst,
                                                   instance_actions.DELETE))

        # NOTE(takashin): If objects.Instance.destroy() is called,
        # objects.Instance.uuid (inst.uuid) and host (inst.host) are changed.
        # So preserve them before calling the method to test.
        instance_uuid = inst.uuid
        instance_host = inst.host
        getattr(self.compute_api, delete_type)(self.context, inst)
        for k, v in updates.items():
            self.assertEqual(inst[k], v)

        mock_save.assert_has_calls(expected_save_calls)
        mock_bdm_get.assert_called_once_with(self.context, instance_uuid)

        if expected_record_calls:
            mock_record.assert_has_calls(expected_record_calls)
        if expected_elevated_calls:
            mock_elevated.assert_has_calls(expected_elevated_calls)

        if inst.vm_state == vm_states.RESIZED:
            mock_mig_get.assert_called_once_with(
                self.context, instance_uuid, 'finished')
            mock_confirm.assert_called_once_with(
                self.context, inst, migration, migration['source_compute'],
                cast=False)
        if instance_host is not None:
            mock_get_cn.assert_called_once_with(self.context,
                                                instance_host)
            mock_up.assert_called_once_with(
                test.MatchType(objects.Service))
        if is_downed_host:
            if 'soft' in delete_type:
                mock_notify_legacy.assert_has_calls([
                    mock.call(self.compute_api.notifier, self.context,
                              inst, 'delete.start'),
                    mock.call(self.compute_api.notifier, self.context,
                              inst, 'delete.end')])
            else:
                mock_notify_legacy.assert_has_calls([
                    mock.call(self.compute_api.notifier, self.context,
                              inst, '%s.start' % delete_type),
                    mock.call(self.compute_api.notifier, self.context,
                              inst, '%s.end' % delete_type)])
            mock_deallocate.assert_called_once_with(self.context, inst)
            mock_inst_destroy.assert_called_once_with(
                self.context, instance_uuid, constraint=None,
                hard_delete=False)
            mock_get_inst.assert_called_with(self.context, instance_uuid)
            self.assertEqual(2, mock_get_inst.call_count)
            self.assertTrue(mock_get_inst.return_value.queued_for_delete)
            mock_save_im.assert_called_once_with()

        if cast:
            if delete_type == 'soft_delete':
                mock_soft_delete.assert_called_once_with(self.context, inst)
            elif delete_type in ['delete', 'force_delete']:
                mock_terminate.assert_called_once_with(
                    self.context, inst, [])

        if is_shelved:
            mock_image_delete.assert_called_once_with(self.context,
                                                      snapshot_id)
        if not cast and delete_type == 'delete':
            mock_notify.assert_has_calls([
                mock.call(self.context, inst, host='fake-mini',
                          source='nova-api',
                          action=delete_type, phase='start'),
                mock.call(self.context, inst, host='fake-mini',
                          source='nova-api',
                          action=delete_type, phase='end')])

    def test_delete(self):
        self._test_delete('delete')

    def test_delete_if_not_launched(self):
        self._test_delete('delete', launched_at=None)

    def test_delete_in_resizing(self):
        old_flavor = objects.Flavor(vcpus=1, memory_mb=512, extra_specs={})
        self._test_delete('delete',
                          task_state=task_states.RESIZE_FINISH,
                          old_flavor=old_flavor)

    def test_delete_in_resized(self):
        self._test_delete('delete', vm_state=vm_states.RESIZED)

    def test_delete_shelved(self):
        fake_sys_meta = {'shelved_image_id': SHELVED_IMAGE}
        self._test_delete('delete',
                          vm_state=vm_states.SHELVED,
                          system_metadata=fake_sys_meta)

    def test_delete_shelved_offloaded(self):
        fake_sys_meta = {'shelved_image_id': SHELVED_IMAGE}
        self._test_delete('delete',
                          vm_state=vm_states.SHELVED_OFFLOADED,
                          system_metadata=fake_sys_meta)

    def test_delete_shelved_image_not_found(self):
        fake_sys_meta = {'shelved_image_id': SHELVED_IMAGE_NOT_FOUND}
        self._test_delete('delete',
                          vm_state=vm_states.SHELVED_OFFLOADED,
                          system_metadata=fake_sys_meta)

    def test_delete_shelved_image_not_authorized(self):
        fake_sys_meta = {'shelved_image_id': SHELVED_IMAGE_NOT_AUTHORIZED}
        self._test_delete('delete',
                          vm_state=vm_states.SHELVED_OFFLOADED,
                          system_metadata=fake_sys_meta)

    def test_delete_shelved_exception(self):
        fake_sys_meta = {'shelved_image_id': SHELVED_IMAGE_EXCEPTION}
        self._test_delete('delete',
                          vm_state=vm_states.SHELVED,
                          system_metadata=fake_sys_meta)

    def test_delete_with_down_host(self):
        self._test_delete('delete', host='down-host')

    def test_delete_soft_with_down_host(self):
        self._test_delete('soft_delete', host='down-host')

    def test_delete_soft_in_resized(self):
        self._test_delete('soft_delete', vm_state=vm_states.RESIZED)

    def test_delete_soft(self):
        self._test_delete('soft_delete')

    def test_delete_forced(self):
        fake_sys_meta = {'shelved_image_id': SHELVED_IMAGE}
        for vm_state in self._get_vm_states():
            if vm_state in (vm_states.SHELVED, vm_states.SHELVED_OFFLOADED):
                self._test_delete('force_delete',
                                  vm_state=vm_state,
                                  system_metadata=fake_sys_meta)
            self._test_delete('force_delete', vm_state=vm_state)

    @mock.patch('nova.compute.api.API._delete_while_booting',
                return_value=False)
    @mock.patch('nova.compute.api.API._lookup_instance')
    @mock.patch('nova.objects.BlockDeviceMappingList.get_by_instance_uuid')
    @mock.patch('nova.objects.Instance.save')
    @mock.patch('nova.compute.utils.notify_about_instance_usage')
    @mock.patch('nova.objects.Service.get_by_compute_host')
    @mock.patch('nova.compute.api.API._local_delete')
    def test_delete_error_state_with_no_host(
            self, mock_local_delete, mock_service_get, _mock_notify,
            _mock_save, mock_bdm_get, mock_lookup, _mock_del_booting):
        # Instance in error state with no host should be a local delete
        # for non API cells
        inst = self._create_instance_obj(params=dict(vm_state=vm_states.ERROR,
                                                     host=None))
        mock_lookup.return_value = None, inst
        with mock.patch.object(self.compute_api.compute_rpcapi,
                               'terminate_instance') as mock_terminate:
            self.compute_api.delete(self.context, inst)
            mock_local_delete.assert_called_once_with(
                    self.context, inst, mock_bdm_get.return_value,
                    'delete', self.compute_api._do_delete)
            mock_terminate.assert_not_called()
        mock_service_get.assert_not_called()

    @mock.patch('nova.compute.api.API._delete_while_booting',
                return_value=False)
    @mock.patch('nova.compute.api.API._lookup_instance')
    @mock.patch('nova.objects.BlockDeviceMappingList.get_by_instance_uuid')
    @mock.patch('nova.objects.Instance.save')
    @mock.patch('nova.compute.utils.notify_about_instance_usage')
    @mock.patch('nova.objects.Service.get_by_compute_host')
    @mock.patch('nova.context.RequestContext.elevated')
    @mock.patch('nova.servicegroup.api.API.service_is_up', return_value=True)
    @mock.patch('nova.compute.api.API._record_action_start')
    @mock.patch('nova.compute.api.API._local_delete')
    def test_delete_error_state_with_host_set(
            self, mock_local_delete, _mock_record, mock_service_up,
            mock_elevated, mock_service_get, _mock_notify, _mock_save,
            mock_bdm_get, mock_lookup, _mock_del_booting):
        # Instance in error state with host set should be a non-local delete
        # for non API cells if the service is up
        inst = self._create_instance_obj(params=dict(vm_state=vm_states.ERROR,
                                                     host='fake-host'))
        mock_lookup.return_value = inst
        with mock.patch.object(self.compute_api.compute_rpcapi,
                               'terminate_instance') as mock_terminate:
            self.compute_api.delete(self.context, inst)
            mock_service_get.assert_called_once_with(
                    mock_elevated.return_value, 'fake-host')
            mock_service_up.assert_called_once_with(
                    mock_service_get.return_value)
            mock_terminate.assert_called_once_with(
                    self.context, inst, mock_bdm_get.return_value)
            mock_local_delete.assert_not_called()

    def test_delete_forced_when_task_state_is_not_none(self):
        for vm_state in self._get_vm_states():
            self._test_delete('force_delete', vm_state=vm_state,
                              task_state=task_states.RESIZE_MIGRATING)

    @mock.patch.object(compute_utils, 'notify_about_instance_action')
    @mock.patch.object(compute_utils, 'notify_about_instance_usage')
    @mock.patch.object(db, 'instance_destroy')
    @mock.patch.object(db, 'constraint')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    def test_delete_fast_if_host_not_set(self, mock_br_get, mock_save,
                                         mock_bdm_get, mock_cons,
                                         mock_inst_destroy,
                                         mock_notify_legacy, mock_notify):
        self.useFixture(nova_fixtures.AllServicesCurrent())
        inst = self._create_instance_obj()
        inst.host = ''
        updates = {'progress': 0, 'task_state': task_states.DELETING}

        mock_lookup = self.useFixture(
            fixtures.MockPatchObject(self.compute_api,
                                     '_lookup_instance')).mock

        mock_lookup.return_value = (None, inst)
        mock_bdm_get.return_value = objects.BlockDeviceMappingList()
        mock_br_get.side_effect = exception.BuildRequestNotFound(
            uuid=inst.uuid)

        mock_cons.return_value = 'constraint'
        delete_time = datetime.datetime(1955, 11, 5, 9, 30,
                                        tzinfo=iso8601.UTC)
        updates['deleted_at'] = delete_time
        updates['deleted'] = True
        fake_inst = fake_instance.fake_db_instance(**updates)
        mock_inst_destroy.return_value = fake_inst

        instance_uuid = inst.uuid
        self.compute_api.delete(self.context, inst)

        for k, v in updates.items():
            self.assertEqual(inst[k], v)

        mock_lookup.assert_called_once_with(self.context, instance_uuid)
        mock_bdm_get.assert_called_once_with(self.context, instance_uuid)
        mock_br_get.assert_called_once_with(self.context, instance_uuid)
        mock_save.assert_called_once_with()

        mock_notify_legacy.assert_has_calls([
            mock.call(self.compute_api.notifier, self.context,
                      inst, 'delete.start'),
            mock.call(self.compute_api.notifier, self.context,
                      inst, 'delete.end')])
        mock_notify.assert_has_calls([
            mock.call(self.context, inst, host='fake-mini',
                      source='nova-api', action='delete', phase='start'),
            mock.call(self.context, inst, host='fake-mini',
                      source='nova-api', action='delete', phase='end')])

        mock_cons.assert_called_once_with(host=mock.ANY)
        mock_inst_destroy.assert_called_once_with(
            self.context, instance_uuid, constraint='constraint',
            hard_delete=False)

    def _fake_do_delete(context, instance, bdms,
                        rservations=None, local=False):
        pass

    @mock.patch.object(compute_utils, 'notify_about_instance_action')
    @mock.patch.object(objects.BlockDeviceMapping, 'destroy')
    @mock.patch.object(cinder.API, 'detach')
    @mock.patch.object(compute_utils, 'notify_about_instance_usage')
    @mock.patch.object(neutron_api.API, 'deallocate_for_instance')
    @mock.patch.object(context.RequestContext, 'elevated')
    @mock.patch.object(objects.Instance, 'destroy')
    def test_local_delete_with_deleted_volume(
            self, mock_inst_destroy, mock_elevated, mock_dealloc,
            mock_notify_legacy, mock_detach, mock_bdm_destroy, mock_notify):
        bdms = [objects.BlockDeviceMapping(
                **fake_block_device.FakeDbBlockDeviceDict(
                {'id': 42, 'volume_id': 'volume_id',
                 'source_type': 'volume', 'destination_type': 'volume',
                 'delete_on_termination': False}))]

        inst = self._create_instance_obj()
        inst._context = self.context
        mock_elevated.return_value = self.context
        mock_detach.side_effect = exception.VolumeNotFound('volume_id')

        self.compute_api._local_delete(self.context, inst, bdms,
                                       'delete',
                                       self._fake_do_delete)

        mock_notify_legacy.assert_has_calls([
            mock.call(self.compute_api.notifier, self.context,
                      inst, 'delete.start'),
            mock.call(self.compute_api.notifier, self.context,
                      inst, 'delete.end')])
        mock_notify.assert_has_calls([
            mock.call(self.context, inst, host='fake-mini', source='nova-api',
                      action='delete', phase='start'),
            mock.call(self.context, inst, host='fake-mini', source='nova-api',
                      action='delete', phase='end')])

        mock_elevated.assert_has_calls([mock.call(), mock.call()])
        mock_detach.assert_called_once_with(mock.ANY, 'volume_id', inst.uuid)
        mock_bdm_destroy.assert_called_once_with()
        mock_inst_destroy.assert_called_once_with()

        mock_dealloc.assert_called_once_with(self.context, inst)

    @mock.patch.object(compute_utils, 'notify_about_instance_action')
    @mock.patch.object(objects.BlockDeviceMapping, 'destroy')
    @mock.patch.object(cinder.API, 'detach')
    @mock.patch.object(compute_utils, 'notify_about_instance_usage')
    @mock.patch.object(neutron_api.API, 'deallocate_for_instance')
    @mock.patch.object(context.RequestContext, 'elevated')
    @mock.patch.object(objects.Instance, 'destroy')
    @mock.patch.object(compute_utils, 'delete_arqs_if_needed')
    def test_local_delete_for_arqs(
            self, mock_del_arqs, mock_inst_destroy, mock_elevated,
            mock_dealloc, mock_notify_legacy, mock_detach,
            mock_bdm_destroy, mock_notify):
        inst = self._create_instance_obj()
        inst._context = self.context
        mock_elevated.return_value = self.context
        bdms = []
        self.compute_api._local_delete(self.context, inst, bdms,
                                       'delete', self._fake_do_delete)
        mock_del_arqs.assert_called_once_with(self.context, inst)

    @mock.patch.object(objects.BlockDeviceMapping, 'destroy')
    def test_local_cleanup_bdm_volumes_stashed_connector(self, mock_destroy):
        """Tests that we call volume_api.terminate_connection when we found
        a stashed connector in the bdm.connection_info dict.
        """
        inst = self._create_instance_obj()
        # create two fake bdms, one is a volume and one isn't, both will be
        # destroyed but we only cleanup the volume bdm in cinder
        conn_info = {'connector': {'host': inst.host}}
        vol_bdm = objects.BlockDeviceMapping(self.context, id=1,
                                             instance_uuid=inst.uuid,
                                             volume_id=uuids.volume_id,
                                             source_type='volume',
                                             destination_type='volume',
                                             delete_on_termination=True,
                                             connection_info=jsonutils.dumps(
                                                conn_info
                                             ),
                                             attachment_id=None,)
        loc_bdm = objects.BlockDeviceMapping(self.context, id=2,
                                             instance_uuid=inst.uuid,
                                             volume_id=uuids.volume_id2,
                                             source_type='blank',
                                             destination_type='local')
        bdms = objects.BlockDeviceMappingList(objects=[vol_bdm, loc_bdm])

        @mock.patch.object(self.compute_api.volume_api, 'terminate_connection')
        @mock.patch.object(self.compute_api.volume_api, 'detach')
        @mock.patch.object(self.compute_api.volume_api, 'delete')
        @mock.patch.object(self.context, 'elevated', return_value=self.context)
        def do_test(self, mock_elevated, mock_delete,
                    mock_detach, mock_terminate):
            self.compute_api._local_cleanup_bdm_volumes(
                bdms, inst, self.context)
            mock_terminate.assert_called_once_with(
                self.context, uuids.volume_id, conn_info['connector'])
            mock_detach.assert_called_once_with(
                self.context, uuids.volume_id, inst.uuid)
            mock_delete.assert_called_once_with(self.context, uuids.volume_id)
            self.assertEqual(2, mock_destroy.call_count)

        do_test(self)

    @mock.patch.object(objects.BlockDeviceMapping, 'destroy')
    def test_local_cleanup_bdm_volumes_with_attach_id(self, mock_destroy):
        """Tests that we call volume_api.attachment_delete when we have an
        attachment_id in the bdm.
        """
        instance = self._create_instance_obj()
        conn_info = {'connector': {'host': instance.host}}
        vol_bdm = objects.BlockDeviceMapping(
            self.context,
            id=1,
            instance_uuid=instance.uuid,
            volume_id=uuids.volume_id,
            source_type='volume',
            destination_type='volume',
            delete_on_termination=True,
            connection_info=jsonutils.dumps(conn_info),
            attachment_id=uuids.attachment_id)
        bdms = objects.BlockDeviceMappingList(objects=[vol_bdm])

        @mock.patch.object(self.compute_api.volume_api, 'delete')
        @mock.patch.object(self.compute_api.volume_api, 'attachment_delete')
        @mock.patch.object(self.context, 'elevated', return_value=self.context)
        def do_test(self, mock_elevated, mock_attach_delete, mock_delete):
            self.compute_api._local_cleanup_bdm_volumes(
                bdms, instance, self.context)

            mock_attach_delete.assert_called_once_with(
                self.context, vol_bdm.attachment_id)
            mock_delete.assert_called_once_with(
                self.context, vol_bdm.volume_id)
            mock_destroy.assert_called_once_with()
        do_test(self)

    @mock.patch.object(objects.BlockDeviceMapping, 'destroy')
    def test_local_cleanup_bdm_volumes_stashed_connector_host_none(
            self, mock_destroy):
        """Tests that we call volume_api.terminate_connection when we found
        a stashed connector in the bdm.connection_info dict.

        This tests the case where:

            1) the instance host is None
            2) the instance vm_state is one where we expect host to be None

        We allow a mismatch of the host in this situation if the instance is
        in a state where we expect its host to have been set to None, such
        as ERROR or SHELVED_OFFLOADED.
        """
        params = dict(host=None, vm_state=vm_states.ERROR)
        inst = self._create_instance_obj(params=params)
        conn_info = {'connector': {'host': 'orig-host'}}
        vol_bdm = objects.BlockDeviceMapping(self.context, id=1,
                                             instance_uuid=inst.uuid,
                                             volume_id=uuids.volume_id,
                                             source_type='volume',
                                             destination_type='volume',
                                             delete_on_termination=True,
                                             connection_info=jsonutils.dumps(
                                                conn_info),
                                             attachment_id=None)
        bdms = objects.BlockDeviceMappingList(objects=[vol_bdm])

        @mock.patch.object(self.compute_api.volume_api, 'terminate_connection')
        @mock.patch.object(self.compute_api.volume_api, 'detach')
        @mock.patch.object(self.compute_api.volume_api, 'delete')
        @mock.patch.object(self.context, 'elevated', return_value=self.context)
        def do_test(self, mock_elevated, mock_delete,
                    mock_detach, mock_terminate):
            self.compute_api._local_cleanup_bdm_volumes(
                bdms, inst, self.context)
            mock_terminate.assert_called_once_with(
                self.context, uuids.volume_id, conn_info['connector'])
            mock_detach.assert_called_once_with(
                self.context, uuids.volume_id, inst.uuid)
            mock_delete.assert_called_once_with(self.context, uuids.volume_id)
            mock_destroy.assert_called_once_with()

        do_test(self)

    def test_delete_disabled(self):
        # If 'disable_terminate' is True, log output is executed only and
        # just return immediately.
        inst = self._create_instance_obj()
        inst.disable_terminate = True
        self.compute_api.delete(self.context, inst)

    @mock.patch.object(objects.Instance, 'save',
                       side_effect=test.TestingException)
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid',
                       return_value=objects.BlockDeviceMappingList())
    def test_delete_soft_rollback(self, mock_get, mock_save):
        inst = self._create_instance_obj()

        delete_time = datetime.datetime(1955, 11, 5)
        self.useFixture(utils_fixture.TimeFixture(delete_time))

        self.assertRaises(test.TestingException,
                          self.compute_api.soft_delete, self.context, inst)
        mock_get.assert_called_once_with(self.context, inst.uuid)
        mock_save.assert_called_once_with()

    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    def test_attempt_delete_of_buildrequest_success(self, mock_get_by_inst):
        build_req_mock = mock.MagicMock()
        mock_get_by_inst.return_value = build_req_mock

        inst = self._create_instance_obj()
        self.assertTrue(
            self.compute_api._attempt_delete_of_buildrequest(self.context,
                                                             inst))
        self.assertTrue(build_req_mock.destroy.called)

    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    def test_attempt_delete_of_buildrequest_not_found(self, mock_get_by_inst):
        mock_get_by_inst.side_effect = exception.BuildRequestNotFound(
                                                                uuid='fake')

        inst = self._create_instance_obj()
        self.assertFalse(
            self.compute_api._attempt_delete_of_buildrequest(self.context,
                                                             inst))

    def test_attempt_delete_of_buildrequest_already_deleted(self):
        inst = self._create_instance_obj()
        build_req_mock = mock.MagicMock()
        build_req_mock.destroy.side_effect = exception.BuildRequestNotFound(
                                                                uuid='fake')
        with mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid',
                               return_value=build_req_mock):
            self.assertFalse(
                self.compute_api._attempt_delete_of_buildrequest(self.context,
                                                                 inst))
            self.assertTrue(build_req_mock.destroy.called)

    def test_delete_while_booting_buildreq_not_deleted(self):
        self.useFixture(nova_fixtures.AllServicesCurrent())
        inst = self._create_instance_obj()
        with mock.patch.object(self.compute_api,
                               '_attempt_delete_of_buildrequest',
                               return_value=False):
            self.assertFalse(
                self.compute_api._delete_while_booting(self.context, inst))

    def test_delete_while_booting_buildreq_deleted_instance_none(self):
        self.useFixture(nova_fixtures.AllServicesCurrent())
        inst = self._create_instance_obj()

        @mock.patch.object(self.compute_api, '_attempt_delete_of_buildrequest',
                           return_value=True)
        @mock.patch.object(self.compute_api, '_lookup_instance',
                           return_value=(None, None))
        def test(mock_lookup, mock_attempt):
            self.assertTrue(
                self.compute_api._delete_while_booting(self.context,
                                                       inst))

        test()

    def test_delete_while_booting_buildreq_deleted_instance_not_found(self):
        self.useFixture(nova_fixtures.AllServicesCurrent())
        inst = self._create_instance_obj()

        @mock.patch.object(self.compute_api, '_attempt_delete_of_buildrequest',
                           return_value=True)
        @mock.patch.object(self.compute_api, '_lookup_instance',
                           side_effect=exception.InstanceNotFound(
                               instance_id='fake'))
        def test(mock_lookup, mock_attempt):
            self.assertTrue(
                self.compute_api._delete_while_booting(self.context,
                                                       inst))

        test()

    @mock.patch('nova.compute.utils.notify_about_instance_delete')
    @mock.patch('nova.objects.Instance.destroy')
    def test_delete_instance_from_cell0(self, destroy_mock, notify_mock):
        """Tests the case that the instance does not have a host and was not
        deleted while building, so conductor put it into cell0 so the API has
        to delete the instance from cell0.
        """
        instance = self._create_instance_obj({'host': None})
        cell0 = objects.CellMapping(uuid=objects.CellMapping.CELL0_UUID)

        with test.nested(
            mock.patch.object(self.compute_api, '_delete_while_booting',
                              return_value=False),
            mock.patch.object(self.compute_api, '_lookup_instance',
                              return_value=(cell0, instance)),
        ) as (
            _delete_while_booting, _lookup_instance,
        ):
            self.compute_api._delete(
                self.context, instance, 'delete', mock.NonCallableMock())
            _delete_while_booting.assert_called_once_with(
                self.context, instance)
            _lookup_instance.assert_called_once_with(
                self.context, instance.uuid)
            notify_mock.assert_called_once_with(
                self.compute_api.notifier, self.context, instance)
            destroy_mock.assert_called_once_with()

    def test_delete_instance_while_booting_host_changes_lookup_fails(self):
        """Tests the case where the instance become scheduled while being
        destroyed but then the final lookup fails.
        """
        instance = self._create_instance_obj({'host': None})

        with test.nested(
            mock.patch.object(
                self.compute_api, '_delete_while_booting',
                side_effect=exception.ObjectActionError(
                    action="delete", reason="reason")),
            mock.patch.object(
                self.compute_api, '_lookup_instance',
                return_value=(None, None)),
            mock.patch.object(self.compute_api, '_local_delete_cleanup')
        ) as (
            _delete_while_booting, _lookup_instance, _local_delete_cleanup
        ):
            self.compute_api._delete(
                self.context, instance, 'delete', mock.NonCallableMock())

            _delete_while_booting.assert_called_once_with(
                self.context, instance)
            _lookup_instance.assert_called_once_with(
                self.context, instance.uuid)
            _local_delete_cleanup.assert_called_once_with(
                self.context, instance.uuid)

    @mock.patch.object(context, 'target_cell')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid',
                       side_effect=exception.InstanceMappingNotFound(
                           uuid='fake'))
    def test_lookup_instance_mapping_none(self, mock_map_get,
                                          mock_target_cell):
        instance = self._create_instance_obj()
        with mock.patch.object(objects.Instance, 'get_by_uuid',
                               return_value=instance) as mock_inst_get:

            cell, ret_instance = self.compute_api._lookup_instance(
                self.context, instance.uuid)
            self.assertEqual((None, instance), (cell, ret_instance))
            mock_inst_get.assert_called_once_with(self.context, instance.uuid)
            self.assertFalse(mock_target_cell.called)

    @mock.patch.object(context, 'target_cell')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid',
                       return_value=objects.InstanceMapping(cell_mapping=None))
    def test_lookup_instance_cell_mapping_none(self, mock_map_get,
                                          mock_target_cell):
        instance = self._create_instance_obj()
        with mock.patch.object(objects.Instance, 'get_by_uuid',
                               return_value=instance) as mock_inst_get:

            cell, ret_instance = self.compute_api._lookup_instance(
                self.context, instance.uuid)
            self.assertEqual((None, instance), (cell, ret_instance))
            mock_inst_get.assert_called_once_with(self.context, instance.uuid)
            self.assertFalse(mock_target_cell.called)

    @mock.patch.object(context, 'target_cell')
    def test_lookup_instance_cell_mapping(self, mock_target_cell):
        instance = self._create_instance_obj()
        mock_target_cell.return_value.__enter__.return_value = self.context

        inst_map = objects.InstanceMapping(
            cell_mapping=objects.CellMapping(database_connection='',
                                             transport_url='none'))

        @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid',
                           return_value=inst_map)
        @mock.patch.object(objects.Instance, 'get_by_uuid',
                           return_value=instance)
        def test(mock_inst_get, mock_map_get):
            cell, ret_instance = self.compute_api._lookup_instance(
                self.context, instance.uuid)
            expected_cell = inst_map.cell_mapping
            self.assertEqual((expected_cell, instance),
                             (cell, ret_instance))
            mock_inst_get.assert_called_once_with(self.context, instance.uuid)
            mock_target_cell.assert_called_once_with(self.context,
                                                     inst_map.cell_mapping)

        test()

    @mock.patch('nova.compute.api.API._get_source_compute_service')
    @mock.patch('nova.servicegroup.api.API.service_is_up', return_value=True)
    @mock.patch.object(objects.Migration, 'save')
    @mock.patch.object(objects.Migration, 'get_by_instance_and_status')
    @mock.patch.object(context.RequestContext, 'elevated')
    def _test_confirm_resize(self, mock_elevated, mock_get, mock_save,
                             mock_service_is_up, mock_get_service,
                             mig_ref_passed=False):
        params = dict(vm_state=vm_states.RESIZED)
        fake_inst = self._create_instance_obj(params=params)
        fake_mig = objects.Migration._from_db_object(
                self.context, objects.Migration(),
                test_migration.fake_db_migration())

        mock_record = self.useFixture(
            fixtures.MockPatchObject(self.compute_api,
                                     '_record_action_start')).mock
        mock_confirm = self.useFixture(
            fixtures.MockPatchObject(self.compute_api.compute_rpcapi,
                                     'confirm_resize')).mock

        mock_elevated.return_value = self.context
        if not mig_ref_passed:
            mock_get.return_value = fake_mig

        def _check_mig(expected_task_state=None):
            self.assertEqual('confirming', fake_mig.status)

        mock_save.side_effect = _check_mig

        if mig_ref_passed:
            self.compute_api.confirm_resize(self.context, fake_inst,
                                            migration=fake_mig)
        else:
            self.compute_api.confirm_resize(self.context, fake_inst)

        mock_elevated.assert_called_once_with()
        mock_service_is_up.assert_called_once_with(
            mock_get_service.return_value)
        mock_save.assert_called_once_with()
        mock_record.assert_called_once_with(self.context, fake_inst,
                                            'confirmResize')
        mock_confirm.assert_called_once_with(self.context, fake_inst, fake_mig,
                                             'compute-source')

        if not mig_ref_passed:
            mock_get.assert_called_once_with(self.context, fake_inst['uuid'],
                                             'finished')

    def test_confirm_resize(self):
        self._test_confirm_resize()

    def test_confirm_resize_with_migration_ref(self):
        self._test_confirm_resize(mig_ref_passed=True)

    @mock.patch('nova.objects.HostMapping.get_by_host',
                return_value=objects.HostMapping(
                    cell_mapping=objects.CellMapping(
                        database_connection='fake://', transport_url='none://',
                        uuid=uuids.cell_uuid)))
    @mock.patch('nova.objects.Service.get_by_compute_host')
    def test_get_source_compute_service(self, mock_service_get, mock_hm_get):
        # First start with a same-cell migration.
        migration = objects.Migration(source_compute='source.host',
                                      cross_cell_move=False)
        self.compute_api._get_source_compute_service(self.context, migration)
        mock_hm_get.assert_not_called()
        mock_service_get.assert_called_once_with(self.context, 'source.host')
        # Make sure the context was not targeted.
        ctxt = mock_service_get.call_args[0][0]
        self.assertIsNone(ctxt.cell_uuid)

        # Now test with a cross-cell migration.
        mock_service_get.reset_mock()
        migration.cross_cell_move = True
        self.compute_api._get_source_compute_service(self.context, migration)
        mock_hm_get.assert_called_once_with(self.context, 'source.host')
        mock_service_get.assert_called_once_with(
            test.MatchType(context.RequestContext), 'source.host')
        # Make sure the context was targeted.
        ctxt = mock_service_get.call_args[0][0]
        self.assertEqual(uuids.cell_uuid, ctxt.cell_uuid)

    @mock.patch('nova.virt.hardware.numa_get_constraints')
    @mock.patch('nova.network.neutron.API.get_requested_resource_for_instance',
                return_value=[])
    @mock.patch('nova.availability_zones.get_host_availability_zone',
                return_value='nova')
    @mock.patch('nova.objects.Quotas.check_deltas')
    @mock.patch('nova.objects.Migration.get_by_instance_and_status')
    @mock.patch('nova.context.RequestContext.elevated')
    @mock.patch('nova.objects.RequestSpec.get_by_instance_uuid')
    def _test_revert_resize(
            self, mock_get_reqspec, mock_elevated, mock_get_migration,
            mock_check, mock_get_host_az, mock_get_requested_resources,
            mock_get_numa, same_flavor):
        params = dict(vm_state=vm_states.RESIZED)
        fake_inst = self._create_instance_obj(params=params)
        fake_inst.info_cache.network_info = model.NetworkInfo([
            model.VIF(id=uuids.port1, profile={'allocation': uuids.rp})])
        fake_mig = objects.Migration._from_db_object(
                self.context, objects.Migration(),
                test_migration.fake_db_migration())
        fake_reqspec = objects.RequestSpec()
        fake_reqspec.flavor = fake_inst.flavor
        fake_numa_topology = objects.InstanceNUMATopology(cells=[
            objects.InstanceNUMACell(
                id=0, cpuset=set([0]), pcpuset=set(), memory=512,
                pagesize=None,
                cpu_pinning_raw=None, cpuset_reserved=None, cpu_policy=None,
                cpu_thread_policy=None)])

        if same_flavor:
            fake_inst.old_flavor = fake_inst.flavor
        else:
            fake_inst.old_flavor = self._create_flavor(
                id=200, flavorid='new-flavor-id', name='new_flavor',
                disabled=False, extra_specs={'hw:numa_nodes': '1'})

        mock_elevated.return_value = self.context
        mock_get_migration.return_value = fake_mig
        mock_get_reqspec.return_value = fake_reqspec
        mock_get_numa.return_value = fake_numa_topology

        def _check_reqspec():
            if same_flavor:
                assert_func = self.assertNotEqual
            else:
                assert_func = self.assertEqual

            assert_func(fake_numa_topology, fake_reqspec.numa_topology)
            assert_func(fake_inst.old_flavor, fake_reqspec.flavor)

        def _check_state(expected_task_state=None):
            self.assertEqual(task_states.RESIZE_REVERTING,
                             fake_inst.task_state)

        def _check_mig():
            self.assertEqual('reverting', fake_mig.status)

        with test.nested(
            mock.patch.object(fake_reqspec, 'save',
                              side_effect=_check_reqspec),
            mock.patch.object(fake_inst, 'save', side_effect=_check_state),
            mock.patch.object(fake_mig, 'save', side_effect=_check_mig),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(self.compute_api.compute_rpcapi, 'revert_resize')
        ) as (mock_reqspec_save, mock_inst_save, mock_mig_save,
              mock_record_action, mock_revert_resize):
            self.compute_api.revert_resize(self.context, fake_inst)

            mock_elevated.assert_called_once_with()
            mock_get_migration.assert_called_once_with(
                self.context, fake_inst['uuid'], 'finished')
            mock_inst_save.assert_called_once_with(expected_task_state=[None])
            mock_mig_save.assert_called_once_with()
            mock_get_reqspec.assert_called_once_with(
                self.context, fake_inst.uuid)
            if same_flavor:
                # if we are not changing flavors through the revert, we
                # shouldn't attempt to rebuild the NUMA topology since it won't
                # have changed
                mock_get_numa.assert_not_called()
            else:
                # not so if the flavor *has* changed though
                mock_get_numa.assert_called_once_with(
                    fake_inst.old_flavor, mock.ANY)
            mock_record_action.assert_called_once_with(self.context, fake_inst,
                                                       'revertResize')
            mock_revert_resize.assert_called_once_with(
                self.context, fake_inst, fake_mig, 'compute-dest',
                mock_get_reqspec.return_value)
            mock_get_requested_resources.assert_called_once_with(
                self.context, fake_inst.uuid)
            self.assertEqual(
                [],
                mock_get_reqspec.return_value.requested_resources)

    def test_revert_resize(self):
        self._test_revert_resize(same_flavor=False)

    def test_revert_resize_same_flavor(self):
        """Test behavior when reverting a migration or a resize to the same
        flavor.
        """
        self._test_revert_resize(same_flavor=True)

    @mock.patch('nova.network.neutron.API.get_requested_resource_for_instance')
    @mock.patch('nova.availability_zones.get_host_availability_zone',
                return_value='nova')
    @mock.patch('nova.objects.Quotas.check_deltas')
    @mock.patch('nova.objects.Migration.get_by_instance_and_status')
    @mock.patch('nova.context.RequestContext.elevated')
    @mock.patch('nova.objects.RequestSpec')
    def test_revert_resize_concurrent_fail(
            self, mock_reqspec, mock_elevated, mock_get_migration, mock_check,
            mock_get_host_az, mock_get_requested_resources):
        params = dict(vm_state=vm_states.RESIZED)
        fake_inst = self._create_instance_obj(params=params)
        fake_inst.info_cache.network_info = model.NetworkInfo([])
        fake_inst.old_flavor = fake_inst.flavor
        fake_mig = objects.Migration._from_db_object(
                self.context, objects.Migration(),
                test_migration.fake_db_migration())

        mock_elevated.return_value = self.context
        mock_get_migration.return_value = fake_mig

        exc = exception.UnexpectedTaskStateError(
            instance_uuid=fake_inst['uuid'],
            actual={'task_state': task_states.RESIZE_REVERTING},
            expected={'task_state': [None]})

        with mock.patch.object(
                fake_inst, 'save', side_effect=exc) as mock_inst_save:
            self.assertRaises(exception.UnexpectedTaskStateError,
                          self.compute_api.revert_resize,
                          self.context,
                          fake_inst)

            mock_elevated.assert_called_once_with()
            mock_get_migration.assert_called_once_with(
                self.context, fake_inst['uuid'], 'finished')
            mock_inst_save.assert_called_once_with(expected_task_state=[None])
            mock_get_requested_resources.assert_not_called()

    # TODO(stephenfin): This is a terrible, terrible function and should be
    # broken up into its constituent parts
    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch('nova.virt.hardware.numa_get_constraints')
    @mock.patch('nova.compute.api.API._allow_resize_to_same_host')
    @mock.patch('nova.compute.utils.is_volume_backed_instance',
                return_value=False)
    @mock.patch('nova.compute.api.API._validate_flavor_image_nostatus')
    @mock.patch('nova.objects.Migration')
    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(quotas_obj.Quotas, 'limit_check_project_and_user')
    @mock.patch.object(quotas_obj.Quotas, 'count_as_dict')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(compute_utils, 'upsize_quota_delta')
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.ComputeNodeList, 'get_all_by_host')
    def _test_resize(self, mock_get_all_by_host,
                     mock_get_by_instance_uuid, mock_get_flavor, mock_upsize,
                     mock_inst_save, mock_count, mock_limit, mock_record,
                     mock_migration, mock_validate, mock_is_vol_backed,
                     mock_allow_resize_to_same_host,
                     mock_get_numa,
                     flavor_id_passed=True,
                     same_host=False, allow_same_host=False,
                     project_id=None,
                     same_flavor=False,
                     clean_shutdown=True,
                     host_name=None,
                     request_spec=True,
                     requested_destination=False,
                     allow_cross_cell_resize=False):

        self.flags(allow_resize_to_same_host=allow_same_host)
        mock_allow_resize_to_same_host.return_value = allow_same_host

        params = {}
        if project_id is not None:
            # To test instance w/ different project id than context (admin)
            params['project_id'] = project_id
        fake_inst = self._create_instance_obj(params=params)
        fake_numa_topology = objects.InstanceNUMATopology(cells=[
            objects.InstanceNUMACell(
                id=0, cpuset=set([0]), pcpuset=set(), memory=512,
                pagesize=None,
                cpu_pinning_raw=None, cpuset_reserved=None, cpu_policy=None,
                cpu_thread_policy=None)])

        mock_resize = self.useFixture(
            fixtures.MockPatchObject(self.compute_api.compute_task_api,
                                     'resize_instance')).mock
        mock_get_numa.return_value = fake_numa_topology

        if host_name:
            mock_get_all_by_host.return_value = [objects.ComputeNode(
                host=host_name, hypervisor_hostname='hypervisor_host')]

        current_flavor = fake_inst.get_flavor()
        if flavor_id_passed:
            new_flavor = self._create_flavor(
                id=200, flavorid='new-flavor-id', name='new_flavor',
                disabled=False, extra_specs={'hw:numa_nodes': '1'})
            if same_flavor:
                new_flavor.id = current_flavor.id
            mock_get_flavor.return_value = new_flavor
        else:
            new_flavor = current_flavor

        if not (flavor_id_passed and same_flavor):
            project_id, user_id = quotas_obj.ids_from_instance(self.context,
                                                               fake_inst)
            if flavor_id_passed:
                mock_upsize.return_value = {'cores': 0, 'ram': 0}

                proj_count = {'instances': 1, 'cores': current_flavor.vcpus,
                              'ram': current_flavor.memory_mb}
                user_count = proj_count.copy()
                mock_count.return_value = {'project': proj_count,
                                           'user': user_count}

            def _check_state(expected_task_state=None):
                self.assertEqual(task_states.RESIZE_PREP,
                                 fake_inst.task_state)
                self.assertEqual(fake_inst.progress, 0)

            mock_inst_save.side_effect = _check_state

            if allow_same_host:
                filter_properties = {'ignore_hosts': []}
            else:
                filter_properties = {'ignore_hosts': [fake_inst['host']]}

            if request_spec:
                fake_spec = objects.RequestSpec()
                if requested_destination:
                    cell1 = objects.CellMapping(uuid=uuids.cell1, name='cell1')
                    fake_spec.requested_destination = objects.Destination(
                        host='dummy_host', node='dummy_node', cell=cell1)
                mock_get_by_instance_uuid.return_value = fake_spec
            else:
                mock_get_by_instance_uuid.side_effect = (
                    exception.RequestSpecNotFound(instance_uuid=fake_inst.id))
                fake_spec = None

            scheduler_hint = {'filter_properties': filter_properties}

        mock_allow_cross_cell_resize = self.useFixture(
            fixtures.MockPatchObject(
                self.compute_api, '_allow_cross_cell_resize')).mock
        mock_allow_cross_cell_resize.return_value = allow_cross_cell_resize

        if flavor_id_passed:
            self.compute_api.resize(self.context, fake_inst,
                                    flavor_id='new-flavor-id',
                                    clean_shutdown=clean_shutdown,
                                    host_name=host_name)
        else:
            if request_spec:
                self.compute_api.resize(self.context, fake_inst,
                                        clean_shutdown=clean_shutdown,
                                        host_name=host_name)
            else:
                self.assertRaises(exception.RequestSpecNotFound,
                                  self.compute_api.resize,
                                  self.context, fake_inst,
                                  clean_shutdown=clean_shutdown,
                                  host_name=host_name)

        if request_spec:
            if allow_same_host:
                self.assertEqual([], fake_spec.ignore_hosts)
            else:
                self.assertEqual([fake_inst['host']], fake_spec.ignore_hosts)

            if host_name is None:
                self.assertIsNotNone(fake_spec.requested_destination)
            else:
                self.assertIn('host', fake_spec.requested_destination)
                self.assertEqual(host_name,
                                 fake_spec.requested_destination.host)
                self.assertIn('node', fake_spec.requested_destination)
                self.assertEqual('hypervisor_host',
                                 fake_spec.requested_destination.node)
            self.assertEqual(
                allow_cross_cell_resize,
                fake_spec.requested_destination.allow_cross_cell_move)
            mock_allow_resize_to_same_host.assert_called_once()

            if flavor_id_passed and not same_flavor:
                mock_get_numa.assert_called_once_with(new_flavor, mock.ANY)
            else:
                mock_get_numa.assert_not_called()

        if host_name:
            mock_get_all_by_host.assert_called_once_with(
                self.context, host_name, True)

        if flavor_id_passed:
            mock_get_flavor.assert_called_once_with('new-flavor-id',
                                                    read_deleted='no')

        if not (flavor_id_passed and same_flavor):
            if flavor_id_passed:
                mock_upsize.assert_called_once_with(
                    test.MatchType(objects.Flavor),
                    test.MatchType(objects.Flavor))
                image_meta = utils.get_image_from_system_metadata(
                    fake_inst.system_metadata)
                if not same_flavor:
                    mock_validate.assert_called_once_with(
                        self.context, image_meta, new_flavor, root_bdm=None,
                        validate_pci=True)
                # mock.ANY might be 'instances', 'cores', or 'ram'
                # depending on how the deltas dict is iterated in check_deltas
                mock_count.assert_called_once_with(
                    self.context, mock.ANY, project_id, user_id=user_id)
                # The current and new flavor have the same cores/ram
                req_cores = current_flavor.vcpus
                req_ram = current_flavor.memory_mb
                values = {'cores': req_cores, 'ram': req_ram}
                mock_limit.assert_called_once_with(
                    self.context, user_values=values, project_values=values,
                    project_id=project_id, user_id=user_id)

                mock_inst_save.assert_called_once_with(
                    expected_task_state=[None])
            else:
                # This is a migration
                mock_validate.assert_not_called()

            mock_migration.assert_not_called()

            mock_get_by_instance_uuid.assert_called_once_with(self.context,
                                                              fake_inst.uuid)

            if flavor_id_passed:
                mock_record.assert_called_once_with(self.context, fake_inst,
                                                    'resize')
            else:
                if request_spec:
                    mock_record.assert_called_once_with(
                        self.context, fake_inst, 'migrate')
                else:
                    mock_record.assert_not_called()

            if request_spec:
                mock_resize.assert_called_once_with(
                    self.context, fake_inst,
                    scheduler_hint=scheduler_hint,
                    flavor=test.MatchType(objects.Flavor),
                    clean_shutdown=clean_shutdown,
                    request_spec=fake_spec, do_cast=True)
            else:
                mock_resize.assert_not_called()

    def test_resize(self):
        self._test_resize()

    def test_resize_same_host_and_allowed(self):
        self._test_resize(same_host=True, allow_same_host=True)

    def test_resize_same_host_and_not_allowed(self):
        self._test_resize(same_host=True, allow_same_host=False)

    def test_resize_different_project_id(self):
        self._test_resize(project_id='different')

    def test_resize_forced_shutdown(self):
        self._test_resize(clean_shutdown=False)

    def test_resize_allow_cross_cell_resize_true(self):
        self._test_resize(allow_cross_cell_resize=True)

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch('nova.compute.flavors.get_flavor_by_flavor_id')
    @mock.patch('nova.objects.Quotas.count_as_dict')
    @mock.patch('nova.objects.Quotas.limit_check_project_and_user')
    def test_resize_quota_check(self, mock_check, mock_count, mock_get):
        self.flags(cores=1, group='quota')
        self.flags(ram=2048, group='quota')
        proj_count = {'instances': 1, 'cores': 1, 'ram': 1024}
        user_count = proj_count.copy()
        mock_count.return_value = {'project': proj_count,
                                   'user': user_count}

        cur_flavor = objects.Flavor(id=1, name='foo', vcpus=1, memory_mb=512,
                                    root_gb=10, disabled=False, extra_specs={})
        fake_inst = self._create_instance_obj()
        fake_inst.flavor = cur_flavor
        new_flavor = objects.Flavor(id=2, name='bar', vcpus=1, memory_mb=2048,
                                    root_gb=10, disabled=False, extra_specs={})
        mock_get.return_value = new_flavor
        mock_check.side_effect = exception.OverQuota(
                overs=['ram'], quotas={'cores': 1, 'ram': 2048},
                usages={'instances': 1, 'cores': 1, 'ram': 2048},
                headroom={'ram': 2048})

        self.assertRaises(exception.TooManyInstances, self.compute_api.resize,
                          self.context, fake_inst, flavor_id='new')
        mock_check.assert_called_once_with(
                self.context,
                user_values={'cores': 1, 'ram': 2560},
                project_values={'cores': 1, 'ram': 2560},
                project_id=fake_inst.project_id, user_id=fake_inst.user_id)

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch('nova.compute.utils.is_volume_backed_instance',
                new=mock.Mock(return_value=False))
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    def test_resize__with_accelerator(self, mock_get_flavor):
        """Ensure resizes are rejected if either flavor requests accelerator.
        """
        fake_inst = self._create_instance_obj()
        new_flavor = self._create_flavor(
            id=200, flavorid='new-flavor-id', name='new_flavor',
            disabled=False, extra_specs={'accel:device_profile': 'dp'})
        mock_get_flavor.return_value = new_flavor

        self.assertRaises(
            exception.ForbiddenWithAccelerators,
            self.compute_api.resize,
            self.context, fake_inst, flavor_id=new_flavor.flavorid)

    def _test_migrate(self, *args, **kwargs):
        self._test_resize(*args, flavor_id_passed=False, **kwargs)

    def test_migrate(self):
        self._test_migrate()

    def test_migrate_same_host_and_allowed(self):
        self._test_migrate(same_host=True, allow_same_host=True)

    def test_migrate_same_host_and_not_allowed(self):
        self._test_migrate(same_host=True, allow_same_host=False)

    def test_migrate_different_project_id(self):
        self._test_migrate(project_id='different')

    def test_migrate_request_spec_not_found(self):
        self._test_migrate(request_spec=False)

    def test_migrate_with_requested_destination(self):
        # RequestSpec has requested_destination
        self._test_migrate(requested_destination=True)

    def test_migrate_with_host_name(self):
        self._test_migrate(host_name='target_host')

    def test_migrate_with_host_name_allow_cross_cell_resize_true(self):
        self._test_migrate(host_name='target_host',
                           allow_cross_cell_resize=True)

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch.object(objects.ComputeNodeList, 'get_all_by_host',
                       side_effect=exception.ComputeHostNotFound(
                           host='nonexistent_host'))
    def test_migrate_nonexistent_host(self, mock_get_all_by_host):
        fake_inst = self._create_instance_obj()
        self.assertRaises(exception.ComputeHostNotFound,
                          self.compute_api.resize, self.context,
                          fake_inst, host_name='nonexistent_host')

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(quotas_obj.Quotas, 'limit_check_project_and_user')
    @mock.patch.object(quotas_obj.Quotas, 'count_as_dict')
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    def test_resize_invalid_flavor_fails(self, mock_get_flavor, mock_count,
                                         mock_limit, mock_record, mock_save):
        mock_resize = self.useFixture(fixtures.MockPatchObject(
            self.compute_api.compute_task_api, 'resize_instance')).mock

        fake_inst = self._create_instance_obj()
        exc = exception.FlavorNotFound(flavor_id='flavor-id')
        mock_get_flavor.side_effect = exc

        self.assertRaises(exception.FlavorNotFound,
                          self.compute_api.resize, self.context,
                          fake_inst, flavor_id='flavor-id')
        mock_get_flavor.assert_called_once_with('flavor-id', read_deleted='no')
        # Should never reach these.
        mock_count.assert_not_called()
        mock_limit.assert_not_called()
        mock_record.assert_not_called()
        mock_resize.assert_not_called()
        mock_save.assert_not_called()

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(quotas_obj.Quotas, 'limit_check_project_and_user')
    @mock.patch.object(quotas_obj.Quotas, 'count_as_dict')
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    def test_resize_disabled_flavor_fails(self, mock_get_flavor, mock_count,
                                          mock_limit, mock_record, mock_save):
        mock_resize = self.useFixture(fixtures.MockPatchObject(
            self.compute_api.compute_task_api, 'resize_instance')).mock

        fake_inst = self._create_instance_obj()
        fake_flavor = self._create_flavor(id=200, flavorid='flavor-id',
                            name='foo', disabled=True)
        mock_get_flavor.return_value = fake_flavor

        self.assertRaises(exception.FlavorNotFound,
                          self.compute_api.resize, self.context,
                          fake_inst, flavor_id='flavor-id')
        mock_get_flavor.assert_called_once_with('flavor-id', read_deleted='no')
        # Should never reach these.
        mock_count.assert_not_called()
        mock_limit.assert_not_called()
        mock_record.assert_not_called()
        mock_resize.assert_not_called()
        mock_save.assert_not_called()

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    def test_resize_to_zero_disk_flavor_fails(self, get_flavor_by_flavor_id):
        fake_inst = self._create_instance_obj()
        fake_flavor = self._create_flavor(id=200, flavorid='flavor-id',
                            name='foo', root_gb=0)

        get_flavor_by_flavor_id.return_value = fake_flavor

        with mock.patch.object(compute_utils, 'is_volume_backed_instance',
                               return_value=False):
            self.assertRaises(exception.CannotResizeDisk,
                              self.compute_api.resize, self.context,
                              fake_inst, flavor_id='flavor-id')

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch('nova.compute.api.API._validate_flavor_image_nostatus')
    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch('nova.compute.api.API._record_action_start')
    @mock.patch('nova.conductor.conductor_api.ComputeTaskAPI.resize_instance')
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    def test_resize_to_zero_disk_flavor_volume_backed(self,
                                                      get_flavor_by_flavor_id,
                                                      resize_instance_mock,
                                                      record_mock,
                                                      get_by_inst,
                                                      validate_mock):
        params = dict(image_ref='')
        fake_inst = self._create_instance_obj(params=params)

        fake_flavor = self._create_flavor(id=200, flavorid='flavor-id',
                                          name='foo', root_gb=0)

        get_flavor_by_flavor_id.return_value = fake_flavor

        @mock.patch.object(compute_utils, 'is_volume_backed_instance',
                           return_value=True)
        @mock.patch.object(fake_inst, 'save')
        def do_test(mock_save, mock_volume):
            self.compute_api.resize(self.context, fake_inst,
                                    flavor_id='flavor-id')
            mock_volume.assert_called_once_with(self.context, fake_inst)

        do_test()

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(quotas_obj.Quotas,
                       'limit_check_project_and_user')
    @mock.patch.object(quotas_obj.Quotas, 'count_as_dict')
    @mock.patch.object(compute_utils, 'upsize_quota_delta')
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    def test_resize_quota_exceeds_fails(self, mock_get_flavor, mock_upsize,
                                        mock_count, mock_limit, mock_record,
                                        mock_save):
        mock_resize = self.useFixture(fixtures.MockPatchObject(
            self.compute_api.compute_task_api, 'resize_instance')).mock

        fake_inst = self._create_instance_obj()
        fake_flavor = self._create_flavor(id=200, flavorid='flavor-id',
                            name='foo', disabled=False)
        mock_get_flavor.return_value = fake_flavor
        deltas = dict(cores=0)
        mock_upsize.return_value = deltas
        quotas = {'cores': 0}
        overs = ['cores']
        over_quota_args = dict(quotas=quotas,
                               usages={'instances': 1, 'cores': 1, 'ram': 512},
                               overs=overs)

        proj_count = {'instances': 1, 'cores': fake_inst.flavor.vcpus,
                      'ram': fake_inst.flavor.memory_mb}
        user_count = proj_count.copy()
        mock_count.return_value = {'project': proj_count, 'user': user_count}

        req_cores = fake_inst.flavor.vcpus
        req_ram = fake_inst.flavor.memory_mb
        values = {'cores': req_cores, 'ram': req_ram}
        mock_limit.side_effect = exception.OverQuota(**over_quota_args)

        self.assertRaises(exception.TooManyInstances,
                          self.compute_api.resize, self.context,
                          fake_inst, flavor_id='flavor-id')

        mock_save.assert_not_called()
        mock_get_flavor.assert_called_once_with('flavor-id', read_deleted='no')
        mock_upsize.assert_called_once_with(test.MatchType(objects.Flavor),
                                            test.MatchType(objects.Flavor))
        # mock.ANY might be 'instances', 'cores', or 'ram'
        # depending on how the deltas dict is iterated in check_deltas
        mock_count.assert_called_once_with(self.context, mock.ANY,
                                           fake_inst.project_id,
                                           user_id=fake_inst.user_id)
        mock_limit.assert_called_once_with(self.context, user_values=values,
                                           project_values=values,
                                           project_id=fake_inst.project_id,
                                           user_id=fake_inst.user_id)
        # Should never reach these.
        mock_record.assert_not_called()
        mock_resize.assert_not_called()

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    @mock.patch.object(compute_utils, 'upsize_quota_delta')
    @mock.patch.object(quotas_obj.Quotas, 'count_as_dict')
    @mock.patch.object(quotas_obj.Quotas, 'limit_check_project_and_user')
    def test_resize_quota_exceeds_fails_instance(self, mock_check, mock_count,
                                                 mock_upsize, mock_flavor):
        fake_inst = self._create_instance_obj()
        fake_flavor = self._create_flavor(id=200, flavorid='flavor-id',
                            name='foo', disabled=False)
        mock_flavor.return_value = fake_flavor
        deltas = dict(cores=1, ram=1)
        mock_upsize.return_value = deltas
        quotas = {'instances': 1, 'cores': -1, 'ram': -1}
        overs = ['ram']
        over_quota_args = dict(quotas=quotas,
                               usages={'instances': 1, 'cores': 1, 'ram': 512},
                               overs=overs)
        mock_check.side_effect = exception.OverQuota(**over_quota_args)

        with mock.patch.object(fake_inst, 'save') as mock_save:
            self.assertRaises(exception.TooManyInstances,
                              self.compute_api.resize, self.context,
                              fake_inst, flavor_id='flavor-id')
            self.assertFalse(mock_save.called)

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    @mock.patch.object(objects.Quotas, 'count_as_dict')
    @mock.patch.object(objects.Quotas, 'limit_check_project_and_user')
    def test_resize_instance_quota_exceeds_with_multiple_resources(
            self, mock_check, mock_count, mock_get_flavor):
        quotas = {'cores': 1, 'ram': 512}
        overs = ['cores', 'ram']
        over_quota_args = dict(quotas=quotas,
                               usages={'instances': 1, 'cores': 1, 'ram': 512},
                               overs=overs)

        proj_count = {'instances': 1, 'cores': 1, 'ram': 512}
        user_count = proj_count.copy()
        mock_count.return_value = {'project': proj_count, 'user': user_count}
        mock_check.side_effect = exception.OverQuota(**over_quota_args)
        mock_get_flavor.return_value = self._create_flavor(id=333,
                                                           vcpus=3,
                                                           memory_mb=1536)
        try:
            self.compute_api.resize(self.context, self._create_instance_obj(),
                                    'fake_flavor_id')
        except exception.TooManyInstances as e:
            self.assertEqual('cores, ram', e.kwargs['overs'])
            self.assertEqual('2, 1024', e.kwargs['req'])
            self.assertEqual('1, 512', e.kwargs['used'])
            self.assertEqual('1, 512', e.kwargs['allowed'])
            mock_get_flavor.assert_called_once_with('fake_flavor_id',
                                                    read_deleted="no")
        else:
            self.fail("Exception not raised")

    # TODO(huaqiang): Remove in Wallaby
    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    @mock.patch.object(compute_utils, 'is_volume_backed_instance',
                       new=mock.Mock(return_value=True))
    @mock.patch('nova.objects.service.get_minimum_version_all_cells',
                new=mock.Mock(return_value=51))
    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(utils, 'get_image_from_system_metadata')
    @mock.patch.object(flavors, 'get_flavor_by_flavor_id')
    def test_resize_mixed_instance_compute_version_low_fails(
            self, mock_get_flavor, mock_image, mock_spec):
        """Check resizing an mixed policy instance fails if some
        nova-compute node is not upgraded to Victory yet.
        """
        numa_topology = objects.InstanceNUMATopology(cells=[
            objects.InstanceNUMACell(
                id=0, cpuset=set(), pcpuset=set([0, 1, 2, 3]), memory=1024,
                pagesize=None, cpu_pinning_raw=None, cpuset_reserved=None,
                cpu_policy='dedicated', cpu_thread_policy=None)
        ])
        flavor = objects.Flavor(id=1, name='current', vcpus=4, memory_mb=1024,
                                root_gb=10, disabled=False,
                                extra_specs={
                                    "hw:cpu_policy": "dedicated"
                                })
        new_flavor = objects.Flavor(id=2, name='new', vcpus=4, memory_mb=1024,
                                    root_gb=10, disabled=False,
                                    extra_specs={
                                        "hw:cpu_policy": "mixed",
                                        "hw:cpu_dedicated_mask": "^0-2",
                                    })
        image = {"properties": {}}
        params = {
            'vcpus': 4,
            'numa_topology': numa_topology,
        }

        mock_image.return_value = image
        mock_get_flavor.return_value = new_flavor
        instance = self._create_instance_obj(params=params, flavor=flavor)
        self.assertRaises(exception.MixedInstanceNotSupportByComputeService,
                          self.compute_api.resize, self.context,
                          instance, flavor_id='flavor-new')
        mock_spec.assert_called_once()

    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(objects.Instance, 'save')
    def test_pause(self, mock_save, mock_record):
        # Ensure instance can be paused.
        instance = self._create_instance_obj()
        self.assertEqual(instance.vm_state, vm_states.ACTIVE)
        self.assertIsNone(instance.task_state)

        rpcapi = self.compute_api.compute_rpcapi

        mock_pause = self.useFixture(
            fixtures.MockPatchObject(rpcapi, 'pause_instance')).mock

        with mock.patch.object(rpcapi, 'pause_instance') as mock_pause:
            self.compute_api.pause(self.context, instance)

        self.assertEqual(vm_states.ACTIVE, instance.vm_state)
        self.assertEqual(task_states.PAUSING,
                         instance.task_state)
        mock_save.assert_called_once_with(expected_task_state=[None])
        mock_record.assert_called_once_with(self.context, instance,
                                            instance_actions.PAUSE)
        mock_pause.assert_called_once_with(self.context, instance)

    def _test_pause_fails(self, vm_state):
        params = dict(vm_state=vm_state)
        instance = self._create_instance_obj(params=params)
        self.assertIsNone(instance.task_state)
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.pause,
                          self.context, instance)

    def test_pause_fails_invalid_states(self):
        invalid_vm_states = self._get_vm_states(set([vm_states.ACTIVE]))
        for state in invalid_vm_states:
            self._test_pause_fails(state)

    @mock.patch.object(compute_api.API, '_record_action_start')
    @mock.patch.object(objects.Instance, 'save')
    def test_unpause(self, mock_save, mock_record):
        # Ensure instance can be unpaused.
        params = dict(vm_state=vm_states.PAUSED)
        instance = self._create_instance_obj(params=params)
        self.assertEqual(instance.vm_state, vm_states.PAUSED)
        self.assertIsNone(instance.task_state)

        rpcapi = self.compute_api.compute_rpcapi

        with mock.patch.object(rpcapi, 'unpause_instance') as mock_unpause:
            self.compute_api.unpause(self.context, instance)

        self.assertEqual(vm_states.PAUSED, instance.vm_state)
        self.assertEqual(task_states.UNPAUSING, instance.task_state)
        mock_save.assert_called_once_with(expected_task_state=[None])
        mock_record.assert_called_once_with(self.context, instance,
                                            instance_actions.UNPAUSE)
        mock_unpause.assert_called_once_with(self.context, instance)

    def test_get_diagnostics_none_host(self):
        instance = self._create_instance_obj()
        instance.host = None
        self.assertRaises(exception.InstanceNotReady,
                          self.compute_api.get_diagnostics,
                          self.context, instance)

    def test_get_instance_diagnostics_none_host(self):
        instance = self._create_instance_obj()
        instance.host = None
        self.assertRaises(exception.InstanceNotReady,
                          self.compute_api.get_instance_diagnostics,
                          self.context, instance)

    @mock.patch.object(objects.ComputeNodeList, 'get_all_by_host')
    def test_live_migrate_active_vm_state(self, mock_nodelist):
        instance = self._create_instance_obj()
        self._live_migrate_instance(instance)

    @mock.patch.object(objects.ComputeNodeList, 'get_all_by_host')
    def test_live_migrate_paused_vm_state(self, mock_nodelist):
        paused_state = dict(vm_state=vm_states.PAUSED)
        instance = self._create_instance_obj(params=paused_state)
        self._live_migrate_instance(instance)

    @mock.patch.object(objects.ComputeNodeList, 'get_all_by_host')
    @mock.patch.object(compute_utils, 'add_instance_fault_from_exc')
    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.InstanceAction, 'action_start')
    @mock.patch.object(objects.Instance, 'save')
    def test_live_migrate_messaging_timeout(self, _save, _action, get_spec,
                                            add_instance_fault_from_exc,
                                            mock_nodelist):
        instance = self._create_instance_obj()
        api = conductor.api.ComputeTaskAPI

        with mock.patch.object(api, 'live_migrate_instance',
                               side_effect=oslo_exceptions.MessagingTimeout):
            self.assertRaises(oslo_exceptions.MessagingTimeout,
                              self.compute_api.live_migrate,
                              self.context, instance,
                              host_name='fake_dest_host',
                              block_migration=True, disk_over_commit=True)
            add_instance_fault_from_exc.assert_called_once_with(
                self.context,
                instance,
                mock.ANY)

    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.InstanceAction, 'action_start')
    @mock.patch.object(objects.ComputeNodeList, 'get_all_by_host',
                       side_effect=exception.ComputeHostNotFound(
                           host='fake_host'))
    def test_live_migrate_computehost_notfound(self, mock_nodelist,
                                               mock_action,
                                               mock_get_spec):
        instance = self._create_instance_obj()
        self.assertRaises(exception.ComputeHostNotFound,
                          self.compute_api.live_migrate,
                          self.context, instance,
                          host_name='fake_host',
                          block_migration='auto',
                          disk_over_commit=False)
        self.assertIsNone(instance.task_state)

    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(objects.InstanceAction, 'action_start')
    def _live_migrate_instance(self, instance, _save, _action, get_spec):
        api = conductor.api.ComputeTaskAPI
        fake_spec = objects.RequestSpec()
        get_spec.return_value = fake_spec
        with mock.patch.object(api, 'live_migrate_instance') as task:
            self.compute_api.live_migrate(self.context, instance,
                                          block_migration=True,
                                          disk_over_commit=True,
                                          host_name='fake_dest_host')
            self.assertEqual(task_states.MIGRATING, instance.task_state)
            task.assert_called_once_with(self.context, instance,
                                         'fake_dest_host',
                                         block_migration=True,
                                         disk_over_commit=True,
                                         request_spec=fake_spec,
                                         async_=False)

    def _get_volumes_for_test_swap_volume(self):
        volumes = {}
        volumes[uuids.old_volume] = {
            'id': uuids.old_volume,
            'display_name': 'old_volume',
            'attach_status': 'attached',
            'size': 5,
            'status': 'in-use',
            'multiattach': False,
            'attachments': {uuids.vol_instance: {'attachment_id': 'fakeid'}}}
        volumes[uuids.new_volume] = {
            'id': uuids.new_volume,
            'display_name': 'new_volume',
            'attach_status': 'detached',
            'size': 5,
            'status': 'available',
            'multiattach': False}

        return volumes

    def _get_instance_for_test_swap_volume(self):
        return fake_instance.fake_instance_obj(None, **{
                   'vm_state': vm_states.ACTIVE,
                   'launched_at': timeutils.utcnow(),
                   'locked': False,
                   'availability_zone': 'fake_az',
                   'uuid': uuids.vol_instance,
                   'task_state': None})

    def _test_swap_volume_for_precheck_with_exception(
            self, exc, instance_update=None, volume_update=None):
        volumes = self._get_volumes_for_test_swap_volume()
        instance = self._get_instance_for_test_swap_volume()
        if instance_update:
            instance.update(instance_update)
        if volume_update:
            volumes[volume_update['target']].update(volume_update['value'])

        self.assertRaises(exc, self.compute_api.swap_volume, self.context,
                          instance, volumes[uuids.old_volume],
                          volumes[uuids.new_volume])
        self.assertEqual('in-use', volumes[uuids.old_volume]['status'])
        self.assertEqual('available', volumes[uuids.new_volume]['status'])

    def test_swap_volume_with_invalid_server_state(self):
        # Should fail if VM state is not valid
        self._test_swap_volume_for_precheck_with_exception(
            exception.InstanceInvalidState,
            instance_update={'vm_state': vm_states.BUILDING})
        self._test_swap_volume_for_precheck_with_exception(
            exception.InstanceInvalidState,
            instance_update={'vm_state': vm_states.STOPPED})
        self._test_swap_volume_for_precheck_with_exception(
            exception.InstanceInvalidState,
            instance_update={'vm_state': vm_states.SUSPENDED})

    def test_swap_volume_with_another_server_volume(self):
        # Should fail if old volume's instance_uuid is not that of the instance
        self._test_swap_volume_for_precheck_with_exception(
            exception.InvalidVolume,
            volume_update={
                'target': uuids.old_volume,
                'value': {
                    'attachments': {
                        uuids.vol_instance_2: {'attachment_id': 'fakeid'}}}})

    def test_swap_volume_with_new_volume_attached(self):
        # Should fail if new volume is attached
        self._test_swap_volume_for_precheck_with_exception(
            exception.InvalidVolume,
            volume_update={'target': uuids.new_volume,
                           'value': {'attach_status': 'attached'}})

    def test_swap_volume_with_smaller_new_volume(self):
        # Should fail if new volume is smaller than the old volume
        self._test_swap_volume_for_precheck_with_exception(
            exception.InvalidVolume,
            volume_update={'target': uuids.new_volume,
                           'value': {'size': 4}})

    def test_swap_volume_with_swap_volume_error(self):
        self._test_swap_volume(expected_exception=AttributeError)

    def test_swap_volume_volume_api_usage(self):
        self._test_swap_volume()

    def test_swap_volume_volume_api_usage_new_attach_flow(self):
        self._test_swap_volume(attachment_id=uuids.attachment_id)

    def test_swap_volume_with_swap_volume_error_new_attach_flow(self):
        self._test_swap_volume(expected_exception=AttributeError,
                               attachment_id=uuids.attachment_id)

    def test_swap_volume_new_vol_already_attached_new_flow(self):
        self._test_swap_volume(attachment_id=uuids.attachment_id,
                               volume_already_attached=True)

    def _test_swap_volume(self, expected_exception=None, attachment_id=None,
                          volume_already_attached=False):
        volumes = self._get_volumes_for_test_swap_volume()
        instance = self._get_instance_for_test_swap_volume()

        def fake_vol_api_begin_detaching(context, volume_id):
            self.assertTrue(uuidutils.is_uuid_like(volume_id))
            volumes[volume_id]['status'] = 'detaching'

        def fake_vol_api_roll_detaching(context, volume_id):
            self.assertTrue(uuidutils.is_uuid_like(volume_id))
            if volumes[volume_id]['status'] == 'detaching':
                volumes[volume_id]['status'] = 'in-use'

        def fake_vol_api_reserve(context, volume_id):
            self.assertTrue(uuidutils.is_uuid_like(volume_id))
            self.assertEqual('available', volumes[volume_id]['status'])
            volumes[volume_id]['status'] = 'attaching'

        def fake_vol_api_unreserve(context, volume_id):
            self.assertTrue(uuidutils.is_uuid_like(volume_id))
            if volumes[volume_id]['status'] == 'attaching':
                volumes[volume_id]['status'] = 'available'

        def fake_vol_api_attachment_create(context, volume_id, instance_id):
            self.assertTrue(uuidutils.is_uuid_like(volume_id))
            self.assertEqual('available', volumes[volume_id]['status'])
            volumes[volume_id]['status'] = 'reserved'
            return {'id': uuids.attachment_id}

        def fake_vol_api_attachment_delete(context, attachment_id):
            self.assertTrue(uuidutils.is_uuid_like(attachment_id))
            if volumes[uuids.new_volume]['status'] == 'reserved':
                volumes[uuids.new_volume]['status'] = 'available'

        def fake_volume_is_attached(context, instance, volume_id):
            if volume_already_attached:
                raise exception.InvalidVolume(reason='Volume already attached')
            else:
                pass

        @mock.patch.object(compute_api.API, '_record_action_start')
        @mock.patch.object(self.compute_api.compute_rpcapi, 'swap_volume',
                           return_value=True)
        @mock.patch.object(self.compute_api.volume_api, 'unreserve_volume',
                           side_effect=fake_vol_api_unreserve)
        @mock.patch.object(self.compute_api.volume_api, 'attachment_delete',
                           side_effect=fake_vol_api_attachment_delete)
        @mock.patch.object(self.compute_api.volume_api, 'reserve_volume',
                           side_effect=fake_vol_api_reserve)
        @mock.patch.object(self.compute_api,
                           '_check_volume_already_attached',
                           side_effect=fake_volume_is_attached)
        @mock.patch.object(self.compute_api.volume_api, 'attachment_create',
                           side_effect=fake_vol_api_attachment_create)
        @mock.patch.object(self.compute_api.volume_api, 'roll_detaching',
                           side_effect=fake_vol_api_roll_detaching)
        @mock.patch.object(objects.BlockDeviceMapping,
                           'get_by_volume_and_instance')
        @mock.patch.object(self.compute_api.volume_api, 'begin_detaching',
                           side_effect=fake_vol_api_begin_detaching)
        def _do_test(mock_begin_detaching, mock_get_by_volume_and_instance,
                     mock_roll_detaching, mock_attachment_create,
                     mock_check_volume_attached, mock_reserve_volume,
                     mock_attachment_delete, mock_unreserve_volume,
                     mock_swap_volume, mock_record):
            bdm = objects.BlockDeviceMapping(
                        **fake_block_device.FakeDbBlockDeviceDict(
                        {'no_device': False, 'volume_id': '1', 'boot_index': 0,
                         'connection_info': 'inf', 'device_name': '/dev/vda',
                         'source_type': 'volume', 'destination_type': 'volume',
                         'tag': None, 'attachment_id': attachment_id},
                        anon=True))
            mock_get_by_volume_and_instance.return_value = bdm
            if expected_exception:
                mock_swap_volume.side_effect = AttributeError()
                self.assertRaises(expected_exception,
                                  self.compute_api.swap_volume, self.context,
                                  instance, volumes[uuids.old_volume],
                                  volumes[uuids.new_volume])
                self.assertEqual('in-use', volumes[uuids.old_volume]['status'])
                self.assertEqual('available',
                                 volumes[uuids.new_volume]['status'])
                # Make assertions about what was called if there was or was not
                # a Cinder 3.44 style attachment provided.
                if attachment_id is None:
                    # Old style attachment, so unreserve was called and
                    # attachment_delete was not called.
                    mock_unreserve_volume.assert_called_once_with(
                        self.context, uuids.new_volume)
                    mock_attachment_delete.assert_not_called()
                else:
                    # New style attachment, so unreserve was not called and
                    # attachment_delete was called.
                    mock_unreserve_volume.assert_not_called()
                    mock_attachment_delete.assert_called_once_with(
                        self.context, attachment_id)

                # Assert the call to the rpcapi.
                mock_swap_volume.assert_called_once_with(
                    self.context, instance=instance,
                    old_volume_id=uuids.old_volume,
                    new_volume_id=uuids.new_volume,
                    new_attachment_id=attachment_id)
                mock_record.assert_called_once_with(
                    self.context, instance, instance_actions.SWAP_VOLUME)
            elif volume_already_attached:
                self.assertRaises(exception.InvalidVolume,
                                  self.compute_api.swap_volume, self.context,
                                  instance, volumes[uuids.old_volume],
                                  volumes[uuids.new_volume])
                self.assertEqual('in-use', volumes[uuids.old_volume]['status'])
                self.assertEqual('available',
                                 volumes[uuids.new_volume]['status'])
                mock_check_volume_attached.assert_called_once_with(
                    self.context, instance, volumes[uuids.new_volume])
                mock_roll_detaching.assert_called_once_with(self.context,
                                                            uuids.old_volume)
            else:
                self.compute_api.swap_volume(self.context, instance,
                                             volumes[uuids.old_volume],
                                             volumes[uuids.new_volume])
                # Make assertions about what was called if there was or was not
                # a Cinder 3.44 style attachment provided.
                if attachment_id is None:
                    # Old style attachment, so reserve was called and
                    # attachment_create was not called.
                    mock_reserve_volume.assert_called_once_with(
                        self.context, uuids.new_volume)
                    mock_attachment_create.assert_not_called()
                    mock_check_volume_attached.assert_not_called()
                else:
                    # New style attachment, so reserve was not called and
                    # attachment_create was called.
                    mock_reserve_volume.assert_not_called()
                    mock_check_volume_attached.assert_called_once_with(
                        self.context, instance, volumes[uuids.new_volume])
                    mock_attachment_create.assert_called_once_with(
                        self.context, uuids.new_volume, instance.uuid)

                # Assert the call to the rpcapi.
                mock_swap_volume.assert_called_once_with(
                    self.context, instance=instance,
                    old_volume_id=uuids.old_volume,
                    new_volume_id=uuids.new_volume,
                    new_attachment_id=attachment_id)
                mock_record.assert_called_once_with(
                     self.context, instance, instance_actions.SWAP_VOLUME)

        _do_test()

    def test_count_attachments_for_swap_not_found_and_readonly(self):
        """Tests that attachment records that aren't found are considered
        read/write by default. Also tests that read-only attachments are
        not counted.
        """
        ctxt = context.get_admin_context()
        volume = {
            'attachments': {
                uuids.server1: {
                    'attachment_id': uuids.attachment1
                },
                uuids.server2: {
                    'attachment_id': uuids.attachment2
                }
            }
        }

        def fake_attachment_get(_context, attachment_id):
            if attachment_id == uuids.attachment1:
                raise exception.VolumeAttachmentNotFound(
                    attachment_id=attachment_id)
            return {'attach_mode': 'ro'}

        with mock.patch.object(self.compute_api.volume_api, 'attachment_get',
                               side_effect=fake_attachment_get) as mock_get:
            self.assertEqual(
                1, self.compute_api._count_attachments_for_swap(ctxt, volume))
        mock_get.assert_has_calls([
            mock.call(ctxt, uuids.attachment1),
            mock.call(ctxt, uuids.attachment2)], any_order=True)

    @mock.patch('nova.volume.cinder.API.attachment_get',
                new_callable=mock.NonCallableMock)  # asserts not called
    def test_count_attachments_for_swap_no_query(self, mock_attachment_get):
        """Tests that if the volume has <2 attachments, we don't query
        the attachments for their attach_mode value.
        """
        volume = {}
        self.assertEqual(
            0, self.compute_api._count_attachments_for_swap(
                mock.sentinel.context, volume))
        volume = {
            'attachments': {
                uuids.server: {
                    'attachment_id': uuids.attach1
                }
            }
        }
        self.assertEqual(
            1, self.compute_api._count_attachments_for_swap(
                mock.sentinel.context, volume))

    @mock.patch.object(compute_utils, 'is_volume_backed_instance')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(image_api.API, 'create')
    @mock.patch.object(utils, 'get_image_from_system_metadata')
    @mock.patch.object(compute_api.API, '_record_action_start')
    def _test_snapshot_and_backup(self, mock_record, mock_get_image,
                                  mock_create, mock_save, mock_is_volume,
                                  is_snapshot=True, with_base_ref=False,
                                  min_ram=None, min_disk=None,
                                  create_fails=False,
                                  instance_vm_state=vm_states.ACTIVE):
        params = dict(locked=True)
        instance = self._create_instance_obj(params=params)
        instance.vm_state = instance_vm_state

        # Test non-inheritable properties, 'user_id' should also not be
        # carried from sys_meta into image property...since it should be set
        # explicitly by _create_image() in compute api.
        fake_image_meta = {
            'name': 'base-name',
            'disk_format': 'fake',
            'container_format': 'fake',
            'properties': {
                'user_id': 'meow',
                'foo': 'bar',
                'blah': 'bug?',
                'cache_in_nova': 'dropped',
                'bittorrent': 'dropped',
                'img_signature_hash_method': 'dropped',
                'img_signature': 'dropped',
                'img_signature_key_type': 'dropped',
                'img_signature_certificate_uuid': 'dropped'
            },
        }
        image_type = is_snapshot and 'snapshot' or 'backup'
        sent_meta = {
            'visibility': 'private',
            'name': 'fake-name',
            'disk_format': 'fake',
            'container_format': 'fake',
            'properties': {
                'user_id': self.context.user_id,
                'instance_uuid': instance.uuid,
                'image_type': image_type,
                'foo': 'bar',
                'blah': 'bug?',
                'cow': 'moo',
                'cat': 'meow',
            },

        }
        if is_snapshot:
            if min_ram is not None:
                fake_image_meta['min_ram'] = min_ram
                sent_meta['min_ram'] = min_ram
            if min_disk is not None:
                fake_image_meta['min_disk'] = min_disk
                sent_meta['min_disk'] = min_disk
            sent_meta.pop('disk_format', None)
            sent_meta.pop('container_format', None)
        else:
            sent_meta['properties']['backup_type'] = 'fake-backup-type'

        extra_props = dict(cow='moo', cat='meow')

        if not is_snapshot:
            mock_is_volume.return_value = False

        mock_get_image.return_value = fake_image_meta

        fake_image = dict(id='fake-image-id')
        if create_fails:
            mock_create.side_effect = test.TestingException()
        else:
            mock_create.return_value = fake_image

        def check_state(expected_task_state=None):
            expected_state = (is_snapshot and
                              task_states.IMAGE_SNAPSHOT_PENDING or
                              task_states.IMAGE_BACKUP)
            self.assertEqual(expected_state, instance.task_state)

        if not create_fails:
            mock_save.side_effect = check_state

        if is_snapshot:
            with mock.patch.object(self.compute_api.compute_rpcapi,
                                   'snapshot_instance') as mock_snapshot:
                if create_fails:
                    self.assertRaises(test.TestingException,
                                      self.compute_api.snapshot,
                                      self.context, instance, 'fake-name',
                                      extra_properties=extra_props)
                else:
                    res = self.compute_api.snapshot(
                        self.context, instance, 'fake-name',
                        extra_properties=extra_props)
                    mock_record.assert_called_once_with(
                        self.context, instance, instance_actions.CREATE_IMAGE)
                    mock_snapshot.assert_called_once_with(
                        self.context, instance, fake_image['id'])
        else:
            with mock.patch.object(self.compute_api.compute_rpcapi,
                                   'backup_instance') as mock_backup:
                if create_fails:
                    self.assertRaises(test.TestingException,
                                      self.compute_api.backup,
                                      self.context, instance,
                                      'fake-name', 'fake-backup-type',
                                      'fake-rotation',
                                      extra_properties=extra_props)
                else:
                    res = self.compute_api.backup(
                        self.context, instance, 'fake-name',
                        'fake-backup-type', 'fake-rotation',
                        extra_properties=extra_props)
                    mock_record.assert_called_once_with(
                        self.context, instance, instance_actions.BACKUP)
                    mock_backup.assert_called_once_with(
                        self.context, instance, fake_image['id'],
                        'fake-backup-type', 'fake-rotation')

        mock_create.assert_called_once_with(self.context, sent_meta)
        mock_get_image.assert_called_once_with(instance.system_metadata)

        if not is_snapshot:
            mock_is_volume.assert_called_once_with(self.context, instance)
        else:
            mock_is_volume.assert_not_called()

        if not create_fails:
            self.assertEqual(fake_image, res)
            mock_save.assert_called_once_with(expected_task_state=[None])

    def test_snapshot(self):
        self._test_snapshot_and_backup()

    def test_snapshot_fails(self):
        self._test_snapshot_and_backup(create_fails=True)

    def test_snapshot_invalid_state(self):
        instance = self._create_instance_obj()
        instance.vm_state = vm_states.ACTIVE
        instance.task_state = task_states.IMAGE_SNAPSHOT
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.snapshot,
                          self.context, instance, 'fake-name')
        instance.vm_state = vm_states.ACTIVE
        instance.task_state = task_states.IMAGE_BACKUP
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.snapshot,
                          self.context, instance, 'fake-name')
        instance.vm_state = vm_states.BUILDING
        instance.task_state = None
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.snapshot,
                          self.context, instance, 'fake-name')

    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(compute_utils, 'create_image')
    @mock.patch.object(compute_rpcapi.ComputeAPI,
                       'snapshot_instance')
    def test_vm_deleting_while_creating_snapshot(self,
                                                snapshot_instance,
                                                _create_image, save):
        instance = self._create_instance_obj()
        save.side_effect = exception.UnexpectedDeletingTaskStateError(
            "Exception")
        _create_image.return_value = dict(id='fake-image-id')
        with mock.patch.object(self.compute_api.image_api,
                               'delete') as image_delete:
            self.assertRaises(exception.InstanceInvalidState,
                              self.compute_api.snapshot,
                              self.context,
                              instance, 'fake-image')
            image_delete.assert_called_once_with(self.context,
                                                 'fake-image-id')

    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(compute_utils, 'create_image')
    @mock.patch.object(compute_rpcapi.ComputeAPI,
                       'snapshot_instance')
    def test_vm_deleted_while_creating_snapshot(self,
                                                snapshot_instance,
                                                _create_image, save):
        instance = self._create_instance_obj()
        save.side_effect = exception.InstanceNotFound(
            "Exception")
        _create_image.return_value = dict(id='fake-image-id')
        with mock.patch.object(self.compute_api.image_api,
                               'delete') as image_delete:
            self.assertRaises(exception.InstanceInvalidState,
                              self.compute_api.snapshot,
                              self.context,
                              instance, 'fake-image')
            image_delete.assert_called_once_with(self.context,
                                                 'fake-image-id')

    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(compute_utils, 'create_image')
    @mock.patch.object(compute_rpcapi.ComputeAPI,
                       'snapshot_instance')
    def test_vm_deleted_while_snapshot_and_snapshot_delete_failed(self,
                                                        snapshot_instance,
                                                        _create_image, save):
        instance = self._create_instance_obj()
        save.side_effect = exception.InstanceNotFound(instance_id='fake')
        _create_image.return_value = dict(id='fake-image-id')
        with mock.patch.object(self.compute_api.image_api,
                               'delete') as image_delete:
            image_delete.side_effect = test.TestingException()
            self.assertRaises(exception.InstanceInvalidState,
                              self.compute_api.snapshot,
                              self.context,
                              instance, 'fake-image')
            image_delete.assert_called_once_with(self.context,
                                                 'fake-image-id')

    def test_snapshot_with_base_image_ref(self):
        self._test_snapshot_and_backup(with_base_ref=True)

    def test_snapshot_min_ram(self):
        self._test_snapshot_and_backup(min_ram=42)

    def test_snapshot_min_disk(self):
        self._test_snapshot_and_backup(min_disk=42)

    def test_backup(self):
        for state in [vm_states.ACTIVE, vm_states.STOPPED,
                      vm_states.PAUSED, vm_states.SUSPENDED]:
            self._test_snapshot_and_backup(is_snapshot=False,
                                           instance_vm_state=state)

    def test_backup_fails(self):
        self._test_snapshot_and_backup(is_snapshot=False, create_fails=True)

    def test_backup_invalid_state(self):
        instance = self._create_instance_obj()
        instance.vm_state = vm_states.ACTIVE
        instance.task_state = task_states.IMAGE_SNAPSHOT
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.backup,
                          self.context, instance, 'fake-name',
                          'fake', 'fake')
        instance.vm_state = vm_states.ACTIVE
        instance.task_state = task_states.IMAGE_BACKUP
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.backup,
                          self.context, instance, 'fake-name',
                          'fake', 'fake')
        instance.vm_state = vm_states.BUILDING
        instance.task_state = None
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.backup,
                          self.context, instance, 'fake-name',
                          'fake', 'fake')

    def test_backup_with_base_image_ref(self):
        self._test_snapshot_and_backup(is_snapshot=False,
                                       with_base_ref=True)

    def test_backup_volume_backed_instance(self):
        instance = self._create_instance_obj()

        with mock.patch.object(compute_utils, 'is_volume_backed_instance',
                               return_value=True) as mock_is_volume_backed:
            self.assertRaises(exception.InvalidRequest,
                              self.compute_api.backup, self.context,
                              instance, 'fake-name', 'weekly',
                              3, extra_properties={})
            mock_is_volume_backed.assert_called_once_with(self.context,
                                                          instance)

    def _test_snapshot_volume_backed(self, quiesce_required=False,
                                     quiesce_fails=False,
                                     quiesce_unsupported=False,
                                     vm_state=vm_states.ACTIVE,
                                     snapshot_fails=False, limits=None):
        fake_sys_meta = {'image_min_ram': '11',
                         'image_min_disk': '22',
                         'image_container_format': 'ami',
                         'image_disk_format': 'ami',
                         'image_ram_disk': 'fake_ram_disk_id',
                         'image_bdm_v2': 'True',
                         'image_block_device_mapping': '[]',
                         'image_mappings': '[]',
                         'image_cache_in_nova': 'True'}
        if quiesce_required:
            fake_sys_meta['image_os_require_quiesce'] = 'yes'
        params = dict(locked=True, vm_state=vm_state,
                      system_metadata=fake_sys_meta)
        instance = self._create_instance_obj(params=params)
        instance['root_device_name'] = 'vda'

        instance_bdms = []

        expect_meta = {
            'name': 'test-snapshot',
            'properties': {'root_device_name': 'vda',
                           'ram_disk': 'fake_ram_disk_id'},
            'size': 0,
            'min_disk': '22',
            'visibility': 'private',
            'min_ram': '11',
        }
        if quiesce_required:
            expect_meta['properties']['os_require_quiesce'] = 'yes'

        quiesced = [False, False]
        quiesce_expected = not (quiesce_unsupported or quiesce_fails) \
                           and vm_state == vm_states.ACTIVE

        @classmethod
        def fake_bdm_list_get_by_instance_uuid(cls, context, instance_uuid):
            return obj_base.obj_make_list(context, cls(),
                    objects.BlockDeviceMapping, instance_bdms)

        def fake_image_create(_self, context, image_meta, data=None):
            self.assertThat(image_meta, matchers.DictMatches(expect_meta))

        def fake_volume_create_snapshot(self, context, volume_id, name,
                                        description):
            if snapshot_fails:
                raise exception.OverQuota(overs="snapshots")
            return {'id': '%s-snapshot' % volume_id}

        def fake_quiesce_instance(context, instance):
            if quiesce_unsupported:
                raise exception.InstanceQuiesceNotSupported(
                    instance_id=instance['uuid'], reason='unsupported')
            if quiesce_fails:
                raise oslo_exceptions.MessagingTimeout('quiece timeout')
            quiesced[0] = True

        def fake_unquiesce_instance(context, instance, mapping=None):
            quiesced[1] = True

        def fake_get_absolute_limits(context):
            if limits is not None:
                return limits
            return {"totalSnapshotsUsed": 0, "maxTotalSnapshots": 10}

        self.stub_out('nova.objects.BlockDeviceMappingList'
                      '.get_by_instance_uuid',
                      fake_bdm_list_get_by_instance_uuid)
        self.stub_out('nova.image.glance.API.create', fake_image_create)
        self.stub_out('nova.volume.cinder.API.get',
                      lambda self, context, volume_id:
                          {'id': volume_id, 'display_description': ''})
        self.stub_out('nova.volume.cinder.API.create_snapshot_force',
                       fake_volume_create_snapshot)
        self.useFixture(fixtures.MockPatchObject(
            self.compute_api.compute_rpcapi, 'quiesce_instance',
            side_effect=fake_quiesce_instance))
        self.useFixture(fixtures.MockPatchObject(
            self.compute_api.compute_rpcapi, 'unquiesce_instance',
            side_effect=fake_unquiesce_instance))
        self.useFixture(nova_fixtures.GlanceFixture(self))

        with test.nested(
                mock.patch.object(compute_api.API, '_record_action_start'),
                mock.patch.object(compute_utils, 'EventReporter')) as (
            mock_record, mock_event):
            # No block devices defined
            self.compute_api.snapshot_volume_backed(
                self.context, instance, 'test-snapshot')

        mock_record.assert_called_once_with(self.context,
                                            instance,
                                            instance_actions.CREATE_IMAGE)
        mock_event.assert_called_once_with(self.context,
                                           'api_snapshot_instance',
                                           CONF.host,
                                           instance.uuid,
                                           graceful_exit=False)

        bdm = fake_block_device.FakeDbBlockDeviceDict(
                {'no_device': False, 'volume_id': '1', 'boot_index': 0,
                 'connection_info': 'inf', 'device_name': '/dev/vda',
                 'source_type': 'volume', 'destination_type': 'volume',
                 'tag': None})
        instance_bdms.append(bdm)

        expect_meta['properties']['bdm_v2'] = True
        expect_meta['properties']['block_device_mapping'] = []
        expect_meta['properties']['block_device_mapping'].append(
            {'guest_format': None, 'boot_index': 0, 'no_device': None,
             'image_id': None, 'volume_id': None, 'disk_bus': None,
             'volume_size': None, 'source_type': 'snapshot',
             'device_type': None, 'snapshot_id': '1-snapshot',
             'device_name': '/dev/vda',
             'destination_type': 'volume', 'delete_on_termination': False,
             'tag': None, 'volume_type': None})

        limits_patcher = mock.patch.object(
            self.compute_api.volume_api, 'get_absolute_limits',
            side_effect=fake_get_absolute_limits)
        limits_patcher.start()
        self.addCleanup(limits_patcher.stop)

        with test.nested(
                mock.patch.object(compute_api.API, '_record_action_start'),
                mock.patch.object(compute_utils, 'EventReporter')) as (
                mock_record, mock_event):
            # All the db_only fields and the volume ones are removed
            if snapshot_fails:
                self.assertRaises(exception.OverQuota,
                                  self.compute_api.snapshot_volume_backed,
                                  self.context, instance, "test-snapshot")
            else:
                self.compute_api.snapshot_volume_backed(
                    self.context, instance, 'test-snapshot')

        self.assertEqual(quiesce_expected, quiesced[0])
        self.assertEqual(quiesce_expected, quiesced[1])

        mock_record.assert_called_once_with(self.context,
                                            instance,
                                            instance_actions.CREATE_IMAGE)
        mock_event.assert_called_once_with(self.context,
                                           'api_snapshot_instance',
                                           CONF.host,
                                           instance.uuid,
                                           graceful_exit=False)

        instance.system_metadata['image_mappings'] = jsonutils.dumps(
            [{'virtual': 'ami', 'device': 'vda'},
             {'device': 'vda', 'virtual': 'ephemeral0'},
             {'device': 'vdb', 'virtual': 'swap'},
             {'device': 'vdc', 'virtual': 'ephemeral1'}])[:255]
        instance.system_metadata['image_block_device_mapping'] = (
            jsonutils.dumps(
                [{'source_type': 'snapshot', 'destination_type': 'volume',
                  'guest_format': None, 'device_type': 'disk', 'boot_index': 1,
                  'disk_bus': 'ide', 'device_name': '/dev/vdf',
                  'delete_on_termination': True, 'snapshot_id': 'snapshot-2',
                  'volume_id': None, 'volume_size': 100, 'image_id': None,
                  'no_device': None, 'volume_type': None}])[:255])

        bdm = fake_block_device.FakeDbBlockDeviceDict(
                {'no_device': False, 'volume_id': None, 'boot_index': -1,
                 'connection_info': 'inf', 'device_name': '/dev/vdh',
                 'source_type': 'blank', 'destination_type': 'local',
                 'guest_format': 'swap', 'delete_on_termination': True,
                 'tag': None, 'volume_type': None})
        instance_bdms.append(bdm)
        # The non-volume image mapping will go at the front of the list
        # because the volume BDMs are processed separately.
        expect_meta['properties']['block_device_mapping'].insert(0,
            {'guest_format': 'swap', 'boot_index': -1, 'no_device': False,
             'image_id': None, 'volume_id': None, 'disk_bus': None,
             'volume_size': None, 'source_type': 'blank',
             'device_type': None, 'snapshot_id': None,
             'device_name': '/dev/vdh',
             'destination_type': 'local', 'delete_on_termination': True,
             'tag': None, 'volume_type': None})

        quiesced = [False, False]

        with test.nested(
                mock.patch.object(compute_api.API, '_record_action_start'),
                mock.patch.object(compute_utils, 'EventReporter')) as (
                mock_record, mock_event):
            # Check that the mappings from the image properties are not
            # included
            if snapshot_fails:
                self.assertRaises(exception.OverQuota,
                                  self.compute_api.snapshot_volume_backed,
                                  self.context, instance, "test-snapshot")
            else:
                self.compute_api.snapshot_volume_backed(
                    self.context, instance, 'test-snapshot')

        self.assertEqual(quiesce_expected, quiesced[0])
        self.assertEqual(quiesce_expected, quiesced[1])

        mock_record.assert_called_once_with(self.context,
                                            instance,
                                            instance_actions.CREATE_IMAGE)
        mock_event.assert_called_once_with(self.context,
                                           'api_snapshot_instance',
                                           CONF.host,
                                           instance.uuid,
                                           graceful_exit=False)

    def test_snapshot_volume_backed(self):
        self._test_snapshot_volume_backed(quiesce_required=False,
                                          quiesce_unsupported=False)

    def test_snapshot_volume_backed_with_quiesce_unsupported(self):
        self._test_snapshot_volume_backed(quiesce_required=True,
                                          quiesce_unsupported=False)

    def test_snaphost_volume_backed_with_quiesce_failure(self):
        self.assertRaises(oslo_exceptions.MessagingTimeout,
                          self._test_snapshot_volume_backed,
                          quiesce_required=True,
                          quiesce_fails=True)

    def test_snapshot_volume_backed_with_quiesce_create_snap_fails(self):
        self._test_snapshot_volume_backed(quiesce_required=True,
                                          snapshot_fails=True)

    def test_snapshot_volume_backed_unlimited_quota(self):
        """Tests that there is unlimited quota on volume snapshots so we
        don't perform a quota check.
        """
        limits = {'maxTotalSnapshots': -1, 'totalSnapshotsUsed': 0}
        self._test_snapshot_volume_backed(limits=limits)

    def test_snapshot_volume_backed_over_quota_before_snapshot(self):
        """Tests that the up-front check on quota fails before actually
        attempting to snapshot any volumes.
        """
        limits = {'maxTotalSnapshots': 1, 'totalSnapshotsUsed': 1}
        self.assertRaises(exception.OverQuota,
                          self._test_snapshot_volume_backed,
                          limits=limits)

    def test_snapshot_volume_backed_with_quiesce_skipped(self):
        self._test_snapshot_volume_backed(quiesce_required=False,
                                          quiesce_unsupported=True)

    def test_snapshot_volume_backed_with_quiesce_exception(self):
        self.assertRaises(exception.NovaException,
                          self._test_snapshot_volume_backed,
                          quiesce_required=True,
                          quiesce_unsupported=True)

    def test_snapshot_volume_backed_with_suspended(self):
        self._test_snapshot_volume_backed(quiesce_required=False,
                                          quiesce_unsupported=True,
                                          vm_state=vm_states.SUSPENDED)

    def test_snapshot_volume_backed_with_pause(self):
        self._test_snapshot_volume_backed(quiesce_required=False,
                                          quiesce_unsupported=True,
                                          vm_state=vm_states.PAUSED)

    @mock.patch.object(context, 'set_target_cell')
    @mock.patch.object(objects.BlockDeviceMapping, 'get_by_volume')
    def test_get_bdm_by_volume_id(self, mock_get_by_volume,
                                  mock_target_cell):
        fake_cells = [mock.sentinel.cell0, mock.sentinel.cell1]

        mock_get_by_volume.side_effect = [
            exception.VolumeBDMNotFound(volume_id=mock.sentinel.volume_id),
            mock.sentinel.bdm]

        with mock.patch.object(compute_api, 'CELLS', fake_cells):
            bdm = self.compute_api._get_bdm_by_volume_id(
                self.context, mock.sentinel.volume_id,
                mock.sentinel.expected_attrs)

        self.assertEqual(mock.sentinel.bdm, bdm)

        mock_target_cell.assert_has_calls([
            mock.call(self.context, cell) for cell in fake_cells])
        mock_get_by_volume.assert_has_calls(
            [mock.call(self.context,
                       mock.sentinel.volume_id,
                       expected_attrs=mock.sentinel.expected_attrs)] * 2)

    @mock.patch.object(context, 'set_target_cell')
    @mock.patch.object(objects.BlockDeviceMapping, 'get_by_volume')
    def test_get_missing_bdm_by_volume_id(self, mock_get_by_volume,
                                          mock_target_cell):
        fake_cells = [mock.sentinel.cell0, mock.sentinel.cell1]

        mock_get_by_volume.side_effect = exception.VolumeBDMNotFound(
            volume_id=mock.sentinel.volume_id)

        with mock.patch.object(compute_api, 'CELLS', fake_cells):
            self.assertRaises(
                exception.VolumeBDMNotFound,
                self.compute_api._get_bdm_by_volume_id,
                self.context, mock.sentinel.volume_id,
                mock.sentinel.expected_attrs)

    @mock.patch.object(compute_api.API, '_get_bdm_by_volume_id')
    def test_volume_snapshot_create(self, mock_get_bdm):
        volume_id = '1'
        create_info = {'id': 'eyedee'}
        fake_bdm = fake_block_device.FakeDbBlockDeviceDict({
                    'id': 123,
                    'device_name': '/dev/sda2',
                    'source_type': 'volume',
                    'destination_type': 'volume',
                    'connection_info': "{'fake': 'connection_info'}",
                    'volume_id': 1,
                    'boot_index': -1})
        fake_bdm['instance'] = fake_instance.fake_db_instance(
            launched_at=timeutils.utcnow(),
            vm_state=vm_states.ACTIVE)
        fake_bdm['instance_uuid'] = fake_bdm['instance']['uuid']
        fake_bdm = objects.BlockDeviceMapping._from_db_object(
                self.context, objects.BlockDeviceMapping(),
                fake_bdm, expected_attrs=['instance'])

        mock_get_bdm.return_value = fake_bdm

        with mock.patch.object(self.compute_api.compute_rpcapi,
                               'volume_snapshot_create') as mock_snapshot:
            snapshot = self.compute_api.volume_snapshot_create(self.context,
                volume_id, create_info)

        expected_snapshot = {
            'snapshot': {
                'id': create_info['id'],
                'volumeId': volume_id,
            },
        }
        self.assertEqual(snapshot, expected_snapshot)
        mock_get_bdm.assert_called_once_with(
            self.context, volume_id, expected_attrs=['instance'])
        mock_snapshot.assert_called_once_with(
            self.context, fake_bdm['instance'], volume_id, create_info)

    @mock.patch.object(
        objects.BlockDeviceMapping, 'get_by_volume',
        return_value=objects.BlockDeviceMapping(
            instance=objects.Instance(
                launched_at=timeutils.utcnow(), uuid=uuids.instance_uuid,
                vm_state=vm_states.ACTIVE, task_state=task_states.SHELVING,
                host='fake_host')))
    def test_volume_snapshot_create_shelving(self, bdm_get_by_volume):
        """Tests a negative scenario where the instance task_state is not
        accepted for creating a guest-assisted volume snapshot.
        """
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.volume_snapshot_create,
                          self.context, mock.sentinel.volume_id,
                          mock.sentinel.create_info)

    @mock.patch.object(
        objects.BlockDeviceMapping, 'get_by_volume',
        return_value=objects.BlockDeviceMapping(
            instance=objects.Instance(
                launched_at=timeutils.utcnow(), uuid=uuids.instance_uuid,
                vm_state=vm_states.SHELVED_OFFLOADED, task_state=None,
                host=None)))
    def test_volume_snapshot_create_shelved_offloaded(self, bdm_get_by_volume):
        """Tests a negative scenario where the instance is shelved offloaded
        so we don't have a host to cast to for the guest-assisted snapshot.
        """
        self.assertRaises(exception.InstanceNotReady,
                          self.compute_api.volume_snapshot_create,
                          self.context, mock.sentinel.volume_id,
                          mock.sentinel.create_info)

    @mock.patch.object(compute_api.API, '_get_bdm_by_volume_id')
    def test_volume_snapshot_delete(self, mock_get_bdm):
        volume_id = '1'
        snapshot_id = '2'
        fake_bdm = fake_block_device.FakeDbBlockDeviceDict({
                    'id': 123,
                    'device_name': '/dev/sda2',
                    'source_type': 'volume',
                    'destination_type': 'volume',
                    'connection_info': "{'fake': 'connection_info'}",
                    'volume_id': 1,
                    'boot_index': -1})
        fake_bdm['instance'] = fake_instance.fake_db_instance(
            launched_at=timeutils.utcnow(),
            vm_state=vm_states.ACTIVE)
        fake_bdm['instance_uuid'] = fake_bdm['instance']['uuid']
        fake_bdm = objects.BlockDeviceMapping._from_db_object(
                self.context, objects.BlockDeviceMapping(),
                fake_bdm, expected_attrs=['instance'])

        mock_get_bdm.return_value = fake_bdm
        delete_info = {
            'merge_target_file': 'foo.qcow2',
        }

        with mock.patch.object(
            self.compute_api.compute_rpcapi, 'volume_snapshot_delete'
        ) as mock_snapshot:
            self.compute_api.volume_snapshot_delete(
                self.context, volume_id, snapshot_id, delete_info
            )
        mock_get_bdm.assert_called_once_with(self.context, volume_id,
                                             expected_attrs=['instance'])
        mock_snapshot.assert_called_once_with(
            self.context, fake_bdm['instance'], volume_id, snapshot_id,
            delete_info
        )

    @mock.patch.object(
        objects.BlockDeviceMapping, 'get_by_volume',
        return_value=objects.BlockDeviceMapping(
            instance=objects.Instance(
                launched_at=timeutils.utcnow(), uuid=uuids.instance_uuid,
                vm_state=vm_states.ACTIVE, task_state=task_states.SHELVING,
                host='fake_host')))
    def test_volume_snapshot_delete_shelving(self, bdm_get_by_volume):
        """Tests a negative scenario where the instance is shelving and the
        task_state is set so we can't perform the guest-assisted snapshot.
        """
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.volume_snapshot_delete,
                          self.context, mock.sentinel.volume_id,
                          mock.sentinel.snapshot_id, mock.sentinel.delete_info)

    @mock.patch.object(
        objects.BlockDeviceMapping, 'get_by_volume',
        return_value=objects.BlockDeviceMapping(
            instance=objects.Instance(
                launched_at=timeutils.utcnow(), uuid=uuids.instance_uuid,
                vm_state=vm_states.SHELVED_OFFLOADED, task_state=None,
                host=None)))
    def test_volume_snapshot_delete_shelved_offloaded(self, bdm_get_by_volume):
        """Tests a negative scenario where the instance is shelved offloaded
        so there is no host to cast to for the guest-assisted snapshot delete.
        """
        self.assertRaises(exception.InstanceNotReady,
                          self.compute_api.volume_snapshot_delete,
                          self.context, mock.sentinel.volume_id,
                          mock.sentinel.snapshot_id, mock.sentinel.delete_info)

    @mock.patch.object(compute_api.API, '_get_bdm_by_volume_id')
    def test_volume_snapshot_delete_intermediary_commit(self, mock_get_bdm):
        fake_bdm = fake_block_device.FakeDbBlockDeviceDict({
            'id': 123,
            'device_name': '/dev/sda2',
            'source_type': 'volume',
            'destination_type': 'volume',
            'connection_info': "{'fake': 'connection_info'}",
            'volume_id': uuids.volume_id,
            'boot_index': -1
        })
        fake_bdm['instance'] = fake_instance.fake_db_instance(
            launched_at=timeutils.utcnow(),
            vm_state=vm_states.STOPPED)
        fake_bdm['instance_uuid'] = fake_bdm['instance']['uuid']
        fake_bdm = objects.BlockDeviceMapping._from_db_object(
                self.context, objects.BlockDeviceMapping(),
                fake_bdm, expected_attrs=['instance'])
        mock_get_bdm.return_value = fake_bdm

        # c-vol can provide delete_info with merge_target_file pointing to
        # an intermediary snapshot to commit into it's base. This is only
        # supported while the instance is running at present.
        delete_info = {
            'merge_target_file': 'snap.img'
        }

        # Assert that the request is rejected as offline commit isn't supported
        self.assertRaises(
            exception.InstanceInvalidState,
            self.compute_api.volume_snapshot_delete,
            self.context,
            uuids.volume_id,
            uuids.snapshot_id,
            delete_info
        )

    def _create_instance_with_disabled_disk_config(self, object=False):
        sys_meta = {"image_auto_disk_config": "Disabled"}
        params = {"system_metadata": sys_meta}
        instance = self._create_instance_obj(params=params)
        if object:
            return instance
        return obj_base.obj_to_primitive(instance)

    def _setup_fake_image_with_disabled_disk_config(self):
        self.fake_image = {
            'id': 1,
            'name': 'fake_name',
            'status': 'active',
            'properties': {"auto_disk_config": "Disabled"},
        }

        self.useFixture(nova_fixtures.GlanceFixture(self))
        self.stub_out('nova.tests.fixtures.GlanceFixture.show',
                      lambda obj, context, image_id, **kwargs: self.fake_image)
        return self.fake_image['id']

    def _setup_fake_image_with_invalid_arch(self):
        self.fake_image = {
            'id': 2,
            'name': 'fake_name',
            'status': 'active',
            'properties': {"hw_architecture": "arm64"},
        }

        self.useFixture(nova_fixtures.GlanceFixture(self))
        self.stub_out('nova.tests.fixtures.GlanceFixture.show',
                      lambda obj, context, image_id, **kwargs: self.fake_image)
        return self.fake_image['id']

    @mock.patch('nova.compute.api.API.get_instance_host_status',
                new=mock.Mock(return_value=fields_obj.HostStatus.UP))
    def test_resize_with_disabled_auto_disk_config_fails(self):
        fake_inst = self._create_instance_with_disabled_disk_config(
            object=True)

        self.assertRaises(exception.AutoDiskConfigDisabledByImage,
                          self.compute_api.resize,
                          self.context, fake_inst,
                          auto_disk_config=True)

    def test_create_with_disabled_auto_disk_config_fails(self):
        image_id = self._setup_fake_image_with_disabled_disk_config()

        self.assertRaises(exception.AutoDiskConfigDisabledByImage,
            self.compute_api.create, self.context,
            "fake_flavor", image_id, auto_disk_config=True)

    def test_rebuild_with_disabled_auto_disk_config_fails(self):
        fake_inst = self._create_instance_with_disabled_disk_config(
            object=True)
        image_id = self._setup_fake_image_with_disabled_disk_config()
        self.assertRaises(exception.AutoDiskConfigDisabledByImage,
                          self.compute_api.rebuild,
                          self.context,
                          fake_inst,
                          image_id,
                          "new password",
                          auto_disk_config=True)

    def test_rebuild_with_invalid_image_arch(self):
        instance = fake_instance.fake_instance_obj(
            self.context, vm_state=vm_states.ACTIVE, cell_name='fake-cell',
            launched_at=timeutils.utcnow(),
            system_metadata={}, image_ref='foo',
            expected_attrs=['system_metadata'])
        image_id = self._setup_fake_image_with_invalid_arch()
        self.assertRaises(exception.InvalidArchitectureName,
                          self.compute_api.rebuild,
                          self.context,
                          instance,
                          image_id,
                          "new password")
        self.assertIsNone(instance.task_state)

    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(objects.Instance, 'get_flavor')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch.object(compute_api.API, '_get_image')
    @mock.patch.object(compute_api.API, '_check_image_arch')
    @mock.patch.object(compute_api.API, '_check_auto_disk_config')
    @mock.patch.object(compute_api.API, '_checks_for_create_and_rebuild')
    @mock.patch.object(compute_api.API, '_record_action_start')
    def test_rebuild_with_invalid_volume(self, _record_action_start,
            _checks_for_create_and_rebuild, _check_auto_disk_config,
            _check_image_arch, mock_get_image,
            mock_get_bdms, get_flavor,
            instance_save, req_spec_get_by_inst_uuid):
        """Test a negative scenario where the instance has an
        invalid volume.
        """
        instance = fake_instance.fake_instance_obj(
            self.context, vm_state=vm_states.ACTIVE, cell_name='fake-cell',
            launched_at=timeutils.utcnow(),
            system_metadata={}, image_ref='foo',
            expected_attrs=['system_metadata'])

        bdms = objects.BlockDeviceMappingList(objects=[
                objects.BlockDeviceMapping(
                    boot_index=None, image_id=None,
                    source_type='volume', destination_type='volume',
                    volume_type=None, snapshot_id=None,
                    volume_id=uuids.volume_id, volume_size=None)])
        mock_get_bdms.return_value = bdms

        get_flavor.return_value = test_flavor.fake_flavor
        flavor = instance.get_flavor()

        image_href = 'foo'
        image = {
            "min_ram": 10, "min_disk": 1,
            "properties": {
                'architecture': fields_obj.Architecture.X86_64}}
        mock_get_image.return_value = (None, image)

        fake_spec = objects.RequestSpec()
        req_spec_get_by_inst_uuid.return_value = fake_spec

        fake_volume = {'id': uuids.volume_id, 'status': 'retyping'}
        with mock.patch.object(self.compute_api.volume_api, 'get',
                               return_value=fake_volume) as mock_get_volume:
            self.assertRaises(exception.InvalidVolume,
                              self.compute_api.rebuild,
                              self.context,
                              instance,
                              image_href,
                              "new password")
            self.assertIsNone(instance.task_state)
            mock_get_bdms.assert_called_once_with(self.context,
                                                  instance.uuid)
            mock_get_volume.assert_called_once_with(self.context,
                                                    uuids.volume_id)
            _check_auto_disk_config.assert_called_once_with(
                image=image, auto_disk_config=None)
            _check_image_arch.assert_called_once_with(image=image)
            _checks_for_create_and_rebuild.assert_called_once_with(
                self.context, None, image, flavor, {}, [], None)

    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(objects.Instance, 'get_flavor')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch.object(compute_api.API, '_get_image')
    @mock.patch.object(compute_api.API, '_check_auto_disk_config')
    @mock.patch.object(compute_api.API, '_checks_for_create_and_rebuild')
    @mock.patch.object(compute_api.API, '_record_action_start')
    def test_rebuild(self, _record_action_start,
            _checks_for_create_and_rebuild, _check_auto_disk_config,
            _get_image, bdm_get_by_instance_uuid, get_flavor, instance_save,
            req_spec_get_by_inst_uuid):
        orig_system_metadata = {}
        instance = fake_instance.fake_instance_obj(self.context,
                vm_state=vm_states.ACTIVE, cell_name='fake-cell',
                launched_at=timeutils.utcnow(),
                system_metadata=orig_system_metadata,
                image_ref='foo',
                expected_attrs=['system_metadata'])
        get_flavor.return_value = test_flavor.fake_flavor
        flavor = instance.get_flavor()
        image_href = 'foo'
        image = {
            "min_ram": 10, "min_disk": 1,
            "properties": {
                'architecture': fields_obj.Architecture.X86_64}}
        admin_pass = ''
        files_to_inject = []
        bdms = objects.BlockDeviceMappingList()

        _get_image.return_value = (None, image)
        bdm_get_by_instance_uuid.return_value = bdms

        fake_spec = objects.RequestSpec()
        req_spec_get_by_inst_uuid.return_value = fake_spec

        with mock.patch.object(self.compute_api.compute_task_api,
                'rebuild_instance') as rebuild_instance:
            self.compute_api.rebuild(self.context, instance, image_href,
                    admin_pass, files_to_inject)

            rebuild_instance.assert_called_once_with(self.context,
                    instance=instance, new_pass=admin_pass,
                    injected_files=files_to_inject, image_ref=image_href,
                    orig_image_ref=image_href,
                    orig_sys_metadata=orig_system_metadata, bdms=bdms,
                    preserve_ephemeral=False, host=instance.host,
                    request_spec=fake_spec)

        _check_auto_disk_config.assert_called_once_with(
            image=image, auto_disk_config=None)
        _checks_for_create_and_rebuild.assert_called_once_with(self.context,
                None, image, flavor, {}, [], None)
        self.assertNotEqual(orig_system_metadata, instance.system_metadata)
        bdm_get_by_instance_uuid.assert_called_once_with(
            self.context, instance.uuid)

    @mock.patch.object(objects.RequestSpec, 'save')
    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(objects.Instance, 'get_flavor')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch.object(compute_api.API, '_get_image')
    @mock.patch.object(compute_api.API, '_check_auto_disk_config')
    @mock.patch.object(compute_api.API, '_checks_for_create_and_rebuild')
    @mock.patch.object(compute_api.API, '_record_action_start')
    def test_rebuild_change_image(self, _record_action_start,
            _checks_for_create_and_rebuild, _check_auto_disk_config,
            _get_image, bdm_get_by_instance_uuid, get_flavor, instance_save,
            req_spec_get_by_inst_uuid, req_spec_save):
        orig_system_metadata = {}
        get_flavor.return_value = test_flavor.fake_flavor
        orig_image_href = 'orig_image'
        orig_image = {
            "min_ram": 10, "min_disk": 1,
            "properties": {'architecture': fields_obj.Architecture.X86_64,
                           'vm_mode': 'hvm'}}
        new_image_href = 'new_image'
        new_image = {
            "min_ram": 10, "min_disk": 1,
             "properties": {'architecture': fields_obj.Architecture.X86_64,
                           'vm_mode': 'xen'}}
        admin_pass = ''
        files_to_inject = []
        bdms = objects.BlockDeviceMappingList()

        instance = fake_instance.fake_instance_obj(self.context,
                vm_state=vm_states.ACTIVE, cell_name='fake-cell',
                launched_at=timeutils.utcnow(),
                system_metadata=orig_system_metadata,
                expected_attrs=['system_metadata'],
                image_ref=orig_image_href,
                node='node',
                vm_mode=fields_obj.VMMode.HVM)
        flavor = instance.get_flavor()

        def get_image(context, image_href):
            if image_href == new_image_href:
                return (None, new_image)
            if image_href == orig_image_href:
                return (None, orig_image)
        _get_image.side_effect = get_image
        bdm_get_by_instance_uuid.return_value = bdms

        fake_spec = objects.RequestSpec(id=1)
        req_spec_get_by_inst_uuid.return_value = fake_spec

        with mock.patch.object(self.compute_api.compute_task_api,
                'rebuild_instance') as rebuild_instance:
            self.compute_api.rebuild(self.context, instance, new_image_href,
                    admin_pass, files_to_inject)

            rebuild_instance.assert_called_once_with(self.context,
                    instance=instance, new_pass=admin_pass,
                    injected_files=files_to_inject, image_ref=new_image_href,
                    orig_image_ref=orig_image_href,
                    orig_sys_metadata=orig_system_metadata, bdms=bdms,
                    preserve_ephemeral=False, host=None,
                    request_spec=fake_spec)
            # assert the request spec was modified so the scheduler picks
            # the existing instance host/node
            req_spec_save.assert_called_once_with()
            self.assertIn('_nova_check_type', fake_spec.scheduler_hints)
            self.assertEqual('rebuild',
                             fake_spec.scheduler_hints['_nova_check_type'][0])

        _check_auto_disk_config.assert_called_once_with(
            image=new_image, auto_disk_config=None)
        _checks_for_create_and_rebuild.assert_called_once_with(self.context,
                None, new_image, flavor, {}, [], None)
        self.assertEqual(fields_obj.VMMode.XEN, instance.vm_mode)

    @mock.patch.object(objects.KeyPair, 'get_by_name')
    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(objects.Instance, 'get_flavor')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch.object(compute_api.API, '_get_image')
    @mock.patch.object(compute_api.API, '_check_auto_disk_config')
    @mock.patch.object(compute_api.API, '_checks_for_create_and_rebuild')
    @mock.patch.object(compute_api.API, '_record_action_start')
    def test_rebuild_change_keypair(self, _record_action_start,
            _checks_for_create_and_rebuild, _check_auto_disk_config,
            _get_image, bdm_get_by_instance_uuid, get_flavor, instance_save,
            req_spec_get_by_inst_uuid, mock_get_keypair):
        orig_system_metadata = {}
        orig_key_name = 'orig_key_name'
        orig_key_data = 'orig_key_data_XXX'
        instance = fake_instance.fake_instance_obj(self.context,
                vm_state=vm_states.ACTIVE, cell_name='fake-cell',
                launched_at=timeutils.utcnow(),
                system_metadata=orig_system_metadata,
                image_ref='foo',
                expected_attrs=['system_metadata'],
                key_name=orig_key_name,
                key_data=orig_key_data)
        get_flavor.return_value = test_flavor.fake_flavor
        flavor = instance.get_flavor()
        image_href = 'foo'
        image = {
            "min_ram": 10, "min_disk": 1,
            "properties": {'architecture': fields_obj.Architecture.X86_64,
                           'vm_mode': 'hvm'}}
        admin_pass = ''
        files_to_inject = []
        bdms = objects.BlockDeviceMappingList()

        _get_image.return_value = (None, image)
        bdm_get_by_instance_uuid.return_value = bdms

        fake_spec = objects.RequestSpec()
        req_spec_get_by_inst_uuid.return_value = fake_spec

        keypair = self._create_keypair_obj(instance)
        mock_get_keypair.return_value = keypair
        with mock.patch.object(self.compute_api.compute_task_api,
                'rebuild_instance') as rebuild_instance:
            self.compute_api.rebuild(self.context, instance, image_href,
                    admin_pass, files_to_inject, key_name=keypair.name)

            rebuild_instance.assert_called_once_with(self.context,
                    instance=instance, new_pass=admin_pass,
                    injected_files=files_to_inject, image_ref=image_href,
                    orig_image_ref=image_href,
                    orig_sys_metadata=orig_system_metadata, bdms=bdms,
                    preserve_ephemeral=False, host=instance.host,
                    request_spec=fake_spec)

        _check_auto_disk_config.assert_called_once_with(
            image=image, auto_disk_config=None)
        _checks_for_create_and_rebuild.assert_called_once_with(self.context,
                None, image, flavor, {}, [], None)
        self.assertNotEqual(orig_key_name, instance.key_name)
        self.assertNotEqual(orig_key_data, instance.key_data)

    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(objects.Instance, 'get_flavor')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch.object(compute_api.API, '_get_image')
    @mock.patch.object(compute_api.API, '_check_auto_disk_config')
    @mock.patch.object(compute_api.API, '_checks_for_create_and_rebuild')
    @mock.patch.object(compute_api.API, '_record_action_start')
    def test_rebuild_change_trusted_certs(self, _record_action_start,
            _checks_for_create_and_rebuild, _check_auto_disk_config,
            _get_image, bdm_get_by_instance_uuid, get_flavor, instance_save,
            req_spec_get_by_inst_uuid):
        orig_system_metadata = {}
        orig_trusted_certs = ['orig-trusted-cert-1', 'orig-trusted-cert-2']
        new_trusted_certs = ['new-trusted-cert-1', 'new-trusted-cert-2']
        instance = fake_instance.fake_instance_obj(
            self.context, vm_state=vm_states.ACTIVE, cell_name='fake-cell',
            launched_at=timeutils.utcnow(),
            system_metadata=orig_system_metadata, image_ref='foo',
            expected_attrs=['system_metadata'],
            trusted_certs=orig_trusted_certs)
        get_flavor.return_value = test_flavor.fake_flavor
        flavor = instance.get_flavor()
        image_href = 'foo'
        image = {
            "min_ram": 10, "min_disk": 1,
            "properties": {'architecture': fields_obj.Architecture.X86_64,
                           'vm_mode': 'hvm'}}
        admin_pass = ''
        files_to_inject = []
        bdms = objects.BlockDeviceMappingList()

        _get_image.return_value = (None, image)
        bdm_get_by_instance_uuid.return_value = bdms

        fake_spec = objects.RequestSpec()
        req_spec_get_by_inst_uuid.return_value = fake_spec

        with mock.patch.object(self.compute_api.compute_task_api,
                'rebuild_instance') as rebuild_instance:
            self.compute_api.rebuild(self.context, instance, image_href,
                                     admin_pass, files_to_inject,
                                     trusted_certs=new_trusted_certs)

            rebuild_instance.assert_called_once_with(
                self.context, instance=instance, new_pass=admin_pass,
                injected_files=files_to_inject, image_ref=image_href,
                orig_image_ref=image_href,
                orig_sys_metadata=orig_system_metadata, bdms=bdms,
                preserve_ephemeral=False, host=instance.host,
                request_spec=fake_spec)

        _check_auto_disk_config.assert_called_once_with(
            image=image, auto_disk_config=None)
        _checks_for_create_and_rebuild.assert_called_once_with(
            self.context, None, image, flavor, {}, [], None)
        self.assertEqual(new_trusted_certs, instance.trusted_certs.ids)

    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(objects.Instance, 'get_flavor')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch.object(compute_api.API, '_get_image')
    @mock.patch.object(compute_api.API, '_check_auto_disk_config')
    @mock.patch.object(compute_api.API, '_checks_for_create_and_rebuild')
    @mock.patch.object(compute_api.API, '_record_action_start')
    def test_rebuild_unset_trusted_certs(self, _record_action_start,
                                          _checks_for_create_and_rebuild,
                                          _check_auto_disk_config,
                                          _get_image, bdm_get_by_instance_uuid,
                                          get_flavor, instance_save,
                                          req_spec_get_by_inst_uuid):
        """Tests the scenario that the server was created with some trusted
        certs and then rebuilt without trusted_image_certificates=None
        explicitly to unset the trusted certs on the server.
        """
        orig_system_metadata = {}
        orig_trusted_certs = ['orig-trusted-cert-1', 'orig-trusted-cert-2']
        new_trusted_certs = None
        instance = fake_instance.fake_instance_obj(
            self.context, vm_state=vm_states.ACTIVE, cell_name='fake-cell',
            launched_at=timeutils.utcnow(),
            system_metadata=orig_system_metadata, image_ref='foo',
            expected_attrs=['system_metadata'],
            trusted_certs=orig_trusted_certs)
        get_flavor.return_value = test_flavor.fake_flavor
        flavor = instance.get_flavor()
        image_href = 'foo'
        image = {
            "min_ram": 10, "min_disk": 1,
            "properties": {'architecture': fields_obj.Architecture.X86_64,
                           'vm_mode': 'hvm'}}
        admin_pass = ''
        files_to_inject = []
        bdms = objects.BlockDeviceMappingList()

        _get_image.return_value = (None, image)
        bdm_get_by_instance_uuid.return_value = bdms

        fake_spec = objects.RequestSpec()
        req_spec_get_by_inst_uuid.return_value = fake_spec

        with mock.patch.object(self.compute_api.compute_task_api,
                               'rebuild_instance') as rebuild_instance:
            self.compute_api.rebuild(self.context, instance, image_href,
                                     admin_pass, files_to_inject,
                                     trusted_certs=new_trusted_certs)

            rebuild_instance.assert_called_once_with(
                self.context, instance=instance, new_pass=admin_pass,
                injected_files=files_to_inject, image_ref=image_href,
                orig_image_ref=image_href,
                orig_sys_metadata=orig_system_metadata, bdms=bdms,
                preserve_ephemeral=False, host=instance.host,
                request_spec=fake_spec)

        _check_auto_disk_config.assert_called_once_with(
            image=image, auto_disk_config=None)
        _checks_for_create_and_rebuild.assert_called_once_with(
            self.context, None, image, flavor, {}, [], None)
        self.assertIsNone(instance.trusted_certs)

    @mock.patch.object(compute_utils, 'is_volume_backed_instance',
                       return_value=True)
    @mock.patch.object(objects.Instance, 'get_flavor')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch.object(compute_api.API, '_get_image')
    @mock.patch.object(compute_api.API, '_check_auto_disk_config')
    @mock.patch.object(compute_api.API, '_record_action_start')
    def test_rebuild_volume_backed_instance_with_trusted_certs(
            self, _record_action_start, _check_auto_disk_config, _get_image,
            bdm_get_by_instance_uuid, get_flavor, instance_is_volume_backed):
        orig_system_metadata = {}
        new_trusted_certs = ['new-trusted-cert-1', 'new-trusted-cert-2']
        instance = fake_instance.fake_instance_obj(
            self.context, vm_state=vm_states.ACTIVE, cell_name='fake-cell',
            launched_at=timeutils.utcnow(),
            system_metadata=orig_system_metadata, image_ref=None,
            expected_attrs=['system_metadata'], trusted_certs=None)
        get_flavor.return_value = test_flavor.fake_flavor
        image_href = 'foo'
        image = {
            "min_ram": 10, "min_disk": 1,
            "properties": {'architecture': fields_obj.Architecture.X86_64,
                           'vm_mode': 'hvm'}}
        admin_pass = ''
        files_to_inject = []
        bdms = objects.BlockDeviceMappingList()

        _get_image.return_value = (None, image)
        bdm_get_by_instance_uuid.return_value = bdms

        self.assertRaises(exception.CertificateValidationFailed,
                          self.compute_api.rebuild, self.context, instance,
                          image_href, admin_pass, files_to_inject,
                          trusted_certs=new_trusted_certs)

        _check_auto_disk_config.assert_called_once_with(
            image=image, auto_disk_config=None)

    @mock.patch('nova.objects.Quotas.limit_check')
    def test_check_metadata_properties_quota_with_empty_dict(self,
                                                             limit_check):
        metadata = {}
        self.compute_api._check_metadata_properties_quota(self.context,
                                                          metadata)
        self.assertEqual(0, limit_check.call_count)

    @mock.patch('nova.objects.Quotas.limit_check')
    def test_check_injected_file_quota_with_empty_list(self,
                                                       limit_check):
        injected_files = []
        self.compute_api._check_injected_file_quota(self.context,
                                                    injected_files)
        self.assertEqual(0, limit_check.call_count)

    def _test_check_injected_file_quota_onset_file_limit_exceeded(self,
                                                                  side_effect):
        injected_files = [
            {
                "path": "/etc/banner.txt",
                "contents": "foo"
            }
        ]
        with mock.patch('nova.objects.Quotas.limit_check',
                        side_effect=side_effect):
            self.compute_api._check_injected_file_quota(
                self.context, injected_files)

    def test_check_injected_file_quota_onset_file_limit_exceeded(self):
        # This is the first call to limit_check.
        side_effect = exception.OverQuota(overs='injected_files')
        self.assertRaises(exception.OnsetFileLimitExceeded,
            self._test_check_injected_file_quota_onset_file_limit_exceeded,
            side_effect)

    def test_check_injected_file_quota_onset_file_path_limit(self):
        # This is the second call to limit_check.
        side_effect = (mock.DEFAULT,
                       exception.OverQuota(overs='injected_file_path_bytes',
                                    quotas={'injected_file_path_bytes': 255}))
        self.assertRaises(exception.OnsetFilePathLimitExceeded,
            self._test_check_injected_file_quota_onset_file_limit_exceeded,
            side_effect)

    def test_check_injected_file_quota_onset_file_content_limit(self):
        # This is the second call to limit_check but with different overs.
        side_effect = (mock.DEFAULT,
            exception.OverQuota(overs='injected_file_content_bytes',
                                quotas={'injected_file_content_bytes': 10240}))
        self.assertRaises(exception.OnsetFileContentLimitExceeded,
            self._test_check_injected_file_quota_onset_file_limit_exceeded,
            side_effect)

    @mock.patch('nova.objects.Quotas.get_all_by_project_and_user',
                new=mock.MagicMock())
    @mock.patch('nova.objects.Quotas.count_as_dict')
    @mock.patch('nova.objects.Quotas.limit_check_project_and_user')
    @mock.patch('nova.objects.Instance.save')
    @mock.patch('nova.objects.InstanceAction.action_start')
    @mock.patch('nova.compute.api.API._update_queued_for_deletion')
    def test_restore_by_admin(self, update_qfd, action_start, instance_save,
                              quota_check, quota_count):
        admin_context = context.RequestContext('admin_user',
                                               'admin_project',
                                               True)
        proj_count = {'instances': 1, 'cores': 1, 'ram': 512}
        user_count = proj_count.copy()
        quota_count.return_value = {'project': proj_count, 'user': user_count}
        instance = self._create_instance_obj()
        instance.vm_state = vm_states.SOFT_DELETED
        instance.task_state = None
        instance.save()
        with mock.patch.object(self.compute_api, 'compute_rpcapi') as rpc:
            self.compute_api.restore(admin_context, instance)
            rpc.restore_instance.assert_called_once_with(admin_context,
                                                         instance)
        self.assertEqual(instance.task_state, task_states.RESTORING)
        # mock.ANY might be 'instances', 'cores', or 'ram' depending on how the
        # deltas dict is iterated in check_deltas
        # user_id is expected to be None because no per-user quotas have been
        # defined
        quota_count.assert_called_once_with(admin_context, mock.ANY,
                                            instance.project_id,
                                            user_id=None)
        quota_check.assert_called_once_with(
            admin_context,
            user_values={'instances': 2,
                         'cores': 1 + instance.flavor.vcpus,
                         'ram': 512 + instance.flavor.memory_mb},
            project_values={'instances': 2,
                            'cores': 1 + instance.flavor.vcpus,
                            'ram': 512 + instance.flavor.memory_mb},
            project_id=instance.project_id)
        update_qfd.assert_called_once_with(admin_context, instance.uuid, False)

    @mock.patch('nova.objects.Quotas.get_all_by_project_and_user',
                new=mock.MagicMock())
    @mock.patch('nova.objects.Quotas.count_as_dict')
    @mock.patch('nova.objects.Quotas.limit_check_project_and_user')
    @mock.patch('nova.objects.Instance.save')
    @mock.patch('nova.objects.InstanceAction.action_start')
    @mock.patch('nova.compute.api.API._update_queued_for_deletion')
    def test_restore_by_instance_owner(self, update_qfd, action_start,
                                       instance_save,
                                       quota_check, quota_count):
        proj_count = {'instances': 1, 'cores': 1, 'ram': 512}
        user_count = proj_count.copy()
        quota_count.return_value = {'project': proj_count, 'user': user_count}
        instance = self._create_instance_obj()
        instance.vm_state = vm_states.SOFT_DELETED
        instance.task_state = None
        instance.save()
        with mock.patch.object(self.compute_api, 'compute_rpcapi') as rpc:
            self.compute_api.restore(self.context, instance)
            rpc.restore_instance.assert_called_once_with(self.context,
                                                         instance)
        self.assertEqual(instance.project_id, self.context.project_id)
        self.assertEqual(instance.task_state, task_states.RESTORING)
        # mock.ANY might be 'instances', 'cores', or 'ram' depending on how the
        # deltas dict is iterated in check_deltas
        # user_id is expected to be None because no per-user quotas have been
        # defined
        quota_count.assert_called_once_with(self.context, mock.ANY,
                                            instance.project_id,
                                            user_id=None)
        quota_check.assert_called_once_with(
            self.context,
            user_values={'instances': 2,
                         'cores': 1 + instance.flavor.vcpus,
                         'ram': 512 + instance.flavor.memory_mb},
            project_values={'instances': 2,
                            'cores': 1 + instance.flavor.vcpus,
                            'ram': 512 + instance.flavor.memory_mb},
            project_id=instance.project_id)
        update_qfd.assert_called_once_with(self.context, instance.uuid, False)

    @mock.patch.object(objects.InstanceAction, 'action_start')
    def test_external_instance_event(self, mock_action_start):

        instances = [
            objects.Instance(uuid=uuids.instance_1, host='host1',
                             migration_context=None),
            objects.Instance(uuid=uuids.instance_2, host='host1',
                             migration_context=None),
            objects.Instance(uuid=uuids.instance_3, host='host2',
                             migration_context=None),
            objects.Instance(uuid=uuids.instance_4, host='host2',
                             migration_context=None),
            objects.Instance(uuid=uuids.instance_5, host='host2',
                             migration_context=None, task_state=None,
                             vm_state=vm_states.STOPPED,
                             power_state=power_state.SHUTDOWN),
            objects.Instance(uuid=uuids.instance_6, host='host2',
                             migration_context=None, task_state=None,
                             vm_state=vm_states.ACTIVE,
                             power_state=power_state.RUNNING)
            ]
        # Create a single cell context and associate it with all instances
        mapping = objects.InstanceMapping.get_by_instance_uuid(
                self.context, instances[0].uuid)
        with context.target_cell(self.context, mapping.cell_mapping) as cc:
            cell_context = cc
        for instance in instances:
            instance._context = cell_context

        volume_id = uuidutils.generate_uuid()
        events = [
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_1,
                name='network-changed'),
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_2,
                name='network-changed'),
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_3,
                name='network-changed'),
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_4,
                name='volume-extended',
                tag=volume_id),
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_5,
                name='power-update',
                tag="POWER_ON"),
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_6,
                name='power-update',
                tag="POWER_OFF"),
            ]
        self.compute_api.compute_rpcapi = mock.MagicMock()
        self.compute_api.external_instance_event(self.context,
                                                 instances, events)
        method = self.compute_api.compute_rpcapi.external_instance_event
        method.assert_any_call(cell_context, instances[0:2], events[0:2],
                               host='host1')
        method.assert_any_call(cell_context, instances[2:], events[2:],
                               host='host2')
        calls = [mock.call(self.context, uuids.instance_4,
                           instance_actions.EXTEND_VOLUME, want_result=False),
                 mock.call(self.context, uuids.instance_5,
                           instance_actions.START, want_result=False),
                 mock.call(self.context, uuids.instance_6,
                           instance_actions.STOP, want_result=False)]
        mock_action_start.assert_has_calls(calls)
        self.assertEqual(2, method.call_count)

    def test_external_instance_event_power_update_invalid_tag(self):
        instance1 = objects.Instance(self.context)
        instance1.uuid = uuids.instance1
        instance1.id = 1
        instance1.vm_state = vm_states.ACTIVE
        instance1.task_state = None
        instance1.power_state = power_state.RUNNING
        instance1.host = 'host1'
        instance1.migration_context = None
        instance2 = objects.Instance(self.context)
        instance2.uuid = uuids.instance2
        instance2.id = 2
        instance2.vm_state = vm_states.STOPPED
        instance2.task_state = None
        instance2.power_state = power_state.SHUTDOWN
        instance2.host = 'host2'
        instance2.migration_context = None
        instances = [instance1, instance2]
        events = [
            objects.InstanceExternalEvent(
                instance_uuid=instance1.uuid,
                name='power-update',
                tag="VACATION"),
            objects.InstanceExternalEvent(
                instance_uuid=instance2.uuid,
                name='power-update',
                tag="POWER_ON")
            ]
        with test.nested(
            mock.patch.object(self.compute_api.compute_rpcapi,
                              'external_instance_event'),
            mock.patch.object(objects.InstanceAction, 'action_start'),
            mock.patch.object(compute_api, 'LOG')
        ) as (
            mock_ex, mock_action_start, mock_log
        ):
            self.compute_api.external_instance_event(self.context,
                instances, events)
            self.assertEqual(2, mock_ex.call_count)
            # event VACATION requested on instance1 is ignored because
            # its an invalid event tag.
            mock_ex.assert_has_calls(
                [mock.call(self.context, [instance2],
                           [events[1]], host=u'host2'),
                 mock.call(self.context, [instance1], [], host=u'host1')],
                any_order=True)
            mock_action_start.assert_called_once_with(
                self.context, instance2.uuid, instance_actions.START,
                want_result=False)
            self.assertEqual(1, mock_log.warning.call_count)
            self.assertIn(
                'Invalid power state', mock_log.warning.call_args[0][0])

    def test_external_instance_event_evacuating_instance(self):
        # Since we're patching the db's migration_get(), use a dict here so
        # that we can validate the id is making its way correctly to the db api
        migrations = {}
        migrations[42] = {'id': 42, 'source_compute': 'host1',
                          'dest_compute': 'host2', 'source_node': None,
                          'dest_node': None, 'dest_host': None,
                          'old_instance_type_id': None,
                          'new_instance_type_id': None,
                          'uuid': uuids.migration,
                          'instance_uuid': uuids.instance_2, 'status': None,
                          'migration_type': 'evacuation', 'memory_total': None,
                          'memory_processed': None, 'memory_remaining': None,
                          'disk_total': None, 'disk_processed': None,
                          'disk_remaining': None, 'deleted': False,
                          'hidden': False, 'created_at': None,
                          'updated_at': None, 'deleted_at': None,
                          'cross_cell_move': False, 'user_id': None,
                          'project_id': None}

        def migration_get(context, id):
            return migrations[id]

        instances = [
            objects.Instance(uuid=uuids.instance_1, host='host1',
                             migration_context=None),
            objects.Instance(uuid=uuids.instance_2, host='host1',
                             migration_context=objects.MigrationContext(
                                 migration_id=42)),
            objects.Instance(uuid=uuids.instance_3, host='host2',
                             migration_context=None)
            ]

        # Create a single cell context and associate it with all instances
        mapping = objects.InstanceMapping.get_by_instance_uuid(
                self.context, instances[0].uuid)
        with context.target_cell(self.context, mapping.cell_mapping) as cc:
            cell_context = cc
        for instance in instances:
            instance._context = cell_context

        events = [
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_1,
                name='network-changed'),
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_2,
                name='network-changed'),
            objects.InstanceExternalEvent(
                instance_uuid=uuids.instance_3,
                name='network-changed'),
            ]

        with mock.patch('nova.db.sqlalchemy.api.migration_get', migration_get):
            self.compute_api.compute_rpcapi = mock.MagicMock()
            self.compute_api.external_instance_event(self.context,
                                                     instances, events)
            method = self.compute_api.compute_rpcapi.external_instance_event
            method.assert_any_call(cell_context, instances[0:2], events[0:2],
                                   host='host1')
            method.assert_any_call(cell_context, instances[1:], events[1:],
                                   host='host2')
            self.assertEqual(2, method.call_count)

    @mock.patch('nova.objects.Migration.get_by_id')
    @mock.patch('nova.objects.HostMapping.get_by_host')
    @mock.patch('nova.context.set_target_cell')
    @mock.patch('nova.context.get_admin_context')
    def test_external_instance_event_cross_cell_move(
            self, get_admin_context, set_target_cell, get_hm_by_host,
            get_mig_by_id):
        """Tests a scenario where an external server event comes for an
        instance undergoing a cross-cell migration so the event is routed
        to both the source host in the source cell and dest host in dest cell
        using the properly targeted request contexts.
        """
        migration = objects.Migration(
            id=1, source_compute='host1', dest_compute='host2',
            cross_cell_move=True)
        migration_context = objects.MigrationContext(
            instance_uuid=uuids.instance, migration_id=migration.id,
            migration_type='resize', cross_cell_move=True)
        instance = objects.Instance(
            self.context, uuid=uuids.instance, host=migration.source_compute,
            migration_context=migration_context)
        get_mig_by_id.return_value = migration
        source_cell_mapping = objects.CellMapping(name='source-cell')
        dest_cell_mapping = objects.CellMapping(name='dest-cell')

        # Wrap _get_relevant_hosts and sort the result for predictable asserts.
        original_get_relevant_hosts = self.compute_api._get_relevant_hosts

        def wrap_get_relevant_hosts(_self, *a, **kw):
            hosts, cross_cell_move = original_get_relevant_hosts(*a, **kw)
            return sorted(hosts), cross_cell_move
        self.stub_out('nova.compute.api.API._get_relevant_hosts',
                      wrap_get_relevant_hosts)

        def fake_hm_get_by_host(ctxt, host):
            if host == migration.source_compute:
                return objects.HostMapping(
                    host=host, cell_mapping=source_cell_mapping)
            if host == migration.dest_compute:
                return objects.HostMapping(
                    host=host, cell_mapping=dest_cell_mapping)
            raise Exception('Unexpected host: %s' % host)

        get_hm_by_host.side_effect = fake_hm_get_by_host
        # get_admin_context should be called twice in order (source and dest)
        get_admin_context.side_effect = [
            mock.sentinel.source_context, mock.sentinel.dest_context]

        event = objects.InstanceExternalEvent(
            instance_uuid=instance.uuid, name='network-vif-plugged')
        events = [event]

        with mock.patch.object(self.compute_api.compute_rpcapi,
                               'external_instance_event') as rpc_mock:
            self.compute_api.external_instance_event(
                self.context, [instance], events)

        # We should have gotten the migration because of the migration_context.
        get_mig_by_id.assert_called_once_with(self.context, migration.id)
        # We should have gotten two host mappings (for source and dest).
        self.assertEqual(2, get_hm_by_host.call_count)
        get_hm_by_host.assert_has_calls([
            mock.call(self.context, migration.source_compute),
            mock.call(self.context, migration.dest_compute)])
        self.assertEqual(2, get_admin_context.call_count)
        # We should have targeted a context to both cells.
        self.assertEqual(2, set_target_cell.call_count)
        set_target_cell.assert_has_calls([
            mock.call(mock.sentinel.source_context, source_cell_mapping),
            mock.call(mock.sentinel.dest_context, dest_cell_mapping)])
        # We should have RPC cast to both hosts in different cells.
        self.assertEqual(2, rpc_mock.call_count)
        rpc_mock.assert_has_calls([
            mock.call(mock.sentinel.source_context, [instance], events,
                      host=migration.source_compute),
            mock.call(mock.sentinel.dest_context, [instance], events,
                      host=migration.dest_compute)],
            # The rpc calls are based on iterating over a dict which is not
            # ordered so we have to just assert the calls in any order.
            any_order=True)

    def test_volume_ops_invalid_task_state(self):
        instance = self._create_instance_obj()
        self.assertEqual(instance.vm_state, vm_states.ACTIVE)
        instance.task_state = 'Any'
        volume_id = uuidutils.generate_uuid()
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.attach_volume,
                          self.context, instance, volume_id)

        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.detach_volume,
                          self.context, instance, volume_id)

        new_volume_id = uuidutils.generate_uuid()
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.swap_volume,
                          self.context, instance,
                          volume_id, new_volume_id)

    def test_get_volumes_for_bdms_errors(self):
        """Simple test to make sure _get_volumes_for_bdms raises up errors."""
        # Use a mix of pre-existing and source_type=image volumes to test the
        # filtering logic in the method.
        bdms = objects.BlockDeviceMappingList(objects=[
            objects.BlockDeviceMapping(source_type='image', volume_id=None),
            objects.BlockDeviceMapping(source_type='volume',
                                       volume_id=uuids.volume_id)])
        for exc in (
            exception.VolumeNotFound(volume_id=uuids.volume_id),
            exception.CinderConnectionFailed(reason='gremlins'),
            exception.Forbidden()
        ):
            with mock.patch.object(self.compute_api.volume_api, 'get',
                                   side_effect=exc) as mock_vol_get:
                self.assertRaises(type(exc),
                                  self.compute_api._get_volumes_for_bdms,
                                  self.context, bdms)
            mock_vol_get.assert_called_once_with(self.context, uuids.volume_id)

    @ddt.data(True, False)
    def test_validate_vol_az_for_create_multiple_vols_diff_az(self, cross_az):
        """Tests cross_az_attach=True|False scenarios where the volumes are
        in different zones.
        """
        self.flags(cross_az_attach=cross_az, group='cinder')
        volumes = [{'availability_zone': str(x)} for x in range(2)]
        if cross_az:
            # Since cross_az_attach=True (the default) we do not care that the
            # volumes are in different zones.
            self.assertIsNone(self.compute_api._validate_vol_az_for_create(
                None, volumes))
        else:
            # In this case the volumes cannot be in different zones.
            ex = self.assertRaises(
                exception.MismatchVolumeAZException,
                self.compute_api._validate_vol_az_for_create, None, volumes)
            self.assertIn('Volumes are in different availability zones: 0,1',
                          str(ex))

    def test_validate_vol_az_for_create_vol_az_matches_default_cpu_az(self):
        """Tests the scenario that the instance is not being created in a
        specific zone and the volume's zone matches
        CONF.default_availabilty_zone so None is returned indicating the
        RequestSpec.availability_zone does not need to be updated.
        """
        self.flags(cross_az_attach=False, group='cinder')
        volumes = [{'availability_zone': CONF.default_availability_zone}]
        self.assertIsNone(self.compute_api._validate_vol_az_for_create(
            None, volumes))

    @mock.patch.object(cinder.API, 'get_snapshot',
             side_effect=exception.CinderConnectionFailed(reason='error'))
    def test_validate_bdm_with_cinder_down(self, mock_get_snapshot):
        instance = self._create_instance_obj()
        instance_type = self._create_flavor()
        bdms = [objects.BlockDeviceMapping(
                **fake_block_device.FakeDbBlockDeviceDict(
                {
                 'id': 1,
                 'snapshot_id': 1,
                 'source_type': 'volume',
                 'destination_type': 'volume',
                 'device_name': 'vda',
                 'boot_index': 0,
                 }))]
        image_cache = volumes = {}
        self.assertRaises(exception.CinderConnectionFailed,
                          self.compute_api._validate_bdm,
                          self.context,
                          instance, instance_type, bdms, image_cache, volumes)

    @mock.patch.object(cinder.API, 'attachment_create',
                       side_effect=exception.InvalidInput(reason='error'))
    def test_validate_bdm_with_error_volume_new_flow(self, mock_attach_create):
        # Tests that an InvalidInput exception raised from
        # volume_api.attachment_create due to the volume status not being
        # 'available' results in _validate_bdm re-raising InvalidVolume.
        instance = self._create_instance_obj()
        del instance.id
        instance_type = self._create_flavor()
        volume_id = 'e856840e-9f5b-4894-8bde-58c6e29ac1e8'
        volume_info = {'status': 'error',
                       'attach_status': 'detached',
                       'id': volume_id, 'multiattach': False}
        bdms = [objects.BlockDeviceMapping(
                **fake_block_device.FakeDbBlockDeviceDict(
                {
                 'boot_index': 0,
                 'volume_id': volume_id,
                 'source_type': 'volume',
                 'destination_type': 'volume',
                 'device_name': 'vda',
                }))]

        self.assertRaises(exception.InvalidVolume,
                          self.compute_api._validate_bdm,
                          self.context,
                          instance, instance_type, bdms, {},
                          {volume_id: volume_info})

        mock_attach_create.assert_called_once_with(
            self.context, volume_id, instance.uuid)

    def test_validate_bdm_missing_boot_index(self):
        """Tests that _validate_bdm will fail if there is no boot_index=0 entry
        """
        bdms = objects.BlockDeviceMappingList(objects=[
            objects.BlockDeviceMapping(
                boot_index=None, image_id=uuids.image_id,
                source_type='image', destination_type='volume')])
        image_cache = volumes = {}
        self.assertRaises(exception.InvalidBDMBootSequence,
                          self.compute_api._validate_bdm,
                          self.context, objects.Instance(), objects.Flavor(),
                          bdms, image_cache, volumes)

    def test_validate_bdm_with_volume_type_name_is_specified(self):
        """Test _check_requested_volume_type method is used.
        """
        instance = self._create_instance_obj()
        instance_type = self._create_flavor()

        volume_type = 'fake_lvm_1'
        volume_types = [{'id': 'fake_volume_type_id_1', 'name': 'fake_lvm_1'},
                        {'id': 'fake_volume_type_id_2', 'name': 'fake_lvm_2'}]

        bdm1 = objects.BlockDeviceMapping(
            **fake_block_device.AnonFakeDbBlockDeviceDict(
                {
                    'uuid': uuids.image_id,
                    'source_type': 'image',
                    'destination_type': 'volume',
                    'device_name': 'vda',
                    'boot_index': 0,
                    'volume_size': 3,
                    'volume_type': 'fake_lvm_1'
                }))
        bdm2 = objects.BlockDeviceMapping(
            **fake_block_device.AnonFakeDbBlockDeviceDict(
                {
                    'uuid': uuids.image_id,
                    'source_type': 'snapshot',
                    'destination_type': 'volume',
                    'device_name': 'vdb',
                    'boot_index': 1,
                    'volume_size': 3,
                    'volume_type': 'fake_lvm_1'
                }))
        bdms = [bdm1, bdm2]

        with test.nested(
                mock.patch.object(cinder.API, 'get_all_volume_types',
                                  return_value=volume_types),
                mock.patch.object(compute_api.API,
                                  '_check_requested_volume_type')) as (
                get_all_vol_types, vol_type_requested):

            image_cache = volumes = {}
            self.compute_api._validate_bdm(self.context, instance,
                                           instance_type, bdms, image_cache,
                                           volumes)

            get_all_vol_types.assert_called_once_with(self.context)

            vol_type_requested.assert_any_call(bdms[0], volume_type,
                                               volume_types)
            vol_type_requested.assert_any_call(bdms[1], volume_type,
                                               volume_types)

    @mock.patch('nova.compute.api.API._get_image')
    def test_validate_bdm_missing_volume_size(self, mock_get_image):
        """Tests that _validate_bdm fail if there volume_size not provided
        """
        instance = self._create_instance_obj()
        # first we test the case of instance.image_ref == bdm.image_id
        bdms = objects.BlockDeviceMappingList(objects=[
            objects.BlockDeviceMapping(
                boot_index=0, image_id=instance.image_ref,
                source_type='image', destination_type='volume',
                volume_type=None, snapshot_id=None, volume_id=None,
                volume_size=None)])
        image_cache = volumes = {}
        self.assertRaises(exception.InvalidBDM,
                          self.compute_api._validate_bdm,
                          self.context, instance, objects.Flavor(),
                          bdms, image_cache, volumes)
        self.assertEqual(0, mock_get_image.call_count)
        # then we test the case of instance.image_ref != bdm.image_id
        image_id = uuids.image_id
        bdms = objects.BlockDeviceMappingList(objects=[
            objects.BlockDeviceMapping(
                boot_index=0, image_id=image_id,
                source_type='image', destination_type='volume',
                volume_type=None, snapshot_id=None, volume_id=None,
                volume_size=None)])
        self.assertRaises(exception.InvalidBDM,
                          self.compute_api._validate_bdm,
                          self.context, instance, objects.Flavor(),
                          bdms, image_cache, volumes)
        mock_get_image.assert_called_once_with(self.context, image_id)

    @mock.patch('nova.compute.api.API._get_image')
    def test_validate_bdm_disk_bus(self, mock_get_image):
        """Tests that _validate_bdm fail if an invalid disk_bus is provided
        """
        instance = self._create_instance_obj()
        bdms = objects.BlockDeviceMappingList(objects=[
            objects.BlockDeviceMapping(
                boot_index=0, image_id=instance.image_ref,
                source_type='image', destination_type='volume',
                volume_type=None, snapshot_id=None, volume_id=None,
                volume_size=1, disk_bus='virtio-scsi')])
        image_cache = volumes = {}
        self.assertRaises(exception.InvalidBDMDiskBus,
                          self.compute_api._validate_bdm,
                          self.context, instance, objects.Flavor(),
                          bdms, image_cache, volumes)

    def test_the_specified_volume_type_id_assignment_to_name(self):
        """Test _check_requested_volume_type method is called, if the user
        is using the volume type ID, assign volume_type to volume type name.
        """
        volume_type = 'fake_volume_type_id_1'
        volume_types = [{'id': 'fake_volume_type_id_1', 'name': 'fake_lvm_1'},
                        {'id': 'fake_volume_type_id_2', 'name': 'fake_lvm_2'}]

        bdms = [objects.BlockDeviceMapping(
            **fake_block_device.AnonFakeDbBlockDeviceDict(
                {
                    'uuid': uuids.image_id,
                    'source_type': 'image',
                    'destination_type': 'volume',
                    'device_name': 'vda',
                    'boot_index': 0,
                    'volume_size': 3,
                    'volume_type': 'fake_volume_type_id_1'
                }))]

        self.compute_api._check_requested_volume_type(bdms[0],
                                                      volume_type,
                                                      volume_types)
        self.assertEqual(bdms[0].volume_type, volume_types[0]['name'])

    def _test_provision_instances_with_cinder_error(self,
                                                    expected_exception):
        @mock.patch('nova.compute.utils.check_num_instances_quota')
        @mock.patch.object(objects.Instance, 'create')
        @mock.patch.object(objects.RequestSpec, 'from_components')
        def do_test(
                mock_req_spec_from_components, _mock_create,
                mock_check_num_inst_quota):
            req_spec_mock = mock.MagicMock()

            mock_check_num_inst_quota.return_value = 1
            mock_req_spec_from_components.return_value = req_spec_mock

            ctxt = context.RequestContext('fake-user', 'fake-project')
            flavor = self._create_flavor()
            min_count = max_count = 1
            boot_meta = {
                'id': 'fake-image-id',
                'properties': {'mappings': []},
                'status': 'fake-status',
                'location': 'far-away'}
            base_options = {'image_ref': 'fake-ref',
                            'display_name': 'fake-name',
                            'project_id': 'fake-project',
                            'availability_zone': None,
                            'metadata': {},
                            'access_ip_v4': None,
                            'access_ip_v6': None,
                            'config_drive': None,
                            'key_name': None,
                            'reservation_id': None,
                            'kernel_id': None,
                            'ramdisk_id': None,
                            'root_device_name': None,
                            'user_data': None,
                            'numa_topology': None,
                            'pci_requests': None,
                            'port_resource_requests': None}
            security_groups = {}
            block_device_mapping = objects.BlockDeviceMappingList(
                objects=[objects.BlockDeviceMapping(
                    **fake_block_device.FakeDbBlockDeviceDict(
                    {
                     'id': 1,
                     'volume_id': 1,
                     'source_type': 'volume',
                     'destination_type': 'volume',
                     'device_name': 'vda',
                     'boot_index': 0,
                     }))])
            shutdown_terminate = True
            instance_group = None
            check_server_group_quota = False
            filter_properties = {'scheduler_hints': None,
                    'instance_type': flavor}
            trusted_certs = None

            self.assertRaises(expected_exception,
                              self.compute_api._provision_instances, ctxt,
                              flavor, min_count, max_count, base_options,
                              boot_meta, security_groups, block_device_mapping,
                              shutdown_terminate, instance_group,
                              check_server_group_quota, filter_properties,
                              None, objects.TagList(), trusted_certs, False)

        do_test()

    @mock.patch.object(cinder.API, 'get',
             side_effect=exception.CinderConnectionFailed(reason='error'))
    def test_provision_instances_with_cinder_down(self, mock_get):
        self._test_provision_instances_with_cinder_error(
            expected_exception=exception.CinderConnectionFailed)

    @mock.patch.object(cinder.API, 'get', new=mock.Mock(
        return_value={'id': '1', 'multiattach': False}))
    @mock.patch.object(cinder.API, 'check_availability_zone', new=mock.Mock())
    @mock.patch.object(cinder.API, 'attachment_create', new=mock.Mock(
        side_effect=exception.InvalidInput(reason='error')))
    def test_provision_instances_with_error_volume(self):
        self._test_provision_instances_with_cinder_error(
            expected_exception=exception.InvalidVolume)

    @mock.patch('nova.objects.RequestSpec.from_components')
    @mock.patch('nova.objects.BuildRequest')
    @mock.patch('nova.objects.Instance')
    @mock.patch('nova.objects.InstanceMapping.create')
    def test_provision_instances_with_keypair(self, mock_im, mock_instance,
                                              mock_br, mock_rs):
        fake_keypair = objects.KeyPair(name='test')
        inst_type = self._create_flavor()

        @mock.patch.object(self.compute_api, '_get_volumes_for_bdms')
        @mock.patch.object(self.compute_api,
                           '_create_reqspec_buildreq_instmapping',
                           new=mock.MagicMock())
        @mock.patch('nova.compute.utils.check_num_instances_quota')
        @mock.patch('nova.network.security_group_api')
        @mock.patch.object(self.compute_api,
                           'create_db_entry_for_new_instance')
        @mock.patch.object(self.compute_api,
                           '_bdm_validate_set_size_and_instance')
        def do_test(mock_bdm_v, mock_cdb, mock_sg, mock_cniq, mock_get_vols):
            mock_cniq.return_value = 1
            self.compute_api._provision_instances(self.context,
                                                  inst_type,
                                                  1, 1, mock.MagicMock(),
                                                  {}, None,
                                                  None, None, None, {}, None,
                                                  fake_keypair,
                                                  objects.TagList(), None,
                                                  False)
            self.assertEqual(
                'test',
                mock_instance.return_value.keypairs.objects[0].name)
            self.compute_api._provision_instances(self.context,
                                                  inst_type,
                                                  1, 1, mock.MagicMock(),
                                                  {}, None,
                                                  None, None, None, {}, None,
                                                  None, objects.TagList(),
                                                  None, False)
            self.assertEqual(
                0,
                len(mock_instance.return_value.keypairs.objects))

        do_test()

    @mock.patch('nova.accelerator.cyborg.get_device_profile_request_groups')
    @mock.patch('nova.objects.RequestSpec.from_components')
    @mock.patch('nova.objects.BuildRequest')
    @mock.patch('nova.objects.Instance')
    @mock.patch('nova.objects.InstanceMapping.create')
    def _test_provision_instances_with_accels(self,
        instance_type, dp_request_groups, prev_request_groups,
        mock_im, mock_instance, mock_br, mock_rs, mock_get_dp):

        @mock.patch.object(self.compute_api, '_get_volumes_for_bdms')
        @mock.patch.object(self.compute_api,
                           '_create_reqspec_buildreq_instmapping',
                           new=mock.MagicMock())
        @mock.patch('nova.compute.utils.check_num_instances_quota')
        @mock.patch('nova.network.security_group_api')
        @mock.patch.object(self.compute_api,
                           'create_db_entry_for_new_instance')
        @mock.patch.object(self.compute_api,
                           '_bdm_validate_set_size_and_instance')
        def do_test(mock_bdm_v, mock_cdb, mock_sg, mock_cniq, mock_get_vols):
            mock_cniq.return_value = 1
            self.compute_api._provision_instances(self.context,
                                                  instance_type,
                                                  1, 1, mock.MagicMock(),
                                                  {}, None,
                                                  None, None, None, {}, None,
                                                  None,
                                                  objects.TagList(), None,
                                                  False)

        mock_get_dp.return_value = dp_request_groups
        fake_rs = fake_request_spec.fake_spec_obj()
        fake_rs.requested_resources = prev_request_groups
        mock_rs.return_value = fake_rs
        do_test()
        return mock_get_dp, fake_rs

    def test_provision_instances_with_accels_ok(self):
        # If extra_specs has accel spec, device profile's request_groups
        # should be obtained, and added to reqspec's requested_resources.
        dp_name = 'mydp'
        extra_specs = {'extra_specs': {'accel:device_profile': dp_name}}
        instance_type = self._create_flavor(**extra_specs)

        prev_groups = [objects.RequestGroup(requester_id='prev0'),
                       objects.RequestGroup(requester_id='prev1')]
        dp_groups = [objects.RequestGroup(requester_id='deviceprofile2'),
                     objects.RequestGroup(requester_id='deviceprofile3')]

        mock_get_dp, fake_rs = self._test_provision_instances_with_accels(
            instance_type, dp_groups, prev_groups)
        mock_get_dp.assert_called_once_with(self.context, dp_name)
        self.assertEqual(prev_groups + dp_groups, fake_rs.requested_resources)

    def test_provision_instances_with_accels_no_dp(self):
        # If extra specs has no accel spec, no attempt should be made to
        # get device profile's request_groups, and reqspec.requested_resources
        # should be left unchanged.
        instance_type = self._create_flavor()
        prev_groups = [objects.RequestGroup(requester_id='prev0'),
                       objects.RequestGroup(requester_id='prev1')]
        mock_get_dp, fake_rs = self._test_provision_instances_with_accels(
            instance_type, [], prev_groups)
        mock_get_dp.assert_not_called()
        self.assertEqual(prev_groups, fake_rs.requested_resources)

    def test_provision_instances_creates_build_request(self):
        @mock.patch.object(self.compute_api, '_get_volumes_for_bdms')
        @mock.patch.object(self.compute_api,
                           '_create_reqspec_buildreq_instmapping')
        @mock.patch.object(objects.Instance, 'create')
        @mock.patch('nova.compute.utils.check_num_instances_quota')
        @mock.patch.object(objects.RequestSpec, 'from_components')
        def do_test(mock_req_spec_from_components, mock_check_num_inst_quota,
                    mock_inst_create, mock_create_rs_br_im, mock_get_volumes):

            min_count = 1
            max_count = 2
            mock_check_num_inst_quota.return_value = 2

            ctxt = context.RequestContext('fake-user', 'fake-project')
            flavor = self._create_flavor()
            boot_meta = {
                'id': 'fake-image-id',
                'properties': {'mappings': []},
                'status': 'fake-status',
                'location': 'far-away'}
            base_options = {'image_ref': 'fake-ref',
                            'display_name': 'fake-name',
                            'project_id': 'fake-project',
                            'availability_zone': None,
                            'metadata': {},
                            'access_ip_v4': None,
                            'access_ip_v6': None,
                            'config_drive': None,
                            'key_name': None,
                            'reservation_id': None,
                            'kernel_id': None,
                            'ramdisk_id': None,
                            'root_device_name': None,
                            'user_data': None,
                            'numa_topology': None,
                            'pci_requests': None,
                            'port_resource_requests': None}
            security_groups = {}
            block_device_mappings = objects.BlockDeviceMappingList(
                objects=[objects.BlockDeviceMapping(
                    **fake_block_device.FakeDbBlockDeviceDict(
                    {
                     'id': 1,
                     'volume_id': 1,
                     'source_type': 'volume',
                     'destination_type': 'volume',
                     'device_name': 'vda',
                     'boot_index': 0,
                     }))])
            instance_tags = objects.TagList(objects=[objects.Tag(tag='tag')])
            shutdown_terminate = True
            trusted_certs = None
            instance_group = None
            check_server_group_quota = False
            filter_properties = {'scheduler_hints': None,
                    'instance_type': flavor}

            with mock.patch.object(
                    self.compute_api,
                    '_bdm_validate_set_size_and_instance',
                    return_value=block_device_mappings) as validate_bdm:
                instances_to_build = self.compute_api._provision_instances(
                        ctxt, flavor,
                        min_count, max_count, base_options, boot_meta,
                        security_groups, block_device_mappings,
                        shutdown_terminate, instance_group,
                        check_server_group_quota, filter_properties, None,
                        instance_tags, trusted_certs, False)
            validate_bdm.assert_has_calls([mock.call(
                ctxt, test.MatchType(objects.Instance), flavor,
                block_device_mappings, {}, mock_get_volumes.return_value,
                False)] * max_count)

            for rs, br, im in instances_to_build:
                self.assertIsInstance(br.instance, objects.Instance)
                self.assertTrue(uuidutils.is_uuid_like(br.instance.uuid))
                self.assertEqual(base_options['project_id'],
                                 br.instance.project_id)
                self.assertEqual(1, br.block_device_mappings[0].id)
                self.assertEqual(br.instance.uuid, br.tags[0].resource_id)
                mock_create_rs_br_im.assert_any_call(ctxt, rs, br, im)

        do_test()

    def test_provision_instances_creates_instance_mapping(self):
        @mock.patch.object(self.compute_api, '_get_volumes_for_bdms')
        @mock.patch.object(self.compute_api,
                           '_create_reqspec_buildreq_instmapping',
                           new=mock.MagicMock())
        @mock.patch('nova.compute.utils.check_num_instances_quota')
        @mock.patch.object(objects.Instance, 'create', new=mock.MagicMock())
        @mock.patch.object(self.compute_api, '_validate_bdm',
                new=mock.MagicMock())
        @mock.patch.object(objects.RequestSpec, 'from_components')
        @mock.patch('nova.objects.InstanceMapping')
        def do_test(mock_inst_mapping, mock_rs, mock_check_num_inst_quota,
                    mock_get_vols):
            inst_mapping_mock = mock.MagicMock()

            mock_check_num_inst_quota.return_value = 1
            mock_inst_mapping.return_value = inst_mapping_mock

            ctxt = context.RequestContext('fake-user', 'fake-project')
            flavor = self._create_flavor()
            min_count = max_count = 1
            boot_meta = {
                'id': 'fake-image-id',
                'properties': {'mappings': []},
                'status': 'fake-status',
                'location': 'far-away'}
            base_options = {'image_ref': 'fake-ref',
                            'display_name': 'fake-name',
                            'project_id': 'fake-project',
                            'availability_zone': None,
                            'metadata': {},
                            'access_ip_v4': None,
                            'access_ip_v6': None,
                            'config_drive': None,
                            'key_name': None,
                            'reservation_id': None,
                            'kernel_id': None,
                            'ramdisk_id': None,
                            'root_device_name': None,
                            'user_data': None,
                            'numa_topology': None,
                            'pci_requests': None,
                            'port_resource_requests': None}
            security_groups = {}
            block_device_mapping = objects.BlockDeviceMappingList(
                objects=[objects.BlockDeviceMapping(
                    **fake_block_device.FakeDbBlockDeviceDict(
                    {
                     'id': 1,
                     'volume_id': 1,
                     'source_type': 'volume',
                     'destination_type': 'volume',
                     'device_name': 'vda',
                     'boot_index': 0,
                     }))])
            shutdown_terminate = True
            instance_group = None
            check_server_group_quota = False
            filter_properties = {'scheduler_hints': None,
                    'instance_type': flavor}
            trusted_certs = None

            instances_to_build = (
                self.compute_api._provision_instances(ctxt, flavor,
                    min_count, max_count, base_options, boot_meta,
                    security_groups, block_device_mapping, shutdown_terminate,
                    instance_group, check_server_group_quota,
                    filter_properties, None, objects.TagList(), trusted_certs,
                    False))
            rs, br, im = instances_to_build[0]
            self.assertTrue(uuidutils.is_uuid_like(br.instance.uuid))
            self.assertEqual(br.instance_uuid, im.instance_uuid)

            self.assertEqual(br.instance.uuid,
                             inst_mapping_mock.instance_uuid)
            self.assertIsNone(inst_mapping_mock.cell_mapping)
            self.assertEqual(ctxt.project_id, inst_mapping_mock.project_id)
            # Verify that the instance mapping created has user_id populated.
            self.assertEqual(ctxt.user_id, inst_mapping_mock.user_id)
        do_test()

    @mock.patch.object(cinder.API, 'get',
                       return_value={'id': '1', 'multiattach': False})
    @mock.patch.object(cinder.API, 'check_availability_zone',)
    @mock.patch.object(cinder.API, 'attachment_create',
                       side_effect=[{'id': uuids.attachment_id},
                                    exception.InvalidInput(reason='error')])
    @mock.patch.object(objects.BlockDeviceMapping, 'save')
    def test_provision_instances_cleans_up_when_volume_invalid_new_flow(self,
            _mock_bdm, _mock_cinder_attach_create,
            _mock_cinder_check_availability_zone, _mock_cinder_get):
        @mock.patch.object(self.compute_api,
                           '_create_reqspec_buildreq_instmapping')
        @mock.patch('nova.compute.utils.check_num_instances_quota')
        @mock.patch.object(objects, 'Instance')
        @mock.patch.object(objects.RequestSpec, 'from_components')
        @mock.patch.object(objects, 'BuildRequest')
        @mock.patch.object(objects, 'InstanceMapping')
        def do_test(mock_inst_mapping, mock_build_req,
                mock_req_spec_from_components, mock_inst,
                mock_check_num_inst_quota, mock_create_rs_br_im):

            min_count = 1
            max_count = 2
            mock_check_num_inst_quota.return_value = 2
            req_spec_mock = mock.MagicMock()
            mock_req_spec_from_components.return_value = req_spec_mock
            inst_mocks = [mock.MagicMock() for i in range(max_count)]
            for inst_mock in inst_mocks:
                inst_mock.project_id = 'fake-project'
            mock_inst.side_effect = inst_mocks
            build_req_mocks = [mock.MagicMock() for i in range(max_count)]
            mock_build_req.side_effect = build_req_mocks
            inst_map_mocks = [mock.MagicMock() for i in range(max_count)]
            mock_inst_mapping.side_effect = inst_map_mocks

            ctxt = context.RequestContext('fake-user', 'fake-project')
            flavor = self._create_flavor(extra_specs={})
            boot_meta = {
                'id': 'fake-image-id',
                'properties': {'mappings': []},
                'status': 'fake-status',
                'location': 'far-away'}
            base_options = {'image_ref': 'fake-ref',
                            'display_name': 'fake-name',
                            'project_id': 'fake-project',
                            'availability_zone': None,
                            'metadata': {},
                            'access_ip_v4': None,
                            'access_ip_v6': None,
                            'config_drive': None,
                            'key_name': None,
                            'reservation_id': None,
                            'kernel_id': None,
                            'ramdisk_id': None,
                            'root_device_name': None,
                            'user_data': None,
                            'numa_topology': None,
                            'pci_requests': None,
                            'port_resource_requests': None}
            security_groups = {}
            block_device_mapping = objects.BlockDeviceMappingList(
                objects=[objects.BlockDeviceMapping(
                    **fake_block_device.FakeDbBlockDeviceDict(
                    {
                     'id': 1,
                     'volume_id': 1,
                     'source_type': 'volume',
                     'destination_type': 'volume',
                     'device_name': 'vda',
                     'boot_index': 0,
                     }))])
            shutdown_terminate = True
            instance_group = None
            check_server_group_quota = False
            filter_properties = {'scheduler_hints': None,
                    'instance_type': flavor}
            tags = objects.TagList()
            trusted_certs = None
            self.assertRaises(exception.InvalidVolume,
                              self.compute_api._provision_instances, ctxt,
                              flavor, min_count, max_count, base_options,
                              boot_meta, security_groups, block_device_mapping,
                              shutdown_terminate, instance_group,
                              check_server_group_quota, filter_properties,
                              None, tags, trusted_certs, False)
            # First instance, build_req, mapping is created and destroyed
            mock_create_rs_br_im.assert_called_once_with(ctxt, req_spec_mock,
                                                         build_req_mocks[0],
                                                         inst_map_mocks[0])
            self.assertTrue(build_req_mocks[0].destroy.called)
            self.assertTrue(inst_map_mocks[0].destroy.called)
            # Second instance, build_req, mapping is not created nor destroyed
            self.assertFalse(inst_mocks[1].create.called)
            self.assertFalse(inst_mocks[1].destroy.called)
            self.assertFalse(build_req_mocks[1].destroy.called)
            self.assertFalse(inst_map_mocks[1].destroy.called)

        do_test()

    def test_provision_instances_creates_reqspec_with_secgroups(self):
        @mock.patch.object(self.compute_api,
                           '_create_reqspec_buildreq_instmapping',
                           new=mock.MagicMock())
        @mock.patch('nova.compute.utils.check_num_instances_quota')
        @mock.patch('nova.network.security_group_api'
                    '.populate_security_groups')
        @mock.patch.object(compute_api, 'objects')
        @mock.patch.object(self.compute_api,
                           'create_db_entry_for_new_instance',
                           new=mock.MagicMock())
        @mock.patch.object(self.compute_api,
                           '_bdm_validate_set_size_and_instance',
                           new=mock.MagicMock())
        def test(mock_objects, mock_secgroup, mock_cniq):
            ctxt = context.RequestContext('fake-user', 'fake-project')
            mock_cniq.return_value = 1
            inst_type = self._create_flavor()
            self.compute_api._provision_instances(ctxt, inst_type, None, None,
                                                  mock.MagicMock(), None, None,
                                                  [], None, None, None, None,
                                                  None, objects.TagList(),
                                                  None, False)
            secgroups = mock_secgroup.return_value
            mock_objects.RequestSpec.from_components.assert_called_once_with(
                mock.ANY, mock.ANY, mock.ANY, mock.ANY, mock.ANY, mock.ANY,
                mock.ANY, mock.ANY, mock.ANY,
                security_groups=secgroups, port_resource_requests=mock.ANY)
        test()

    def _test_rescue(self, vm_state=vm_states.ACTIVE, rescue_password=None,
                     rescue_image=None, clean_shutdown=True):
        instance = self._create_instance_obj(params={'vm_state': vm_state})
        rescue_image_meta_obj = image_meta_obj.ImageMeta.from_dict({})
        bdms = []
        with test.nested(
            mock.patch.object(objects.BlockDeviceMappingList,
                              'get_by_instance_uuid', return_value=bdms),
            mock.patch.object(compute_utils, 'is_volume_backed_instance',
                              return_value=False),
            mock.patch.object(instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(self.compute_api.compute_rpcapi,
                              'rescue_instance'),
            mock.patch.object(objects.ImageMeta, 'from_image_ref',
                              return_value=rescue_image_meta_obj),
        ) as (
            bdm_get_by_instance_uuid, volume_backed_inst, instance_save,
            record_action_start, rpcapi_rescue_instance, mock_find_image_ref,
        ):
            self.compute_api.rescue(self.context, instance,
                                    rescue_password=rescue_password,
                                    rescue_image_ref=rescue_image,
                                    clean_shutdown=clean_shutdown)
            # assert field values set on the instance object
            self.assertEqual(task_states.RESCUING, instance.task_state)
            # assert our mock calls
            bdm_get_by_instance_uuid.assert_called_once_with(
                self.context, instance.uuid)
            volume_backed_inst.assert_called_once_with(
                self.context, instance, bdms)
            instance_save.assert_called_once_with(expected_task_state=[None])
            record_action_start.assert_called_once_with(
                self.context, instance, instance_actions.RESCUE)
            rpcapi_rescue_instance.assert_called_once_with(
                self.context, instance=instance,
                rescue_password=rescue_password,
                rescue_image_ref=rescue_image,
                clean_shutdown=clean_shutdown)
            if rescue_image:
                mock_find_image_ref.assert_called_once_with(
                    self.context, self.compute_api.image_api, rescue_image)

    def test_rescue_active(self):
        self._test_rescue()

    def test_rescue_stopped(self):
        self._test_rescue(vm_state=vm_states.STOPPED)

    def test_rescue_error(self):
        self._test_rescue(vm_state=vm_states.ERROR)

    def test_rescue_with_password(self):
        self._test_rescue(rescue_password='fake-password')

    def test_rescue_with_image(self):
        self._test_rescue(rescue_image='fake-image')

    def test_rescue_forced_shutdown(self):
        self._test_rescue(clean_shutdown=False)

    def test_unrescue(self):
        instance = self._create_instance_obj(
            params={'vm_state': vm_states.RESCUED})
        with test.nested(
            mock.patch.object(instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(self.compute_api.compute_rpcapi,
                              'unrescue_instance')
        ) as (
            instance_save, record_action_start, rpcapi_unrescue_instance
        ):
            self.compute_api.unrescue(self.context, instance)
            # assert field values set on the instance object
            self.assertEqual(task_states.UNRESCUING, instance.task_state)
            # assert our mock calls
            instance_save.assert_called_once_with(expected_task_state=[None])
            record_action_start.assert_called_once_with(
                self.context, instance, instance_actions.UNRESCUE)
            rpcapi_unrescue_instance.assert_called_once_with(
                self.context, instance=instance)

    @mock.patch('nova.objects.image_meta.ImageMeta.from_image_ref')
    @mock.patch('nova.objects.compute_node.ComputeNode'
                '.get_by_host_and_nodename')
    @mock.patch('nova.compute.utils.is_volume_backed_instance',
                return_value=True)
    @mock.patch('nova.objects.block_device.BlockDeviceMappingList'
                '.get_by_instance_uuid')
    def test_rescue_bfv_with_required_trait(self, mock_get_bdms,
            mock_is_volume_backed, mock_get_cn, mock_image_meta_obj_from_ref):
        instance = self._create_instance_obj()
        bdms = objects.BlockDeviceMappingList(objects=[
                objects.BlockDeviceMapping(
                    boot_index=0, image_id=uuids.image_id, source_type='image',
                    destination_type='volume', volume_type=None,
                    snapshot_id=None, volume_id=uuids.volume_id,
                    volume_size=None)])
        rescue_image_meta_obj = image_meta_obj.ImageMeta.from_dict({})

        with test.nested(
            mock.patch.object(self.compute_api.placementclient,
                              'get_provider_traits'),
            mock.patch.object(self.compute_api.volume_api, 'get'),
            mock.patch.object(self.compute_api.volume_api, 'check_attached'),
            mock.patch.object(instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(self.compute_api.compute_rpcapi,
                              'rescue_instance')
        ) as (
            mock_get_traits, mock_get_volume, mock_check_attached,
            mock_instance_save, mock_record_start, mock_rpcapi_rescue
        ):
            # Mock out the returned compute node, image, bdms and volume
            mock_get_cn.return_value = mock.Mock(uuid=uuids.cn)
            mock_image_meta_obj_from_ref.return_value = rescue_image_meta_obj
            mock_get_bdms.return_value = bdms
            mock_get_volume.return_value = mock.sentinel.volume

            # Ensure the required trait is returned, allowing BFV rescue
            mock_trait_info = mock.Mock(traits=[ot.COMPUTE_RESCUE_BFV])
            mock_get_traits.return_value = mock_trait_info

            # Try to rescue the instance
            self.compute_api.rescue(self.context, instance,
                                    rescue_image_ref=uuids.rescue_image_id,
                                    allow_bfv_rescue=True)

            # Assert all of the calls made in the compute API
            mock_get_bdms.assert_called_once_with(self.context, instance.uuid)
            mock_get_volume.assert_called_once_with(
                self.context, uuids.volume_id)
            mock_check_attached.assert_called_once_with(
                self.context, mock.sentinel.volume)
            mock_is_volume_backed.assert_called_once_with(
                self.context, instance, bdms)
            mock_get_cn.assert_called_once_with(
                self.context, instance.host, instance.node)
            mock_get_traits.assert_called_once_with(self.context, uuids.cn)
            mock_instance_save.assert_called_once_with(
                expected_task_state=[None])
            mock_record_start.assert_called_once_with(
                self.context, instance, instance_actions.RESCUE)
            mock_rpcapi_rescue.assert_called_once_with(
                self.context, instance=instance, rescue_password=None,
                rescue_image_ref=uuids.rescue_image_id, clean_shutdown=True)

            # Assert that the instance task state as set in the compute API
            self.assertEqual(task_states.RESCUING, instance.task_state)

    @mock.patch('nova.objects.compute_node.ComputeNode'
                '.get_by_host_and_nodename')
    @mock.patch('nova.compute.utils.is_volume_backed_instance',
                return_value=True)
    @mock.patch('nova.objects.block_device.BlockDeviceMappingList'
                '.get_by_instance_uuid')
    def test_rescue_bfv_without_required_trait(self, mock_get_bdms,
                                               mock_is_volume_backed,
                                               mock_get_cn):
        instance = self._create_instance_obj()
        bdms = objects.BlockDeviceMappingList(objects=[
                objects.BlockDeviceMapping(
                    boot_index=0, image_id=uuids.image_id, source_type='image',
                    destination_type='volume', volume_type=None,
                    snapshot_id=None, volume_id=uuids.volume_id,
                    volume_size=None)])
        with test.nested(
            mock.patch.object(self.compute_api.placementclient,
                              'get_provider_traits'),
            mock.patch.object(self.compute_api.volume_api, 'get'),
            mock.patch.object(self.compute_api.volume_api, 'check_attached'),
        ) as (
            mock_get_traits, mock_get_volume, mock_check_attached
        ):
            # Mock out the returned compute node, bdms and volume
            mock_get_bdms.return_value = bdms
            mock_get_volume.return_value = mock.sentinel.volume
            mock_get_cn.return_value = mock.Mock(uuid=uuids.cn)

            # Ensure the required trait is not returned, denying BFV rescue
            mock_trait_info = mock.Mock(traits=[])
            mock_get_traits.return_value = mock_trait_info

            # Assert that any attempt to rescue a bfv instance on a compute
            # node that does not report the COMPUTE_RESCUE_BFV trait fails and
            # raises InstanceNotRescuable
            self.assertRaises(exception.InstanceNotRescuable,
                              self.compute_api.rescue, self.context, instance,
                              rescue_image_ref=None, allow_bfv_rescue=True)

            # Assert the calls made in the compute API prior to the failure
            mock_get_bdms.assert_called_once_with(self.context, instance.uuid)
            mock_get_volume.assert_called_once_with(
                self.context, uuids.volume_id)
            mock_check_attached.assert_called_once_with(
                self.context, mock.sentinel.volume)
            mock_is_volume_backed.assert_called_once_with(
                self.context, instance, bdms)
            mock_get_cn.assert_called_once_with(
                self.context, instance.host, instance.node)
            mock_get_traits.assert_called_once_with(
                self.context, uuids.cn)

    @mock.patch('nova.compute.utils.is_volume_backed_instance',
                return_value=True)
    @mock.patch('nova.objects.block_device.BlockDeviceMappingList'
                '.get_by_instance_uuid')
    def test_rescue_bfv_without_allow_flag(self, mock_get_bdms,
                                           mock_is_volume_backed):
        instance = self._create_instance_obj()
        bdms = objects.BlockDeviceMappingList(objects=[
                objects.BlockDeviceMapping(
                    boot_index=0, image_id=uuids.image_id, source_type='image',
                    destination_type='volume', volume_type=None,
                    snapshot_id=None, volume_id=uuids.volume_id,
                    volume_size=None)])
        with test.nested(
            mock.patch.object(self.compute_api.volume_api, 'get'),
            mock.patch.object(self.compute_api.volume_api, 'check_attached'),
        ) as (
            mock_get_volume, mock_check_attached
        ):
            # Mock out the returned bdms and volume
            mock_get_bdms.return_value = bdms
            mock_get_volume.return_value = mock.sentinel.volume

            # Assert that any attempt to rescue a bfv instance with
            # allow_bfv_rescue=False fails and raises InstanceNotRescuable
            self.assertRaises(exception.InstanceNotRescuable,
                              self.compute_api.rescue, self.context, instance,
                              rescue_image_ref=None, allow_bfv_rescue=False)

            # Assert the calls made in the compute API prior to the failure
            mock_get_bdms.assert_called_once_with(self.context, instance.uuid)
            mock_get_volume.assert_called_once_with(
                self.context, uuids.volume_id)
            mock_check_attached.assert_called_once_with(
                self.context, mock.sentinel.volume)
            mock_is_volume_backed.assert_called_once_with(
                self.context, instance, bdms)

    @mock.patch('nova.objects.image_meta.ImageMeta.from_image_ref')
    def test_rescue_from_image_ref_failure(self, mock_image_meta_obj_from_ref):
        instance = self._create_instance_obj()
        mock_image_meta_obj_from_ref.side_effect = [
            exception.ImageNotFound(image_id=mock.sentinel.rescue_image_ref),
            exception.ImageBadRequest(
                image_id=mock.sentinel.rescue_image_ref, response='bar')]

        # Assert that UnsupportedRescueImage is raised when from_image_ref
        # returns exception.ImageNotFound
        self.assertRaises(exception.UnsupportedRescueImage,
                          self.compute_api.rescue, self.context, instance,
                          rescue_image_ref=mock.sentinel.rescue_image_ref)

        # Assert that UnsupportedRescueImage is raised when from_image_ref
        # returns exception.ImageBadRequest
        self.assertRaises(exception.UnsupportedRescueImage,
                          self.compute_api.rescue, self.context, instance,
                          rescue_image_ref=mock.sentinel.rescue_image_ref)

        # Assert that we called from_image_ref using the provided ref
        mock_image_meta_obj_from_ref.assert_has_calls([
            mock.call(self.context, self.compute_api.image_api,
                mock.sentinel.rescue_image_ref),
            mock.call(self.context, self.compute_api.image_api,
                mock.sentinel.rescue_image_ref)])

    @mock.patch('nova.objects.image_meta.ImageMeta.from_image_ref')
    def test_rescue_using_volume_backed_snapshot(self,
            mock_image_meta_obj_from_ref):
        instance = self._create_instance_obj()
        rescue_image_obj = image_meta_obj.ImageMeta.from_dict(
            {'min_disk': 0, 'min_ram': 0,
             'properties': {'bdm_v2': True, 'block_device_mapping': [{}]},
             'size': 0, 'status': 'active'})
        mock_image_meta_obj_from_ref.return_value = rescue_image_obj

        # Assert that UnsupportedRescueImage is raised
        self.assertRaises(exception.UnsupportedRescueImage,
                          self.compute_api.rescue, self.context, instance,
                          rescue_image_ref=mock.sentinel.rescue_image_ref)

        # Assert that we called from_image_ref using the provided ref
        mock_image_meta_obj_from_ref.assert_called_once_with(
            self.context, self.compute_api.image_api,
            mock.sentinel.rescue_image_ref)

    def test_set_admin_password_invalid_state(self):
        # Tests that InstanceInvalidState is raised when not ACTIVE.
        instance = self._create_instance_obj({'vm_state': vm_states.STOPPED})
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.set_admin_password,
                          self.context, instance)

    def test_set_admin_password(self):
        # Ensure instance can have its admin password set.
        instance = self._create_instance_obj()

        @mock.patch.object(objects.Instance, 'save')
        @mock.patch.object(self.compute_api, '_record_action_start')
        @mock.patch.object(self.compute_api.compute_rpcapi,
                           'set_admin_password')
        def do_test(compute_rpcapi_mock, record_mock, instance_save_mock):
            # call the API
            self.compute_api.set_admin_password(self.context, instance, 'pass')
            # make our assertions
            instance_save_mock.assert_called_once_with(
                expected_task_state=[None])
            record_mock.assert_called_once_with(
                self.context, instance, instance_actions.CHANGE_PASSWORD)
            compute_rpcapi_mock.assert_called_once_with(
                self.context, instance=instance, new_pass='pass')

        do_test()

    def _test_attach_interface_invalid_state(self, state):
        instance = self._create_instance_obj(
            params={'vm_state': state})
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.attach_interface,
                          self.context, instance, '', '', '', [])

    def test_attach_interface_invalid_state(self):
        for state in [vm_states.BUILDING, vm_states.DELETED,
                      vm_states.ERROR, vm_states.RESCUED,
                      vm_states.RESIZED, vm_states.SOFT_DELETED,
                      vm_states.SUSPENDED, vm_states.SHELVED,
                      vm_states.SHELVED_OFFLOADED]:
            self._test_attach_interface_invalid_state(state)

    def _test_detach_interface_invalid_state(self, state):
        instance = self._create_instance_obj(
            params={'vm_state': state})
        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.detach_interface,
                          self.context, instance, '', '', '', [])

    def test_detach_interface_invalid_state(self):
        for state in [vm_states.BUILDING, vm_states.DELETED,
                      vm_states.ERROR, vm_states.RESCUED,
                      vm_states.RESIZED, vm_states.SOFT_DELETED,
                      vm_states.SUSPENDED, vm_states.SHELVED,
                      vm_states.SHELVED_OFFLOADED]:
            self._test_detach_interface_invalid_state(state)

    def _test_check_and_transform_bdm(self, block_device_mapping):
        instance_type = self._create_flavor()
        base_options = {'uuid': uuids.bdm_instance,
                        'image_ref': 'fake_image_ref',
                        'metadata': {}}
        image_meta = {'status': 'active',
                      'name': 'image_name',
                      'deleted': False,
                      'container_format': 'bare',
                      'id': 'image_id'}
        legacy_bdm = False
        block_device_mapping = block_device_mapping
        self.assertRaises(exception.InvalidRequest,
                          self.compute_api._check_and_transform_bdm,
                          self.context, base_options, instance_type,
                          image_meta, 1, 1, block_device_mapping, legacy_bdm)

    def test_check_and_transform_bdm_source_volume(self):
        block_device_mapping = [{'boot_index': 0,
                                 'device_name': None,
                                 'image_id': 'image_id',
                                 'source_type': 'image'},
                                {'device_name': '/dev/vda',
                                 'source_type': 'volume',
                                 'destination_type': 'volume',
                                 'device_type': None,
                                 'volume_id': 'volume_id'}]
        self._test_check_and_transform_bdm(block_device_mapping)

    def test_check_and_transform_bdm_source_snapshot(self):
        block_device_mapping = [{'boot_index': 0,
                                 'device_name': None,
                                 'image_id': 'image_id',
                                 'source_type': 'image'},
                                {'device_name': '/dev/vda',
                                 'source_type': 'snapshot',
                                 'destination_type': 'volume',
                                 'device_type': None,
                                 'volume_id': 'volume_id'}]
        self._test_check_and_transform_bdm(block_device_mapping)

    def test_bdm_validate_set_size_and_instance(self):
        swap_size = 42
        ephemeral_size = 24
        instance = self._create_instance_obj()
        instance_type = self._create_flavor(swap=swap_size,
                                            ephemeral_gb=ephemeral_size)
        block_device_mapping = [
                {'device_name': '/dev/sda1',
                 'source_type': 'snapshot', 'destination_type': 'volume',
                 'snapshot_id': '00000000-aaaa-bbbb-cccc-000000000000',
                 'delete_on_termination': False,
                 'boot_index': 0},
                {'device_name': '/dev/sdb2',
                 'source_type': 'blank', 'destination_type': 'local',
                 'guest_format': 'swap', 'delete_on_termination': False},
                {'device_name': '/dev/sdb3',
                 'source_type': 'blank', 'destination_type': 'local',
                 'guest_format': 'ext3', 'delete_on_termination': False}]

        block_device_mapping = (
                block_device_obj.block_device_make_list_from_dicts(
                    self.context,
                    map(fake_block_device.AnonFakeDbBlockDeviceDict,
                        block_device_mapping)))

        with mock.patch.object(self.compute_api, '_validate_bdm'):
            image_cache = volumes = {}
            bdms = self.compute_api._bdm_validate_set_size_and_instance(
                self.context, instance, instance_type, block_device_mapping,
                image_cache, volumes)

        expected = [{'device_name': '/dev/sda1',
                     'source_type': 'snapshot', 'destination_type': 'volume',
                     'snapshot_id': '00000000-aaaa-bbbb-cccc-000000000000',
                     'delete_on_termination': False,
                     'boot_index': 0},
                    {'device_name': '/dev/sdb2',
                     'source_type': 'blank', 'destination_type': 'local',
                     'guest_format': 'swap', 'delete_on_termination': False},
                    {'device_name': '/dev/sdb3',
                     'source_type': 'blank', 'destination_type': 'local',
                     'delete_on_termination': False}]
        # Check that the bdm matches what was asked for and that instance_uuid
        # and volume_size are set properly.
        for exp, bdm in zip(expected, bdms):
            self.assertEqual(exp['device_name'], bdm.device_name)
            self.assertEqual(exp['destination_type'], bdm.destination_type)
            self.assertEqual(exp['source_type'], bdm.source_type)
            self.assertEqual(exp['delete_on_termination'],
                             bdm.delete_on_termination)
            self.assertEqual(instance.uuid, bdm.instance_uuid)
        self.assertEqual(swap_size, bdms[1].volume_size)
        self.assertEqual(ephemeral_size, bdms[2].volume_size)

    @mock.patch.object(objects.BuildRequestList, 'get_by_filters')
    @mock.patch('nova.compute.instance_list.get_instance_objects_sorted')
    @mock.patch.object(objects.CellMapping, 'get_by_uuid')
    def test_tenant_to_project_conversion(self, mock_cell_map_get, mock_get,
                                          mock_buildreq_get):
        mock_cell_map_get.side_effect = exception.CellMappingNotFound(
                                                                uuid='fake')
        mock_get.return_value = objects.InstanceList(objects=[]), list()
        api = compute_api.API()
        api.get_all(self.context, search_opts={'tenant_id': 'foo'})
        filters = mock_get.call_args_list[0][0][1]
        self.assertEqual({'project_id': 'foo'}, filters)

    def test_populate_instance_names_host_name(self):
        params = dict(display_name="vm1")
        instance = self._create_instance_obj(params=params)
        self.compute_api._populate_instance_names(instance, 1, 0)
        self.assertEqual('vm1', instance.hostname)

    def test_populate_instance_names_host_name_is_empty(self):
        params = dict(display_name=u'\u865a\u62df\u673a\u662f\u4e2d\u6587')
        instance = self._create_instance_obj(params=params)
        self.compute_api._populate_instance_names(instance, 1, 0)
        self.assertEqual('Server-%s' % instance.uuid, instance.hostname)

    def test_populate_instance_names_host_name_multi(self):
        params = dict(display_name="vm")
        instance = self._create_instance_obj(params=params)
        self.compute_api._populate_instance_names(instance, 2, 1)
        self.assertEqual('vm-2', instance.hostname)

    def test_populate_instance_names_host_name_is_empty_multi(self):
        params = dict(display_name=u'\u865a\u62df\u673a\u662f\u4e2d\u6587')
        instance = self._create_instance_obj(params=params)
        self.compute_api._populate_instance_names(instance, 2, 1)
        self.assertEqual('Server-%s' % instance.uuid, instance.hostname)

    def test_host_statuses(self):
        five_min_ago = timeutils.utcnow() - datetime.timedelta(minutes=5)
        instances = [
            objects.Instance(uuid=uuids.instance_1, host='host1', services=
                             self._obj_to_list_obj(objects.ServiceList(
                             self.context), objects.Service(id=0, host='host1',
                             disabled=True, forced_down=True,
                             binary='nova-compute'))),
            objects.Instance(uuid=uuids.instance_2, host='host2', services=
                             self._obj_to_list_obj(objects.ServiceList(
                             self.context), objects.Service(id=0, host='host2',
                             disabled=True, forced_down=False,
                             binary='nova-compute'))),
            objects.Instance(uuid=uuids.instance_3, host='host3', services=
                             self._obj_to_list_obj(objects.ServiceList(
                             self.context), objects.Service(id=0, host='host3',
                             disabled=False, last_seen_up=five_min_ago,
                             forced_down=False, binary='nova-compute'))),
            objects.Instance(uuid=uuids.instance_4, host='host4', services=
                             self._obj_to_list_obj(objects.ServiceList(
                             self.context), objects.Service(id=0, host='host4',
                             disabled=False, last_seen_up=timeutils.utcnow(),
                             forced_down=False, binary='nova-compute'))),
            objects.Instance(uuid=uuids.instance_5, host='host5', services=
                             objects.ServiceList()),
            objects.Instance(uuid=uuids.instance_6, host=None, services=
                             self._obj_to_list_obj(objects.ServiceList(
                             self.context), objects.Service(id=0, host='host6',
                             disabled=True, forced_down=False,
                             binary='nova-compute'))),
            objects.Instance(uuid=uuids.instance_7, host='host2', services=
                             self._obj_to_list_obj(objects.ServiceList(
                             self.context), objects.Service(id=0, host='host2',
                             disabled=True, forced_down=False,
                             binary='nova-compute')))
            ]

        host_statuses = self.compute_api.get_instances_host_statuses(
                        instances)
        expect_statuses = {uuids.instance_1: fields_obj.HostStatus.DOWN,
                           uuids.instance_2: fields_obj.HostStatus.MAINTENANCE,
                           uuids.instance_3: fields_obj.HostStatus.UNKNOWN,
                           uuids.instance_4: fields_obj.HostStatus.UP,
                           uuids.instance_5: fields_obj.HostStatus.NONE,
                           uuids.instance_6: fields_obj.HostStatus.NONE,
                           uuids.instance_7: fields_obj.HostStatus.MAINTENANCE}
        for instance in instances:
            self.assertEqual(expect_statuses[instance.uuid],
                             host_statuses[instance.uuid])

    @mock.patch.object(objects.Migration, 'get_by_id_and_instance')
    @mock.patch.object(objects.InstanceAction, 'action_start')
    def test_live_migrate_force_complete_succeeded(
            self, action_start, get_by_id_and_instance):

        rpcapi = self.compute_api.compute_rpcapi

        instance = self._create_instance_obj()
        instance.task_state = task_states.MIGRATING

        migration = objects.Migration()
        migration.id = 0
        migration.status = 'running'
        get_by_id_and_instance.return_value = migration

        with mock.patch.object(
                rpcapi, 'live_migration_force_complete') as lm_force_complete:
            self.compute_api.live_migrate_force_complete(
                self.context, instance, migration)

            lm_force_complete.assert_called_once_with(self.context,
                                                      instance,
                                                      migration)
            action_start.assert_called_once_with(
                self.context, instance.uuid, 'live_migration_force_complete',
                want_result=False)

    @mock.patch.object(objects.Migration, 'get_by_id_and_instance')
    def test_live_migrate_force_complete_invalid_migration_state(
            self, get_by_id_and_instance):
        instance = self._create_instance_obj()
        instance.task_state = task_states.MIGRATING

        migration = objects.Migration()
        migration.id = 0
        migration.status = 'error'
        get_by_id_and_instance.return_value = migration

        self.assertRaises(exception.InvalidMigrationState,
                          self.compute_api.live_migrate_force_complete,
                          self.context, instance, migration.id)

    def test_live_migrate_force_complete_invalid_vm_state(self):
        instance = self._create_instance_obj()
        instance.task_state = None

        self.assertRaises(exception.InstanceInvalidState,
                          self.compute_api.live_migrate_force_complete,
                          self.context, instance, '1')

    def _get_migration(self, migration_id, status, migration_type):
        migration = objects.Migration()
        migration.id = migration_id
        migration.status = status
        migration.migration_type = migration_type
        return migration

    @mock.patch('nova.compute.api.API._record_action_start')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'live_migration_abort')
    @mock.patch.object(objects.Migration, 'get_by_id_and_instance')
    def test_live_migrate_abort_succeeded(self,
                                          mock_get_migration,
                                          mock_lm_abort,
                                          mock_rec_action):
        instance = self._create_instance_obj()
        instance.task_state = task_states.MIGRATING
        migration = self._get_migration(21, 'running', 'live-migration')
        mock_get_migration.return_value = migration

        self.compute_api.live_migrate_abort(self.context,
                                            instance,
                                            migration.id)
        mock_rec_action.assert_called_once_with(self.context,
                                    instance,
                                    instance_actions.LIVE_MIGRATION_CANCEL)
        mock_lm_abort.assert_called_once_with(self.context, instance,
                                              migration.id)

    @mock.patch('nova.compute.api.API._record_action_start')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'live_migration_abort')
    @mock.patch.object(objects.Migration, 'get_by_id_and_instance')
    def test_live_migrate_abort_in_queue_succeeded(self,
                                                   mock_get_migration,
                                                   mock_lm_abort,
                                                   mock_rec_action):
        instance = self._create_instance_obj()
        instance.task_state = task_states.MIGRATING
        for migration_status in ('queued', 'preparing'):
            migration = self._get_migration(
                21, migration_status, 'live-migration')
            mock_get_migration.return_value = migration
            self.compute_api.live_migrate_abort(self.context,
                                                instance,
                                                migration.id,
                                                support_abort_in_queue=True)
            mock_rec_action.assert_called_once_with(
                self.context, instance, instance_actions.LIVE_MIGRATION_CANCEL)
            mock_lm_abort.assert_called_once_with(self.context, instance,
                                                  migration.id)
            mock_get_migration.reset_mock()
            mock_rec_action.reset_mock()
            mock_lm_abort.reset_mock()

    @mock.patch.object(objects.Migration, 'get_by_id_and_instance')
    def test_live_migration_abort_in_queue_old_microversion_fails(
            self, mock_get_migration):
        instance = self._create_instance_obj()
        instance.task_state = task_states.MIGRATING
        migration = self._get_migration(21, 'queued', 'live-migration')
        mock_get_migration.return_value = migration
        self.assertRaises(exception.InvalidMigrationState,
                          self.compute_api.live_migrate_abort, self.context,
                          instance, migration.id,
                          support_abort_in_queue=False)

    @mock.patch.object(objects.Migration, 'get_by_id_and_instance')
    def test_live_migration_abort_wrong_migration_status(self,
                                                         mock_get_migration):
        instance = self._create_instance_obj()
        instance.task_state = task_states.MIGRATING
        migration = self._get_migration(21, 'completed', 'live-migration')
        mock_get_migration.return_value = migration

        self.assertRaises(exception.InvalidMigrationState,
                          self.compute_api.live_migrate_abort,
                          self.context,
                          instance,
                          migration.id)

    def test_check_requested_networks_no_requested_networks(self):
        # When there are no requested_networks we call validate_networks on
        # the network API and return the results.
        with mock.patch.object(self.compute_api.network_api,
                               'validate_networks', return_value=3):
            count = self.compute_api._check_requested_networks(
                self.context, None, 5)
        self.assertEqual(3, count)

    def test_check_requested_networks_no_allocate(self):
        # When requested_networks is the single 'none' case for no allocation,
        # we don't validate networks and return the count passed in.
        requested_networks = (
            objects.NetworkRequestList(
                objects=[objects.NetworkRequest(network_id='none')]))
        with mock.patch.object(self.compute_api.network_api,
                               'validate_networks') as validate:
            count = self.compute_api._check_requested_networks(
                self.context, requested_networks, 5)
        self.assertEqual(5, count)
        self.assertFalse(validate.called)

    def test_check_requested_networks_auto_allocate(self):
        # When requested_networks is the single 'auto' case for allocation,
        # we validate networks and return the results.
        requested_networks = (
            objects.NetworkRequestList(
                objects=[objects.NetworkRequest(network_id='auto')]))
        with mock.patch.object(self.compute_api.network_api,
                               'validate_networks', return_value=4):
            count = self.compute_api._check_requested_networks(
                self.context, requested_networks, 5)
        self.assertEqual(4, count)

    @mock.patch.object(objects.InstanceMapping, 'save')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    def test_update_queued_for_deletion(self, mock_get, mock_save):
        uuid = uuids.inst
        inst = objects.Instance(uuid=uuid)
        im = objects.InstanceMapping(instance_uuid=uuid)
        mock_get.return_value = im
        self.compute_api._update_queued_for_deletion(
            self.context, inst.uuid, True)
        self.assertTrue(im.queued_for_delete)
        mock_get.assert_called_once_with(self.context, inst.uuid)
        mock_save.assert_called_once_with()

    @mock.patch.object(objects.InstanceMappingList,
                       'get_not_deleted_by_cell_and_project')
    def test_generate_minimal_construct_for_down_cells(self, mock_get_ims):
        im1 = objects.InstanceMapping(instance_uuid=uuids.inst1, cell_id=1,
            project_id='fake', created_at=None, queued_for_delete=False)
        mock_get_ims.return_value = [im1]
        down_cell_uuids = [uuids.cell1, uuids.cell2, uuids.cell3]
        result = self.compute_api._generate_minimal_construct_for_down_cells(
            self.context, down_cell_uuids, [self.context.project_id], None)
        for inst in result:
            self.assertEqual(inst.uuid, im1.instance_uuid)
            self.assertIn('created_at', inst)
            # minimal construct doesn't contain the usual keys
            self.assertNotIn('display_name', inst)
        self.assertEqual(3, mock_get_ims.call_count)

    @mock.patch.object(objects.InstanceMappingList,
                       'get_not_deleted_by_cell_and_project')
    def test_generate_minimal_construct_for_down_cells_limited(self,
                                                               mock_get_ims):
        im1 = objects.InstanceMapping(instance_uuid=uuids.inst1, cell_id=1,
            project_id='fake', created_at=None, queued_for_delete=False)
        # If this gets called a third time, it'll explode, thus asserting
        # that we break out of the loop once the limit is reached
        mock_get_ims.side_effect = [[im1, im1], [im1]]
        down_cell_uuids = [uuids.cell1, uuids.cell2, uuids.cell3]
        result = self.compute_api._generate_minimal_construct_for_down_cells(
            self.context, down_cell_uuids, [self.context.project_id], 3)
        for inst in result:
            self.assertEqual(inst.uuid, im1.instance_uuid)
            self.assertIn('created_at', inst)
            # minimal construct doesn't contain the usual keys
            self.assertNotIn('display_name', inst)
        # Two instances at limit 3 from first cell, one at limit 1 from the
        # second, no third call.
        self.assertEqual(2, mock_get_ims.call_count)
        mock_get_ims.assert_has_calls([
            mock.call(self.context, uuids.cell1, [self.context.project_id],
                      limit=3),
            mock.call(self.context, uuids.cell2, [self.context.project_id],
                      limit=1),
        ])

    @mock.patch.object(objects.BuildRequestList, 'get_by_filters')
    @mock.patch.object(objects.InstanceMappingList,
                       'get_not_deleted_by_cell_and_project')
    def test_get_all_without_cell_down_support(self, mock_get_ims,
                                               mock_buildreq_get):
        mock_buildreq_get.return_value = objects.BuildRequestList()
        im1 = objects.InstanceMapping(instance_uuid=uuids.inst1, cell_id=1,
            project_id='fake', created_at=None, queued_for_delete=False)
        mock_get_ims.return_value = [im1]
        cell_instances = self._list_of_instances(2)
        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                self.context, objects=cell_instances), [uuids.cell1]
            insts = self.compute_api.get_all(self.context,
                cell_down_support=False)
            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(self.context, {}, None, None,
                fields, None, None, cell_down_support=False)
            for i, instance in enumerate(cell_instances):
                self.assertEqual(instance, insts[i])
            mock_get_ims.assert_not_called()

    @mock.patch.object(objects.BuildRequestList, 'get_by_filters')
    @mock.patch.object(objects.InstanceMappingList,
                       'get_not_deleted_by_cell_and_project')
    def test_get_all_with_cell_down_support(self, mock_get_ims,
                                            mock_buildreq_get):
        mock_buildreq_get.return_value = objects.BuildRequestList()
        im = objects.InstanceMapping(context=self.context,
            instance_uuid=uuids.inst1, cell_id=1,
            project_id='fake', created_at=None, queued_for_delete=False)
        mock_get_ims.return_value = [im]
        cell_instances = self._list_of_instances(2)
        full_instances = objects.InstanceList(self.context,
            objects=cell_instances)
        inst = objects.Instance(context=self.context, uuid=im.instance_uuid,
            project_id=im.project_id, created_at=im.created_at)
        partial_instances = objects.InstanceList(self.context, objects=[inst])
        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                self.context, objects=cell_instances), [uuids.cell1]
            insts = self.compute_api.get_all(self.context, limit=3,
                cell_down_support=True)
            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(self.context, {},
                                                  3, None, fields, None, None,
                                                  cell_down_support=True)
            for i, instance in enumerate(partial_instances + full_instances):
                self.assertTrue(obj_base.obj_equal_prims(instance, insts[i]))
            # With an original limit of 3, and 0 build requests but 2 instances
            # from "up" cells, we should only get at most 1 instance mapping
            # to fill the limit.
            mock_get_ims.assert_called_once_with(self.context, uuids.cell1,
                                                 self.context.project_id,
                                                 limit=1)

    @mock.patch.object(objects.BuildRequestList, 'get_by_filters')
    @mock.patch.object(objects.InstanceMappingList,
                       'get_not_deleted_by_cell_and_project')
    def test_get_all_with_cell_down_support_all_tenants(self, mock_get_ims,
                                                        mock_buildreq_get):
        mock_buildreq_get.return_value = objects.BuildRequestList()
        im = objects.InstanceMapping(context=self.context,
            instance_uuid=uuids.inst1, cell_id=1,
            project_id='fake', created_at=None, queued_for_delete=False)
        mock_get_ims.return_value = [im]
        inst = objects.Instance(context=self.context, uuid=im.instance_uuid,
            project_id=im.project_id, created_at=im.created_at)
        partial_instances = objects.InstanceList(self.context, objects=[inst])
        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                partial_instances), [uuids.cell1]
            insts = self.compute_api.get_all(self.context, limit=3,
                cell_down_support=True, all_tenants=True)
            for i, instance in enumerate(partial_instances):
                self.assertTrue(obj_base.obj_equal_prims(instance, insts[i]))
            # get_not_deleted_by_cell_and_project is called with None
            # project_id because of the all_tenants case.
            mock_get_ims.assert_called_once_with(self.context, uuids.cell1,
                                                 None,
                                                 limit=3)

    @mock.patch('nova.compute.api.API._save_user_id_in_instance_mapping',
                new=mock.MagicMock())
    @mock.patch.object(objects.Instance, 'get_by_uuid')
    def test_get_instance_from_cell_success(self, mock_get_inst):
        cell_mapping = objects.CellMapping(uuid=uuids.cell1,
                                           name='1', id=1)
        im = objects.InstanceMapping(instance_uuid=uuids.inst,
                                     cell_mapping=cell_mapping)
        mock_get_inst.return_value = objects.Instance(uuid=uuids.inst)
        result = self.compute_api._get_instance_from_cell(self.context,
            im, [], True)
        self.assertEqual(uuids.inst, result.uuid)
        mock_get_inst.assert_called_once()

    @mock.patch.object(objects.Instance, 'get_by_uuid')
    def test_get_instance_from_cell_failure(self, mock_get_inst):
        # Make sure InstanceNotFound is bubbled up and not treated like
        # other errors
        mock_get_inst.side_effect = exception.InstanceNotFound(
            instance_id=uuids.inst)
        cell_mapping = objects.CellMapping(uuid=uuids.cell1,
                                           name='1', id=1)
        im = objects.InstanceMapping(instance_uuid=uuids.inst,
                                     cell_mapping=cell_mapping)
        exp = self.assertRaises(exception.InstanceNotFound,
            self.compute_api._get_instance_from_cell, self.context,
            im, [], False)
        self.assertIn('could not be found', str(exp))

    @mock.patch('nova.compute.api.API._save_user_id_in_instance_mapping')
    @mock.patch.object(objects.RequestSpec, 'get_by_instance_uuid')
    @mock.patch('nova.context.scatter_gather_cells')
    def test_get_instance_with_cell_down_support(self, mock_sg, mock_rs,
                                                 mock_save_uid):
        cell_mapping = objects.CellMapping(uuid=uuids.cell1,
                                           name='1', id=1)
        im1 = objects.InstanceMapping(instance_uuid=uuids.inst1,
                                      cell_mapping=cell_mapping,
                                      queued_for_delete=True)
        im2 = objects.InstanceMapping(instance_uuid=uuids.inst2,
                                      cell_mapping=cell_mapping,
                                      queued_for_delete=False,
                                      project_id='fake',
                                      created_at=None)
        mock_sg.return_value = {
            uuids.cell1: context.did_not_respond_sentinel
        }

        # No cell down support, error means we return 500
        exp = self.assertRaises(exception.NovaException,
            self.compute_api._get_instance_from_cell, self.context,
            im1, [], False)
        self.assertIn('info is not available', str(exp))

        # Have cell down support, error + queued_for_delete = NotFound
        exp = self.assertRaises(exception.InstanceNotFound,
            self.compute_api._get_instance_from_cell, self.context,
            im1, [], True)
        self.assertIn('could not be found', str(exp))

        # Have cell down support, error + archived reqspec = NotFound
        mock_rs.side_effect = exception.RequestSpecNotFound(
            instance_uuid=uuids.inst2)
        exp = self.assertRaises(exception.InstanceNotFound,
            self.compute_api._get_instance_from_cell, self.context,
            im2, [], True)
        self.assertIn('could not be found', str(exp))

        # Have cell down support, error + reqspec + not queued_for_delete
        # means we return a minimal instance
        req_spec = objects.RequestSpec(instance_uuid=uuids.inst2,
                                       user_id='fake',
                                       flavor=objects.Flavor(name='fake1'),
                                       image=objects.ImageMeta(id=uuids.image,
                                                               name='fake1'),
                                       availability_zone='nova')
        mock_rs.return_value = req_spec
        mock_rs.side_effect = None
        result = self.compute_api._get_instance_from_cell(self.context,
            im2, [], True)
        self.assertIn('user_id', result)
        self.assertNotIn('display_name', result)
        self.assertEqual(uuids.inst2, result.uuid)
        self.assertEqual('nova', result.availability_zone)
        self.assertEqual(uuids.image, result.image_ref)
        # Verify that user_id is populated during a compute_api.get().
        mock_save_uid.assert_called_once_with(im2, result)

        # Same as above, but boot-from-volume where image is not None but the
        # id of the image is not set.
        req_spec.image = objects.ImageMeta(name='fake1')
        result = self.compute_api._get_instance_from_cell(self.context,
            im2, [], True)
        self.assertIsNone(result.image_ref)

        # Same as above, but boot-from-volume where image is None
        req_spec.image = None
        result = self.compute_api._get_instance_from_cell(self.context,
            im2, [], True)
        self.assertIsNone(result.image_ref)

    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid',
            side_effect=exception.InstanceMappingNotFound(uuid='fake'))
    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'get_by_uuid')
    def test_get_instance_no_mapping(self, mock_get_inst, mock_get_build_req,
            mock_get_inst_map):

        self.useFixture(nova_fixtures.AllServicesCurrent())
        # No Mapping means NotFound
        self.assertRaises(exception.InstanceNotFound,
                          self.compute_api.get, self.context,
                          uuids.inst_uuid)

    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'get_by_uuid')
    def test_get_instance_not_in_cell(self, mock_get_inst, mock_get_build_req,
                mock_get_inst_map):
        build_req_obj = fake_build_request.fake_req_obj(self.context)
        mock_get_inst_map.return_value = objects.InstanceMapping(
                cell_mapping=None)
        mock_get_build_req.return_value = build_req_obj
        instance = build_req_obj.instance
        mock_get_inst.return_value = instance

        inst_from_build_req = self.compute_api.get(self.context, instance.uuid)
        mock_get_inst_map.assert_called_once_with(self.context,
                                                  instance.uuid)
        mock_get_build_req.assert_called_once_with(self.context,
                                                   instance.uuid)
        self.assertEqual(instance, inst_from_build_req)

    @mock.patch('nova.compute.api.API._save_user_id_in_instance_mapping',
                new=mock.MagicMock())
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'get_by_uuid')
    def test_get_instance_not_in_cell_buildreq_deleted_inst_in_cell(
            self, mock_get_inst, mock_get_build_req, mock_get_inst_map):
        # This test checks the following scenario:
        # The instance is not mapped to a cell, so it should be retrieved from
        # a BuildRequest object. However the BuildRequest does not exist
        # because the instance was put in a cell and mapped while while
        # attempting to get the BuildRequest. So pull the instance from the
        # cell.
        self.useFixture(nova_fixtures.AllServicesCurrent())
        build_req_obj = fake_build_request.fake_req_obj(self.context)
        instance = build_req_obj.instance
        inst_map = objects.InstanceMapping(cell_mapping=objects.CellMapping(
            uuid=uuids.cell), instance_uuid=instance.uuid)

        mock_get_inst_map.side_effect = [
            objects.InstanceMapping(cell_mapping=None), inst_map]
        mock_get_build_req.side_effect = exception.BuildRequestNotFound(
            uuid=instance.uuid)
        mock_get_inst.return_value = instance

        inst_from_get = self.compute_api.get(self.context, instance.uuid)

        inst_map_calls = [mock.call(self.context, instance.uuid),
                          mock.call(self.context, instance.uuid)]
        mock_get_inst_map.assert_has_calls(inst_map_calls)
        self.assertEqual(2, mock_get_inst_map.call_count)
        mock_get_build_req.assert_called_once_with(self.context,
                                                   instance.uuid)

        mock_get_inst.assert_called_once_with(self.context, instance.uuid,
                                              expected_attrs=[
                                                  'metadata',
                                                  'system_metadata',
                                                  'security_groups',
                                                  'info_cache'])
        self.assertEqual(instance, inst_from_get)

    @mock.patch.object(context, 'target_cell')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'get_by_uuid')
    def test_get_instance_not_in_cell_buildreq_deleted_inst_still_not_in_cell(
            self, mock_get_inst, mock_get_build_req, mock_get_inst_map,
            mock_target_cell):
        # This test checks the following scenario:
        # The instance is not mapped to a cell, so it should be retrieved from
        # a BuildRequest object. However the BuildRequest does not exist which
        # means it should now be possible to find the instance in a cell db.
        # But the instance is not mapped which means the cellsv2 migration has
        # not occurred in this scenario, so the instance is pulled from the
        # configured Nova db.

        # TODO(alaski): The tested case will eventually be an error condition.
        # But until we force cellsv2 migrations we need this to work.
        self.useFixture(nova_fixtures.AllServicesCurrent())
        build_req_obj = fake_build_request.fake_req_obj(self.context)
        instance = build_req_obj.instance

        mock_get_inst_map.side_effect = [
            objects.InstanceMapping(cell_mapping=None),
            objects.InstanceMapping(cell_mapping=None)]
        mock_get_build_req.side_effect = exception.BuildRequestNotFound(
            uuid=instance.uuid)
        mock_get_inst.return_value = instance

        self.assertRaises(exception.InstanceNotFound,
                          self.compute_api.get,
                          self.context, instance.uuid)

    @mock.patch('nova.objects.InstanceMapping.save')
    def test_save_user_id_in_instance_mapping(self, im_save):
        # Verify user_id is populated if it not set
        im = objects.InstanceMapping()
        i = objects.Instance(user_id='fake')
        self.compute_api._save_user_id_in_instance_mapping(im, i)
        self.assertEqual(im.user_id, i.user_id)
        im_save.assert_called_once_with()
        # Verify user_id is not saved if it is already set
        im_save.reset_mock()
        im.user_id = 'fake-other'
        self.compute_api._save_user_id_in_instance_mapping(im, i)
        self.assertNotEqual(im.user_id, i.user_id)
        im_save.assert_not_called()
        # Verify user_id is not saved if it is None
        im_save.reset_mock()
        im = objects.InstanceMapping()
        i = objects.Instance(user_id=None)
        self.compute_api._save_user_id_in_instance_mapping(im, i)
        self.assertNotIn('user_id', im)
        im_save.assert_not_called()

    @mock.patch('nova.compute.api.API._save_user_id_in_instance_mapping')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    @mock.patch.object(objects.Instance, 'get_by_uuid')
    def test_get_instance_in_cell(self, mock_get_inst, mock_get_build_req,
            mock_get_inst_map, mock_save_uid):
        self.useFixture(nova_fixtures.AllServicesCurrent())
        # This just checks that the instance is looked up normally and not
        # synthesized from a BuildRequest object. Verification of pulling the
        # instance from the proper cell will be added when that capability is.
        instance = self._create_instance_obj()
        build_req_obj = fake_build_request.fake_req_obj(self.context)
        inst_map = objects.InstanceMapping(cell_mapping=objects.CellMapping(
            uuid=uuids.cell), instance_uuid=instance.uuid)
        mock_get_inst_map.return_value = inst_map
        mock_get_build_req.return_value = build_req_obj
        mock_get_inst.return_value = instance

        returned_inst = self.compute_api.get(self.context, instance.uuid)
        mock_get_build_req.assert_not_called()
        mock_get_inst_map.assert_called_once_with(self.context,
                                                  instance.uuid)
        # Verify that user_id is populated during a compute_api.get().
        mock_save_uid.assert_called_once_with(inst_map, instance)
        self.assertEqual(instance, returned_inst)
        mock_get_inst.assert_called_once_with(self.context, instance.uuid,
                                              expected_attrs=[
                                                  'metadata',
                                                  'system_metadata',
                                                  'security_groups',
                                                  'info_cache'])

    def _list_of_instances(self, length=1):
        instances = []
        for i in range(length):
            instances.append(
                fake_instance.fake_instance_obj(self.context, objects.Instance,
                                                uuid=uuidutils.generate_uuid())
            )
        return instances

    @mock.patch.object(objects.BuildRequestList, 'get_by_filters')
    @mock.patch.object(objects.CellMapping, 'get_by_uuid',
                       side_effect=exception.CellMappingNotFound(uuid='fake'))
    def test_get_all_includes_build_requests(self, mock_cell_mapping_get,
                                             mock_buildreq_get):

        build_req_instances = self._list_of_instances(2)
        build_reqs = [objects.BuildRequest(self.context, instance=instance)
                      for instance in build_req_instances]
        mock_buildreq_get.return_value = objects.BuildRequestList(self.context,
            objects=build_reqs)

        cell_instances = self._list_of_instances(2)

        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                self.context, objects=cell_instances), list()

            instances = self.compute_api.get_all(
                self.context, search_opts={'foo': 'bar'},
                limit=None, marker='fake-marker', sort_keys=['baz'],
                sort_dirs=['desc'])

            mock_buildreq_get.assert_called_once_with(
                self.context, {'foo': 'bar'}, limit=None, marker='fake-marker',
                sort_keys=['baz'], sort_dirs=['desc'])
            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(
                self.context, {'foo': 'bar'}, None, None,
                fields, ['baz'], ['desc'], cell_down_support=False)
            for i, instance in enumerate(build_req_instances + cell_instances):
                self.assertEqual(instance, instances[i])

    @mock.patch.object(objects.BuildRequestList, 'get_by_filters')
    @mock.patch.object(objects.CellMapping, 'get_by_uuid',
                       side_effect=exception.CellMappingNotFound(uuid='fake'))
    def test_get_all_includes_build_requests_filter_dupes(self,
            mock_cell_mapping_get, mock_buildreq_get):

        build_req_instances = self._list_of_instances(2)
        build_reqs = [objects.BuildRequest(self.context, instance=instance)
                      for instance in build_req_instances]
        mock_buildreq_get.return_value = objects.BuildRequestList(self.context,
            objects=build_reqs)

        cell_instances = self._list_of_instances(2)

        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            # Insert one of the build_req_instances here so it shows up twice
            mock_inst_get.return_value = objects.InstanceList(self.context,
                objects=build_req_instances[:1] + cell_instances), list()

            instances = self.compute_api.get_all(
                self.context, search_opts={'foo': 'bar'},
                limit=None, marker='fake-marker', sort_keys=['baz'],
                sort_dirs=['desc'])

            mock_buildreq_get.assert_called_once_with(
                self.context, {'foo': 'bar'}, limit=None, marker='fake-marker',
                sort_keys=['baz'], sort_dirs=['desc'])
            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(
                self.context, {'foo': 'bar'}, None, None,
                fields, ['baz'], ['desc'], cell_down_support=False)
            for i, instance in enumerate(build_req_instances + cell_instances):
                self.assertEqual(instance, instances[i])

    @mock.patch.object(objects.BuildRequestList, 'get_by_filters')
    @mock.patch.object(objects.CellMapping, 'get_by_uuid',
                       side_effect=exception.CellMappingNotFound(uuid='fake'))
    def test_get_all_build_requests_decrement_limit(self,
                                                    mock_cell_mapping_get,
                                                    mock_buildreq_get):

        build_req_instances = self._list_of_instances(2)
        build_reqs = [objects.BuildRequest(self.context, instance=instance)
                      for instance in build_req_instances]
        mock_buildreq_get.return_value = objects.BuildRequestList(self.context,
            objects=build_reqs)

        cell_instances = self._list_of_instances(2)

        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                self.context, objects=cell_instances), list()

            instances = self.compute_api.get_all(
                self.context, search_opts={'foo': 'bar'},
                limit=10, marker='fake-marker', sort_keys=['baz'],
                sort_dirs=['desc'])

            mock_buildreq_get.assert_called_once_with(
                self.context, {'foo': 'bar'}, limit=10, marker='fake-marker',
                sort_keys=['baz'], sort_dirs=['desc'])
            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(
                self.context, {'foo': 'bar'}, 8, None,
                fields, ['baz'], ['desc'], cell_down_support=False)
            for i, instance in enumerate(build_req_instances + cell_instances):
                self.assertEqual(instance, instances[i])

    @mock.patch.object(context, 'target_cell')
    @mock.patch.object(objects.BuildRequestList, 'get_by_filters')
    @mock.patch.object(objects.CellMapping, 'get_by_uuid')
    @mock.patch.object(objects.CellMappingList, 'get_all')
    def test_get_all_includes_build_request_cell0(self, mock_cm_get_all,
                                    mock_cell_mapping_get,
                                    mock_buildreq_get, mock_target_cell):

        build_req_instances = self._list_of_instances(2)
        build_reqs = [objects.BuildRequest(self.context, instance=instance)
                      for instance in build_req_instances]
        mock_buildreq_get.return_value = objects.BuildRequestList(self.context,
            objects=build_reqs)

        cell_instances = self._list_of_instances(2)

        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                                             self.context,
                                             objects=cell_instances), []

            instances = self.compute_api.get_all(
                self.context, search_opts={'foo': 'bar'},
                limit=10, marker='fake-marker', sort_keys=['baz'],
                sort_dirs=['desc'])

            for cm in mock_cm_get_all.return_value:
                mock_target_cell.assert_any_call(self.context, cm)

            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(
                mock.ANY, {'foo': 'bar'},
                8, None,
                fields, ['baz'], ['desc'], cell_down_support=False)
            for i, instance in enumerate(build_req_instances +
                                         cell_instances):
                self.assertEqual(instance, instances[i])

    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    def test_update_existing_instance_not_in_cell(self, mock_instmap_get,
                                                  mock_buildreq_get):
        mock_instmap_get.side_effect = exception.InstanceMappingNotFound(
            uuid='fake')
        self.useFixture(nova_fixtures.AllServicesCurrent())

        instance = self._create_instance_obj()
        # Just making sure that the instance has been created
        self.assertIsNotNone(instance.id)
        updates = {'display_name': 'foo_updated'}
        with mock.patch.object(instance, 'save') as mock_inst_save:
            returned_instance = self.compute_api.update_instance(
                self.context, instance, updates)
        mock_buildreq_get.assert_not_called()
        self.assertEqual('foo_updated', returned_instance.display_name)
        mock_inst_save.assert_called_once_with()

    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    def test_update_existing_instance_in_cell(self, mock_instmap_get,
                                              mock_buildreq_get):
        inst_map = objects.InstanceMapping(cell_mapping=objects.CellMapping())
        mock_instmap_get.return_value = inst_map
        self.useFixture(nova_fixtures.AllServicesCurrent())

        instance = self._create_instance_obj()
        # Just making sure that the instance has been created
        self.assertIsNotNone(instance.id)
        updates = {'display_name': 'foo_updated'}
        with mock.patch.object(instance, 'save') as mock_inst_save:
            returned_instance = self.compute_api.update_instance(
                self.context, instance, updates)
        mock_buildreq_get.assert_not_called()
        self.assertEqual('foo_updated', returned_instance.display_name)
        mock_inst_save.assert_called_once_with()

    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    def test_update_future_instance_with_buildreq(self, mock_buildreq_get):

        # This test checks that a new instance which is not yet peristed in
        # DB can be found by looking up the BuildRequest object so we can
        # update it.

        build_req_obj = fake_build_request.fake_req_obj(self.context)
        mock_buildreq_get.return_value = build_req_obj
        self.useFixture(nova_fixtures.AllServicesCurrent())

        instance = self._create_instance_obj()
        # Fake the fact that the instance is not yet persisted in DB
        del instance.id

        updates = {'display_name': 'foo_updated'}
        with mock.patch.object(build_req_obj, 'save') as mock_buildreq_save:
            returned_instance = self.compute_api.update_instance(
                self.context, instance, updates)

        mock_buildreq_get.assert_called_once_with(self.context, instance.uuid)
        self.assertEqual(build_req_obj.instance, returned_instance)
        mock_buildreq_save.assert_called_once_with()
        self.assertEqual('foo_updated', returned_instance.display_name)

    @mock.patch.object(context, 'target_cell')
    @mock.patch.object(objects.Instance, 'get_by_uuid')
    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    def test_update_instance_in_cell_in_transition_state(self,
                                                         mock_buildreq_get,
                                                         mock_instmap_get,
                                                         mock_inst_get,
                                                         mock_target_cell):

        # This test is for covering the following case:
        #  - when we lookup the instance initially, that one is not yet mapped
        #    to a cell and consequently we retrieve it from the BuildRequest
        #  - when we update the instance, that one could have been mapped
        #    meanwhile and the BuildRequest was deleted
        #  - if the instance is mapped, lookup the cell DB to find the instance

        self.useFixture(nova_fixtures.AllServicesCurrent())

        instance = self._create_instance_obj()
        # Fake the fact that the instance is not yet persisted in DB
        del instance.id

        mock_buildreq_get.side_effect = exception.BuildRequestNotFound(
            uuid=instance.uuid)
        inst_map = objects.InstanceMapping(cell_mapping=objects.CellMapping())
        mock_instmap_get.return_value = inst_map
        mock_inst_get.return_value = instance

        updates = {'display_name': 'foo_updated'}
        with mock.patch.object(instance, 'save') as mock_inst_save:
            returned_instance = self.compute_api.update_instance(
                self.context, instance, updates)

        mock_buildreq_get.assert_called_once_with(self.context, instance.uuid)
        mock_target_cell.assert_called_once_with(self.context,
                                                 inst_map.cell_mapping)
        mock_inst_save.assert_called_once_with()
        self.assertEqual('foo_updated', returned_instance.display_name)

    @mock.patch.object(objects.InstanceMapping, 'get_by_instance_uuid')
    @mock.patch.object(objects.BuildRequest, 'get_by_instance_uuid')
    def test_update_instance_not_in_cell_in_transition_state(self,
                                                             mock_buildreq_get,
                                                             mock_instmap_get):

        # This test is for covering the following case:
        #  - when we lookup the instance initially, that one is not yet mapped
        #    to a cell and consequently we retrieve it from the BuildRequest
        #  - when we update the instance, that one could have been mapped
        #    meanwhile and the BuildRequest was deleted
        #  - if the instance is not mapped, lookup the API DB to find whether
        #    the instance was deleted

        self.useFixture(nova_fixtures.AllServicesCurrent())

        instance = self._create_instance_obj()
        # Fake the fact that the instance is not yet persisted in DB
        del instance.id

        mock_buildreq_get.side_effect = exception.BuildRequestNotFound(
            uuid=instance.uuid)
        mock_instmap_get.side_effect = exception.InstanceMappingNotFound(
            uuid='fake')

        updates = {'display_name': 'foo_updated'}
        with mock.patch.object(instance, 'save') as mock_inst_save:
            self.assertRaises(exception.InstanceNotFound,
                              self.compute_api.update_instance,
                              self.context, instance, updates)

        mock_buildreq_get.assert_called_once_with(self.context, instance.uuid)
        mock_inst_save.assert_not_called()

    def test_populate_instance_for_create_neutron_secgroups(self):
        """Tests that a list of security groups passed in do not actually get
        stored on with the instance when using neutron.
        """
        flavor = self._create_flavor()
        params = {'display_name': 'fake-instance'}
        instance = self._create_instance_obj(params, flavor)
        security_groups = objects.SecurityGroupList()
        security_groups.objects = [
            secgroup_obj.SecurityGroup(uuid=uuids.secgroup_id)
        ]
        instance = self.compute_api._populate_instance_for_create(
            self.context, instance, {}, 0, security_groups, flavor, 1,
            False)
        self.assertEqual(0, len(instance.security_groups))

    def test_retrieve_trusted_certs_object(self):
        ids = ['0b5d2c72-12cc-4ba6-a8d7-3ff5cc1d8cb8',
               '674736e3-f25c-405c-8362-bbf991e0ce0a']

        retrieved_certs = self.compute_api._retrieve_trusted_certs_object(
            self.context, ids)
        self.assertEqual(ids, retrieved_certs.ids)

    def test_retrieve_trusted_certs_object_conf(self):
        ids = ['conf-trusted-cert-1', 'conf-trusted-cert-2']

        self.flags(verify_glance_signatures=True, group='glance')
        self.flags(enable_certificate_validation=True, group='glance')
        self.flags(default_trusted_certificate_ids='conf-trusted-cert-1, '
                                                   'conf-trusted-cert-2',
                   group='glance')
        retrieved_certs = self.compute_api._retrieve_trusted_certs_object(
            self.context, None)
        self.assertEqual(ids, retrieved_certs.ids)

    def test_retrieve_trusted_certs_object_none(self):
        self.flags(enable_certificate_validation=False, group='glance')
        self.assertIsNone(
            self.compute_api._retrieve_trusted_certs_object(self.context,
                None))

    def test_retrieve_trusted_certs_object_empty(self):
        self.flags(enable_certificate_validation=False, group='glance')
        self.assertIsNone(self.compute_api._retrieve_trusted_certs_object(
            self.context, []))

    @mock.patch('nova.objects.HostMapping.get_by_host')
    @mock.patch('nova.objects.ComputeNode.get_by_host_and_nodename')
    @mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
                'get_provider_by_name')
    def test__validate_host_or_node_with_host(
            self, mock_get_provider_by_name, mock_get_host_node, mock_get_hm):
        host = 'fake-host'
        node = None

        self.compute_api._validate_host_or_node(self.context, host, node)
        mock_get_hm.assert_called_once_with(self.context, 'fake-host')
        mock_get_host_node.assert_not_called()
        mock_get_provider_by_name.assert_not_called()

    @mock.patch('nova.objects.HostMapping.get_by_host')
    @mock.patch('nova.objects.ComputeNode.get_by_host_and_nodename')
    @mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
                'get_provider_by_name')
    def test__validate_host_or_node_with_invalid_host(
            self, mock_get_provider_by_name, mock_get_host_node, mock_get_hm):
        host = 'fake-host'
        node = None

        mock_get_hm.side_effect = exception.HostMappingNotFound(name=host)
        self.assertRaises(exception.ComputeHostNotFound,
                          self.compute_api._validate_host_or_node,
                          self.context, host, node)
        mock_get_hm.assert_called_once_with(self.context, 'fake-host')
        mock_get_host_node.assert_not_called()
        mock_get_provider_by_name.assert_not_called()

    @mock.patch('nova.context.target_cell')
    @mock.patch('nova.objects.HostMapping.get_by_host')
    @mock.patch('nova.objects.ComputeNode.get_by_host_and_nodename')
    @mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
                'get_provider_by_name')
    def test__validate_host_or_node_with_host_and_node(
            self, mock_get_provider_by_name, mock_get_host_node, mock_get_hm,
            mock_target_cell):
        host = 'fake-host'
        node = 'fake-host'

        self.compute_api._validate_host_or_node(self.context, host, node)
        mock_get_host_node.assert_called_once_with(
            mock_target_cell.return_value.__enter__.return_value,
            'fake-host', 'fake-host')
        mock_get_hm.assert_called_once_with(self.context, 'fake-host')
        mock_get_provider_by_name.assert_not_called()

    @mock.patch('nova.context.target_cell')
    @mock.patch('nova.objects.HostMapping.get_by_host')
    @mock.patch('nova.objects.ComputeNode.get_by_host_and_nodename')
    @mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
                'get_provider_by_name')
    def test__validate_host_or_node_with_invalid_host_and_node(
            self, mock_get_provider_by_name, mock_get_host_node, mock_get_hm,
            mock_target_cell):
        host = 'fake-host'
        node = 'fake-host'

        mock_get_host_node.side_effect = (
            exception.ComputeHostNotFound(host=host))
        self.assertRaises(exception.ComputeHostNotFound,
                          self.compute_api._validate_host_or_node,
                          self.context, host, node)
        mock_get_host_node.assert_called_once_with(
            mock_target_cell.return_value.__enter__.return_value,
            'fake-host', 'fake-host')
        mock_get_hm.assert_called_once_with(self.context, 'fake-host')
        mock_get_provider_by_name.assert_not_called()

    @mock.patch('nova.objects.HostMapping.get_by_host')
    @mock.patch('nova.objects.ComputeNode.get_by_host_and_nodename')
    @mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
                'get_provider_by_name')
    def test__validate_host_or_node_with_node(
            self, mock_get_provider_by_name, mock_get_host_node, mock_get_hm):
        host = None
        node = 'fake-host'

        self.compute_api._validate_host_or_node(self.context, host, node)
        mock_get_provider_by_name.assert_called_once_with(
            self.context, 'fake-host')
        mock_get_host_node.assert_not_called()
        mock_get_hm.assert_not_called()

    @mock.patch('nova.objects.HostMapping.get_by_host')
    @mock.patch('nova.objects.ComputeNode.get_by_host_and_nodename')
    @mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
                'get_provider_by_name')
    def test__validate_host_or_node_with_invalid_node(
            self, mock_get_provider_by_name, mock_get_host_node, mock_get_hm):
        host = None
        node = 'fake-host'

        mock_get_provider_by_name.side_effect = (
            exception.ResourceProviderNotFound(name_or_uuid=node))
        self.assertRaises(exception.ComputeHostNotFound,
                          self.compute_api._validate_host_or_node,
                          self.context, host, node)
        mock_get_provider_by_name.assert_called_once_with(
            self.context, 'fake-host')
        mock_get_host_node.assert_not_called()
        mock_get_hm.assert_not_called()

    @mock.patch('nova.objects.HostMapping.get_by_host')
    @mock.patch('nova.objects.ComputeNode.get_by_host_and_nodename')
    @mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
                'get_provider_by_name')
    def test__validate_host_or_node_with_rp_500_exception(
            self, mock_get_provider_by_name, mock_get_host_node, mock_get_hm):
        host = None
        node = 'fake-host'

        mock_get_provider_by_name.side_effect = (
            exception.PlacementAPIConnectFailure())
        self.assertRaises(exception.PlacementAPIConnectFailure,
                          self.compute_api._validate_host_or_node,
                          self.context, host, node)
        mock_get_provider_by_name.assert_called_once_with(
            self.context, 'fake-host')
        mock_get_host_node.assert_not_called()
        mock_get_hm.assert_not_called()


# TODO(stephenfin): The separation of the mixin is a hangover from cells v1
# days and should be removed
class ComputeAPIUnitTestCase(_ComputeAPIUnitTestMixIn, test.NoDBTestCase):
    def setUp(self):
        super(ComputeAPIUnitTestCase, self).setUp()
        self.compute_api = compute_api.API()

    def test_resize_same_flavor_fails(self):
        self.assertRaises(exception.CannotResizeToSameFlavor,
                          self._test_resize, same_flavor=True)

    def test_find_service_in_cell_error_case(self):
        self.assertRaises(exception.NovaException,
                          compute_api._find_service_in_cell, self.context)

    @mock.patch('nova.objects.Service.get_by_id')
    def test_find_service_in_cell_targets(self, mock_get_service):
        mock_get_service.side_effect = [exception.NotFound(),
                                        mock.sentinel.service]
        compute_api.CELLS = [mock.sentinel.cell0, mock.sentinel.cell1]

        @contextlib.contextmanager
        def fake_target(context, cell):
            yield 'context-for-%s' % cell

        with mock.patch('nova.context.target_cell') as mock_target:
            mock_target.side_effect = fake_target
            s = compute_api._find_service_in_cell(self.context, service_id=123)
            self.assertEqual(mock.sentinel.service, s)
            cells = [call[0][0]
                     for call in mock_get_service.call_args_list]
            self.assertEqual(['context-for-%s' % c for c in compute_api.CELLS],
                             cells)

    def test__validate_numa_rebuild_non_numa(self):
        """Assert that a rebuild of an instance without a NUMA
        topology passes validation.
        """
        flavor = objects.Flavor(
            id=42, vcpus=1, memory_mb=512, root_gb=1, extra_specs={})
        instance = self._create_instance_obj(flavor=flavor)
        # we use a dict instead of image metadata object as
        # _validate_numa_rebuild constructs the object internally
        image = {
            'id': uuids.image_id, 'status': 'foo',
            'properties': {}}
        self.compute_api._validate_numa_rebuild(instance, image, flavor)

    def test__validate_numa_rebuild_no_conflict(self):
        """Assert that a rebuild of an instance without a change
        in NUMA topology passes validation.
        """
        flavor = objects.Flavor(
            id=42, vcpus=1, memory_mb=512, root_gb=1,
            extra_specs={"hw:numa_nodes": 1})
        instance = self._create_instance_obj(flavor=flavor)
        # we use a dict instead of image metadata object as
        # _validate_numa_rebuild constructs the object internally
        image = {
            'id': uuids.image_id, 'status': 'foo',
            'properties': {}}
        # The flavor creates a NUMA topology but the default image and the
        # rebuild image do not have any image properties so there will
        # be no conflict.
        self.compute_api._validate_numa_rebuild(instance, image, flavor)

    def test__validate_numa_rebuild_add_numa_toplogy(self):
        """Assert that a rebuild of an instance with a new image
        that requests a NUMA topology when the original instance did not
        have a NUMA topology is invalid.
        """

        flavor = objects.Flavor(
            id=42, vcpus=1, memory_mb=512, root_gb=1,
            extra_specs={})
        # _create_instance_obj results in the instance.image_meta being None.
        instance = self._create_instance_obj(flavor=flavor)
        # we use a dict instead of image metadata object as
        # _validate_numa_rebuild constructs the object internally
        image = {
            'id': uuids.image_id, 'status': 'foo',
            'properties': {"hw_numa_nodes": 1}}
        # The flavor and default image have no NUMA topology defined. The image
        # used to rebuild requests a NUMA topology which is not allowed as it
        # would alter the NUMA constrains.
        self.assertRaises(
            exception.ImageNUMATopologyRebuildConflict,
            self.compute_api._validate_numa_rebuild, instance, image, flavor)

    def test__validate_numa_rebuild_remove_numa_toplogy(self):
        """Assert that a rebuild of an instance with a new image
        that does not request a NUMA topology when the original image did
        is invalid if it would alter the instances topology as a result.
        """

        flavor = objects.Flavor(
            id=42, vcpus=1, memory_mb=512, root_gb=1,
            extra_specs={})
        # _create_instance_obj results in the instance.image_meta being None.
        instance = self._create_instance_obj(flavor=flavor)
        # we use a dict instead of image metadata object as
        # _validate_numa_rebuild constructs the object internally
        old_image = {
            'id': uuidutils.generate_uuid(), 'status': 'foo',
            'properties': {"hw_numa_nodes": 1}}
        old_image_meta = objects.ImageMeta.from_dict(old_image)
        image = {
            'id': uuidutils.generate_uuid(), 'status': 'foo',
            'properties': {}}
        with mock.patch(
                'nova.objects.instance.Instance.image_meta',
                new_callable=mock.PropertyMock(return_value=old_image_meta)):
            # The old image has a NUMA topology defined but the new image
            # used to rebuild does not. This would alter the NUMA constrains
            # and therefor should raise.
            self.assertRaises(
                exception.ImageNUMATopologyRebuildConflict,
                self.compute_api._validate_numa_rebuild, instance,
                image, flavor)

    def test__validate_numa_rebuild_alter_numa_toplogy(self):
        """Assert that a rebuild of an instance with a new image
        that requests a different NUMA topology than the original image
        is invalid.
        """

        # NOTE(sean-k-mooney): we need to use 2 vcpus here or we will fail
        # with a different exception ImageNUMATopologyAsymmetric when we
        # construct the NUMA constrains as the rebuild image would result
        # in an invalid topology.
        flavor = objects.Flavor(
            id=42, vcpus=2, memory_mb=512, root_gb=1,
            extra_specs={})
        # _create_instance_obj results in the instance.image_meta being None.
        instance = self._create_instance_obj(flavor=flavor)
        # we use a dict instead of image metadata object as
        # _validate_numa_rebuild constructs the object internally
        old_image = {
            'id': uuidutils.generate_uuid(), 'status': 'foo',
            'properties': {"hw_numa_nodes": 1}}
        old_image_meta = objects.ImageMeta.from_dict(old_image)
        image = {
            'id': uuidutils.generate_uuid(), 'status': 'foo',
            'properties': {"hw_numa_nodes": 2}}
        with mock.patch(
                'nova.objects.instance.Instance.image_meta',
                new_callable=mock.PropertyMock(return_value=old_image_meta)):
            # the original image requested 1 NUMA node and the image used
            # for rebuild requests 2 so assert an error is raised.
            self.assertRaises(
                exception.ImageNUMATopologyRebuildConflict,
                self.compute_api._validate_numa_rebuild, instance,
                image, flavor)

    @mock.patch('nova.pci.request.get_pci_requests_from_flavor')
    def test_pmu_image_and_flavor_conflict(self, mock_request):
        """Tests that calling _validate_flavor_image_nostatus()
        with an image that conflicts with the flavor raises but no
        exception is raised if there is no conflict.
        """
        image = {'id': uuids.image_id, 'status': 'foo',
                 'properties': {'hw_pmu': False}}
        flavor = objects.Flavor(
            vcpus=1, memory_mb=512, root_gb=1, extra_specs={'hw:pmu': "true"})
        self.assertRaises(
            exception.ImagePMUConflict,
            self.compute_api._validate_flavor_image_nostatus,
            self.context, image, flavor, None)

    @mock.patch('nova.pci.request.get_pci_requests_from_flavor')
    def test_pmu_image_and_flavor_same_value(self, mock_request):
        # assert that if both the image and flavor are set to the same value
        # no exception is raised and the function returns nothing.
        flavor = objects.Flavor(
            vcpus=1, memory_mb=512, root_gb=1, extra_specs={'hw:pmu': "true"})

        image = {'id': uuids.image_id, 'status': 'foo',
                 'properties': {'hw_pmu': True}}
        self.assertIsNone(self.compute_api._validate_flavor_image_nostatus(
            self.context, image, flavor, None))

    @mock.patch('nova.pci.request.get_pci_requests_from_flavor')
    def test_pmu_image_only(self, mock_request):
        # assert that if only the image metadata is set then it is valid
        flavor = objects.Flavor(
            vcpus=1, memory_mb=512, root_gb=1, extra_specs={})

        # ensure string to bool conversion works for image metadata
        # property by using "yes".
        image = {'id': uuids.image_id, 'status': 'foo',
                 'properties': {'hw_pmu': "yes"}}
        self.assertIsNone(self.compute_api._validate_flavor_image_nostatus(
            self.context, image, flavor, None))

    @mock.patch('nova.pci.request.get_pci_requests_from_flavor')
    def test_pmu_flavor_only(self, mock_request):
        # assert that if only the flavor extra_spec is set then it is valid
        # and test the string to bool conversion of "on" works.
        flavor = objects.Flavor(
            vcpus=1, memory_mb=512, root_gb=1, extra_specs={'hw:pmu': "on"})

        image = {'id': uuids.image_id, 'status': 'foo', 'properties': {}}
        self.assertIsNone(self.compute_api._validate_flavor_image_nostatus(
            self.context, image, flavor, None))

    @mock.patch('nova.pci.request.get_pci_requests_from_flavor')
    def test_pci_validated(self, mock_request):
        """Tests that calling _validate_flavor_image_nostatus() with
        validate_pci=True results in get_pci_requests_from_flavor() being
        called.
        """
        image = {'id': uuids.image_id, 'status': 'foo'}
        flavor = self._create_flavor()
        self.compute_api._validate_flavor_image_nostatus(
            self.context, image, flavor, root_bdm=None, validate_pci=True)
        mock_request.assert_called_once_with(flavor)

    def test_validate_and_build_base_options_translate_neutron_secgroup(self):
        """Tests that _check_requested_secgroups will return a uuid for a
        requested Neutron security group and that will be returned from
        _validate_and_build_base_options
        """
        instance_type = objects.Flavor(**test_flavor.fake_flavor)
        boot_meta = metadata = {}
        kernel_id = ramdisk_id = key_name = key_data = user_data = \
            access_ip_v4 = access_ip_v6 = config_drive = \
                auto_disk_config = reservation_id = None
        # This tests that 'default' is unchanged, but 'fake-security-group'
        # will be translated to a UUID for Neutron.
        requested_secgroups = ['default', 'fake-security-group']
        # This will short-circuit _check_requested_networks
        requested_networks = objects.NetworkRequestList(objects=[
            objects.NetworkRequest(network_id='none')])
        max_count = 1
        supports_port_resource_request = False
        with mock.patch(
                'nova.network.security_group_api.validate_name',
                return_value=uuids.secgroup_uuid) as scget:
            base_options, max_network_count, key_pair, security_groups, \
                    network_metadata = (
                self.compute_api._validate_and_build_base_options(
                    self.context, instance_type, boot_meta, uuids.image_href,
                    mock.sentinel.image_id, kernel_id, ramdisk_id,
                    'fake-display-name', 'fake-description', key_name,
                    key_data, requested_secgroups, 'fake-az', user_data,
                    metadata, access_ip_v4, access_ip_v6, requested_networks,
                    config_drive, auto_disk_config, reservation_id, max_count,
                    supports_port_resource_request
                )
            )
        # Assert the neutron security group API get method was called once
        # and only for the non-default security group name.
        scget.assert_called_once_with(self.context, 'fake-security-group')
        # Assert we translated the non-default secgroup name to uuid.
        self.assertCountEqual(['default', uuids.secgroup_uuid],
                              security_groups)

    @mock.patch('nova.compute.api.API._record_action_start')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'attach_interface')
    def test_tagged_interface_attach(self, mock_attach, mock_record):
        instance = self._create_instance_obj()
        self.compute_api.attach_interface(self.context, instance, None, None,
                                          None, tag='foo')
        mock_attach.assert_called_with(self.context, instance=instance,
                                       network_id=None, port_id=None,
                                       requested_ip=None, tag='foo')
        mock_record.assert_called_once_with(
            self.context, instance, instance_actions.ATTACH_INTERFACE)

    @mock.patch('nova.objects.service.Service.get_by_host_and_binary')
    @mock.patch('nova.compute.api.API._record_action_start')
    def test_attach_interface_qos_aware_port_old_compute(
        self, mock_record, mock_get_service
    ):
        instance = self._create_instance_obj()
        service = objects.Service()
        service.version = 54
        mock_get_service.return_value = service
        with mock.patch.object(
                self.compute_api.network_api, 'show_port',
                return_value={'port': {
                    constants.RESOURCE_REQUEST: {
                        'resources': {'CUSTOM_RESOURCE_CLASS': 42}
                }}}) as mock_show_port:
            self.assertRaises(
                exception.AttachInterfaceWithQoSPolicyNotSupported,
                self.compute_api.attach_interface,
                self.context, instance,
                'foo_net_id', 'foo_port_id', None
            )
        mock_show_port.assert_called_once_with(self.context, 'foo_port_id')
        mock_get_service.assert_called_once_with(
            self.context, instance.host, 'nova-compute')

    @mock.patch('nova.compute.rpcapi.ComputeAPI.attach_interface')
    @mock.patch('nova.objects.service.Service.get_by_host_and_binary')
    @mock.patch('nova.compute.api.API._record_action_start')
    def test_attach_interface_qos_aware_port(
        self, mock_record, mock_get_service, mock_attach):

        instance = self._create_instance_obj()
        service = objects.Service()
        service.version = 55
        mock_get_service.return_value = service
        with mock.patch.object(
            self.compute_api.network_api,
            "show_port",
            return_value={
                "port": {
                    constants.RESOURCE_REQUEST: {
                        "resources": {"CUSTOM_RESOURCE_CLASS": 42}
                    }
                }
            },
        ) as mock_show_port:
            self.compute_api.attach_interface(
                self.context, instance, mock.sentinel.net_id,
                mock.sentinel.port_id, mock.sentinel.ip, mock.sentinel.tag)

        mock_show_port.assert_called_once_with(
            self.context, mock.sentinel.port_id)
        mock_get_service.assert_called_once_with(
            self.context, instance.host, 'nova-compute')
        mock_attach.assert_called_once_with(
            self.context, instance=instance, network_id=mock.sentinel.net_id,
            port_id=mock.sentinel.port_id, requested_ip=mock.sentinel.ip,
            tag=mock.sentinel.tag)

    @mock.patch('nova.compute.api.API._record_action_start')
    @mock.patch.object(compute_rpcapi.ComputeAPI, 'detach_interface')
    def test_detach_interface(self, mock_detach, mock_record):
        instance = self._create_instance_obj(params={
            'info_cache': objects.InstanceInfoCache(
                network_info=model.NetworkInfo([
                    model.VIF(id=uuids.port, address='foo'),
                ]),
            ),
        })
        self.compute_api.detach_interface(self.context, instance, uuids.port)
        mock_detach.assert_called_with(self.context, instance=instance,
                                       port_id=uuids.port)
        mock_record.assert_called_once_with(
            self.context, instance, instance_actions.DETACH_INTERFACE)

    def test_check_attach_and_reserve_volume_multiattach_old_version(self):
        """Tests that _check_attach_and_reserve_volume fails if trying
        to use a multiattach volume with a microversion<2.60.
        """
        instance = self._create_instance_obj()
        volume = {'id': uuids.volumeid, 'multiattach': True}
        bdm = objects.BlockDeviceMapping(volume_id=uuids.volumeid,
                                         instance_uuid=instance.uuid)
        self.assertRaises(exception.MultiattachNotSupportedOldMicroversion,
                          self.compute_api._check_attach_and_reserve_volume,
                          self.context, volume, instance, bdm,
                          supports_multiattach=False)

    @mock.patch('nova.volume.cinder.API.get',
                return_value={'id': uuids.volumeid, 'multiattach': True})
    def test_attach_volume_shelved_offloaded_fails(
            self, volume_get):
        """Tests that trying to attach a multiattach volume to a shelved
        offloaded instance fails because it's not supported.
        """
        instance = self._create_instance_obj(
            params={'vm_state': vm_states.SHELVED_OFFLOADED})
        with mock.patch.object(
                self.compute_api, '_check_volume_already_attached',
                return_value=None):
            self.assertRaises(exception.MultiattachToShelvedNotSupported,
                              self.compute_api.attach_volume,
                              self.context, instance, uuids.volumeid)

    def test_validate_bdm_check_volume_type_raise_not_found(self):
        """Tests that _validate_bdm will fail if the requested volume type
        name or id does not match the volume types in Cinder.
        """
        volume_types = [{'id': 'fake_volume_type_id_1', 'name': 'fake_lvm_1'},
                        {'id': 'fake_volume_type_id_2', 'name': 'fake_lvm_2'}]
        bdm = objects.BlockDeviceMapping(
            **fake_block_device.FakeDbBlockDeviceDict(
                {
                    'uuid': uuids.image_id,
                    'source_type': 'image',
                    'destination_type': 'volume',
                    'device_name': 'vda',
                    'boot_index': 0,
                    'volume_size': 3,
                    'volume_type': 'lvm-1'}))
        self.assertRaises(exception.VolumeTypeNotFound,
                          self.compute_api._check_requested_volume_type,
                          bdm, 'lvm-1', volume_types)

    @mock.patch.object(neutron_api.API, 'has_substr_port_filtering_extension')
    @mock.patch.object(neutron_api.API, 'list_ports')
    @mock.patch.object(objects.BuildRequestList, 'get_by_filters',
                       new_callable=mock.NonCallableMock)
    def test_get_all_ip_filter(self, mock_buildreq_get, mock_list_port,
                               mock_check_ext):
        mock_check_ext.return_value = True
        cell_instances = self._list_of_instances(2)
        mock_list_port.return_value = {
            'ports': [{'device_id': 'fake_device_id'}]}
        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                self.context, objects=cell_instances), list()

            self.compute_api.get_all(
                self.context, search_opts={'ip': 'fake'},
                limit=None, marker=None, sort_keys=['baz'],
                sort_dirs=['desc'])

            mock_list_port.assert_called_once_with(
                self.context, fixed_ips='ip_address_substr=fake',
                fields=['device_id'])
            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(
                self.context, {'ip': 'fake', 'uuid': ['fake_device_id']},
                None, None, fields, ['baz'], ['desc'], cell_down_support=False)

    @mock.patch.object(neutron_api.API, 'has_substr_port_filtering_extension')
    @mock.patch.object(neutron_api.API, 'list_ports')
    @mock.patch.object(objects.BuildRequestList, 'get_by_filters',
                       new_callable=mock.NonCallableMock)
    def test_get_all_ip6_filter(self, mock_buildreq_get, mock_list_port,
                                mock_check_ext):
        mock_check_ext.return_value = True
        cell_instances = self._list_of_instances(2)
        mock_list_port.return_value = {
            'ports': [{'device_id': 'fake_device_id'}]}
        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                self.context, objects=cell_instances), list()

            self.compute_api.get_all(
                self.context, search_opts={'ip6': 'fake'},
                limit=None, marker=None, sort_keys=['baz'],
                sort_dirs=['desc'])

            mock_list_port.assert_called_once_with(
                self.context, fixed_ips='ip_address_substr=fake',
                fields=['device_id'])
            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(
                self.context, {'ip6': 'fake', 'uuid': ['fake_device_id']},
                None, None, fields, ['baz'], ['desc'], cell_down_support=False)

    @mock.patch.object(neutron_api.API, 'has_substr_port_filtering_extension')
    @mock.patch.object(neutron_api.API, 'list_ports')
    @mock.patch.object(objects.BuildRequestList, 'get_by_filters',
                       new_callable=mock.NonCallableMock)
    def test_get_all_ip_and_ip6_filter(self, mock_buildreq_get, mock_list_port,
                                       mock_check_ext):
        mock_check_ext.return_value = True
        cell_instances = self._list_of_instances(2)
        mock_list_port.return_value = {
            'ports': [{'device_id': 'fake_device_id'}]}
        with mock.patch('nova.compute.instance_list.'
                        'get_instance_objects_sorted') as mock_inst_get:
            mock_inst_get.return_value = objects.InstanceList(
                self.context, objects=cell_instances), list()

            self.compute_api.get_all(
                self.context, search_opts={'ip': 'fake1', 'ip6': 'fake2'},
                limit=None, marker=None, sort_keys=['baz'],
                sort_dirs=['desc'])

            mock_list_port.assert_has_calls([
                mock.call(
                    self.context, fixed_ips='ip_address_substr=fake1',
                    fields=['device_id']),
                mock.call(
                    self.context, fixed_ips='ip_address_substr=fake2',
                    fields=['device_id'])
            ])
            fields = ['metadata', 'info_cache', 'security_groups']
            mock_inst_get.assert_called_once_with(
                self.context, {'ip': 'fake1', 'ip6': 'fake2',
                               'uuid': ['fake_device_id', 'fake_device_id']},
                None, None, fields, ['baz'], ['desc'], cell_down_support=False)

    @mock.patch.object(neutron_api.API, 'has_substr_port_filtering_extension')
    @mock.patch.object(neutron_api.API, 'list_ports')
    def test_get_all_ip6_filter_exc(self, mock_list_port, mock_check_ext):
        mock_check_ext.return_value = True
        mock_list_port.side_effect = exception.InternalError('fake')

        instances = self.compute_api.get_all(
            self.context, search_opts={'ip6': 'fake'},
            limit=None, marker='fake-marker', sort_keys=['baz'],
            sort_dirs=['desc'])
        mock_list_port.assert_called_once_with(
            self.context, fixed_ips='ip_address_substr=fake',
            fields=['device_id'])
        self.assertEqual([], instances.objects)

    @mock.patch.object(compute_utils, 'notify_about_instance_action')
    @mock.patch('nova.compute.api.API._delete_while_booting',
                return_value=False)
    @mock.patch('nova.compute.api.API._lookup_instance')
    @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
    @mock.patch('nova.context.RequestContext.elevated')
    @mock.patch.object(objects.Instance, 'save')
    @mock.patch.object(compute_utils, 'notify_about_instance_usage')
    @mock.patch.object(objects.BlockDeviceMapping, 'destroy')
    @mock.patch.object(objects.Instance, 'destroy')
    def _test_delete_volume_backed_instance(
            self, vm_state, mock_instance_destroy, bdm_destroy,
            notify_about_instance_usage, mock_save, mock_elevated,
            bdm_get_by_instance_uuid, mock_lookup, _mock_del_booting,
            notify_about_instance_action):
        volume_id = uuidutils.generate_uuid()
        conn_info = {'connector': {'host': 'orig-host'}}
        bdms = [objects.BlockDeviceMapping(
                **fake_block_device.FakeDbBlockDeviceDict(
                {'id': 42, 'volume_id': volume_id,
                 'source_type': 'volume', 'destination_type': 'volume',
                 'delete_on_termination': False,
                 'connection_info': jsonutils.dumps(conn_info)}))]

        bdm_get_by_instance_uuid.return_value = bdms
        mock_elevated.return_value = self.context

        params = {'host': None, 'vm_state': vm_state}
        inst = self._create_instance_obj(params=params)
        mock_lookup.return_value = None, inst
        connector = conn_info['connector']

        with mock.patch.object(self.compute_api.network_api,
                     'deallocate_for_instance') as mock_deallocate, \
                 mock.patch.object(self.compute_api.volume_api,
                     'terminate_connection') as mock_terminate_conn, \
                 mock.patch.object(self.compute_api.volume_api,
                     'detach') as mock_detach:
            self.compute_api.delete(self.context, inst)

        mock_deallocate.assert_called_once_with(self.context, inst)
        mock_detach.assert_called_once_with(self.context, volume_id,
                                            inst.uuid)
        mock_terminate_conn.assert_called_once_with(self.context,
                                                    volume_id, connector)
        bdm_destroy.assert_called_once_with()

    def test_delete_volume_backed_instance_in_error(self):
        self._test_delete_volume_backed_instance(vm_states.ERROR)

    def test_delete_volume_backed_instance_in_shelved_offloaded(self):
        self._test_delete_volume_backed_instance(vm_states.SHELVED_OFFLOADED)

    def test_compute_api_host(self):
        self.assertTrue(hasattr(self.compute_api, 'host'))
        self.assertEqual(CONF.host, self.compute_api.host)

    @mock.patch('nova.scheduler.client.report.SchedulerReportClient')
    def test_placement_client_init(self, mock_report_client):
        """Tests to make sure that the construction of the placement client
        only happens once per API class instance.
        """
        self.assertIsNone(self.compute_api._placementclient)
        # Access the property twice to make sure SchedulerReportClient is
        # only loaded once.
        for x in range(2):
            self.compute_api.placementclient
        mock_report_client.assert_called_once_with()

    def test_validate_host_for_cold_migrate_same_host_fails(self):
        """Asserts CannotMigrateToSameHost is raised when trying to cold
        migrate to the same host.
        """
        instance = fake_instance.fake_instance_obj(self.context)
        self.assertRaises(exception.CannotMigrateToSameHost,
                          self.compute_api._validate_host_for_cold_migrate,
                          self.context, instance, instance.host,
                          allow_cross_cell_resize=False)

    @mock.patch('nova.objects.ComputeNode.'
                'get_first_node_by_host_for_old_compat')
    def test_validate_host_for_cold_migrate_diff_host_no_cross_cell(
            self, mock_cn_get):
        """Tests the scenario where allow_cross_cell_resize=False and the
        host is found in the same cell as the instance.
        """
        instance = fake_instance.fake_instance_obj(self.context)
        node = self.compute_api._validate_host_for_cold_migrate(
            self.context, instance, uuids.host, allow_cross_cell_resize=False)
        self.assertIs(node, mock_cn_get.return_value)
        mock_cn_get.assert_called_once_with(
            self.context, uuids.host, use_slave=True)

    @mock.patch('nova.objects.HostMapping.get_by_host',
                side_effect=exception.HostMappingNotFound(name=uuids.host))
    def test_validate_host_for_cold_migrate_cross_cell_host_mapping_not_found(
            self, mock_hm_get):
        """Tests the scenario where allow_cross_cell_resize=True but the
        HostMapping for the given host could not be found.
        """
        instance = fake_instance.fake_instance_obj(self.context)
        self.assertRaises(exception.ComputeHostNotFound,
                          self.compute_api._validate_host_for_cold_migrate,
                          self.context, instance, uuids.host,
                          allow_cross_cell_resize=True)
        mock_hm_get.assert_called_once_with(self.context, uuids.host)

    @mock.patch('nova.objects.HostMapping.get_by_host',
                return_value=objects.HostMapping(
                    cell_mapping=objects.CellMapping(uuid=uuids.cell2)))
    @mock.patch('nova.context.target_cell')
    @mock.patch('nova.objects.ComputeNode.'
                'get_first_node_by_host_for_old_compat')
    def test_validate_host_for_cold_migrate_cross_cell(
            self, mock_cn_get, mock_target_cell, mock_hm_get):
        """Tests the scenario where allow_cross_cell_resize=True and the
        ComputeNode is pulled from the target cell defined by the HostMapping.
        """
        instance = fake_instance.fake_instance_obj(self.context)
        node = self.compute_api._validate_host_for_cold_migrate(
            self.context, instance, uuids.host,
            allow_cross_cell_resize=True)
        self.assertIs(node, mock_cn_get.return_value)
        mock_hm_get.assert_called_once_with(self.context, uuids.host)
        # get_first_node_by_host_for_old_compat is called with a temporarily
        # cell-targeted context
        mock_cn_get.assert_called_once_with(
            mock_target_cell.return_value.__enter__.return_value,
            uuids.host, use_slave=True)

    def _test_get_migrations_sorted_filter_duplicates(self, migrations,
                                                      expected):
        """Tests the cross-cell scenario where there are multiple migrations
        with the same UUID from different cells and only one should be
        returned.
        """
        sort_keys = ['created_at', 'id']
        sort_dirs = ['desc', 'desc']
        filters = {'migration_type': 'resize'}
        limit = 1000
        marker = None
        with mock.patch(
                'nova.compute.migration_list.get_migration_objects_sorted',
                return_value=objects.MigrationList(
                    objects=migrations)) as getter:
            sorted_migrations = self.compute_api.get_migrations_sorted(
                self.context, filters, sort_dirs=sort_dirs,
                sort_keys=sort_keys, limit=limit, marker=marker)
        self.assertEqual(1, len(sorted_migrations))
        getter.assert_called_once_with(
            self.context, filters, limit, marker, sort_keys, sort_dirs)
        self.assertIs(expected, sorted_migrations[0])

    def test_get_migrations_sorted_filter_duplicates(self):
        """Tests filtering duplicated Migration records where both have
        created_at and updated_at set.
        """
        t1 = timeutils.utcnow()
        source_cell_migration = objects.Migration(
            uuid=uuids.migration, created_at=t1, updated_at=t1)
        t2 = t1 + datetime.timedelta(seconds=1)
        target_cell_migration = objects.Migration(
            uuid=uuids.migration, created_at=t2, updated_at=t2)
        self._test_get_migrations_sorted_filter_duplicates(
            [source_cell_migration, target_cell_migration],
            target_cell_migration)
        # Run it again in reverse.
        self._test_get_migrations_sorted_filter_duplicates(
            [target_cell_migration, source_cell_migration],
            target_cell_migration)

    def test_get_migrations_sorted_filter_duplicates_using_created_at(self):
        """Tests the cross-cell scenario where there are multiple migrations
        with the same UUID from different cells and only one should be
        returned. In this test the first Migration object to be processed has
        not been updated yet but is created after the second record to process.
        """
        t1 = timeutils.utcnow()
        older = objects.Migration(
            uuid=uuids.migration, created_at=t1, updated_at=t1)
        t2 = t1 + datetime.timedelta(seconds=1)
        newer = objects.Migration(
            uuid=uuids.migration, created_at=t2, updated_at=None)
        self._test_get_migrations_sorted_filter_duplicates(
            [newer, older], newer)
        # Test with just created_at.
        older.updated_at = None
        self._test_get_migrations_sorted_filter_duplicates(
            [newer, older], newer)
        # Run it again in reverse.
        self._test_get_migrations_sorted_filter_duplicates(
            [older, newer], newer)

    @mock.patch('nova.servicegroup.api.API.service_is_up', return_value=True)
    @mock.patch('nova.objects.Migration.get_by_instance_and_status')
    def test_confirm_resize_cross_cell_move_true(self, mock_migration_get,
                                                 mock_service_is_up):
        """Tests confirm_resize where Migration.cross_cell_move is True"""
        instance = fake_instance.fake_instance_obj(
            self.context, vm_state=vm_states.RESIZED, task_state=None,
            launched_at=timeutils.utcnow())
        migration = objects.Migration(cross_cell_move=True)
        mock_migration_get.return_value = migration
        with test.nested(
            mock.patch.object(self.context, 'elevated',
                              return_value=self.context),
            mock.patch.object(migration, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(self.compute_api.compute_task_api,
                              'confirm_snapshot_based_resize'),
            mock.patch.object(self.compute_api, '_get_source_compute_service'),
        ) as (
            mock_elevated, mock_migration_save, mock_record_action,
            mock_conductor_confirm, mock_get_service
        ):
            self.compute_api.confirm_resize(self.context, instance)
        mock_elevated.assert_called_once_with()
        mock_service_is_up.assert_called_once_with(
            mock_get_service.return_value)
        mock_migration_save.assert_called_once_with()
        self.assertEqual('confirming', migration.status)
        mock_record_action.assert_called_once_with(
            self.context, instance, instance_actions.CONFIRM_RESIZE)
        mock_conductor_confirm.assert_called_once_with(
            self.context, instance, migration)

    @mock.patch('nova.objects.service.get_minimum_version_all_cells')
    def test_allow_cross_cell_resize_default_false(self, mock_get_min_ver):
        """Based on the default policy this asserts nobody is allowed to
        perform cross-cell resize.
        """
        instance = objects.Instance(
            project_id='fake-project', user_id='fake-user')
        self.assertFalse(self.compute_api._allow_cross_cell_resize(
            self.context, instance))
        # We did not need to check the minimum nova-compute version since the
        # policy check failed.
        mock_get_min_ver.assert_not_called()

    @mock.patch('nova.objects.service.get_minimum_version_all_cells',
                return_value=compute_api.MIN_COMPUTE_CROSS_CELL_RESIZE - 1)
    def test_allow_cross_cell_resize_false_old_version(self, mock_get_min_ver):
        """Policy allows cross-cell resize but minimum nova-compute service
        version is not new enough.
        """
        instance = objects.Instance(
            project_id='fake-project', user_id='fake-user',
            uuid=uuids.instance)
        with mock.patch.object(self.context, 'can', return_value=True) as can:
            self.assertFalse(self.compute_api._allow_cross_cell_resize(
                self.context, instance))
        can.assert_called_once()
        mock_get_min_ver.assert_called_once_with(
            self.context, ['nova-compute'])

    @mock.patch('nova.network.neutron.API.get_requested_resource_for_instance',
                return_value=[objects.RequestGroup()])
    @mock.patch('nova.objects.service.get_minimum_version_all_cells',
                return_value=compute_api.MIN_COMPUTE_CROSS_CELL_RESIZE)
    def test_allow_cross_cell_resize_false_port_with_resource_req(
            self, mock_get_min_ver, mock_get_res_req):
        """Policy allows cross-cell resize but minimum nova-compute service
        version is not new enough.
        """
        instance = objects.Instance(
            project_id='fake-project', user_id='fake-user',
            uuid=uuids.instance)
        with mock.patch.object(self.context, 'can', return_value=True) as can:
            self.assertFalse(self.compute_api._allow_cross_cell_resize(
                self.context, instance))
        can.assert_called_once()
        mock_get_min_ver.assert_called_once_with(
            self.context, ['nova-compute'])
        mock_get_res_req.assert_called_once_with(self.context, uuids.instance)

    @mock.patch('nova.network.neutron.API.get_requested_resource_for_instance',
                return_value=[])
    @mock.patch('nova.objects.service.get_minimum_version_all_cells',
                return_value=compute_api.MIN_COMPUTE_CROSS_CELL_RESIZE)
    def test_allow_cross_cell_resize_true(
            self, mock_get_min_ver, mock_get_res_req):
        """Policy allows cross-cell resize and minimum nova-compute service
        version is new enough.
        """
        instance = objects.Instance(
            project_id='fake-project', user_id='fake-user',
            uuid=uuids.instance)
        with mock.patch.object(self.context, 'can', return_value=True) as can:
            self.assertTrue(self.compute_api._allow_cross_cell_resize(
                self.context, instance))
        can.assert_called_once()
        mock_get_min_ver.assert_called_once_with(
            self.context, ['nova-compute'])
        mock_get_res_req.assert_called_once_with(self.context, uuids.instance)

    def _test_block_accelerators(self, instance, args_info,
                                 until_service=None):
        @compute_api.block_accelerators(until_service=until_service)
        def myfunc(self, context, instance, *args, **kwargs):
            args_info['args'] = (context, instance, *args)
            args_info['kwargs'] = dict(**kwargs)

        args = ('arg1', 'arg2')
        kwargs = {'arg3': 'dummy3', 'arg4': 'dummy4'}

        myfunc(mock.ANY, self.context, instance, *args, **kwargs)

        expected_args = (self.context, instance, *args)
        return expected_args, kwargs

    def test_block_accelerators_no_device_profile(self):
        instance = self._create_instance_obj()
        args_info = {}

        expected_args, kwargs = self._test_block_accelerators(
                                    instance, args_info)
        self.assertEqual(expected_args, args_info['args'])
        self.assertEqual(kwargs, args_info['kwargs'])

    def test_block_accelerators_with_device_profile(self):
        extra_specs = {'accel:device_profile': 'mydp'}
        flavor = self._create_flavor(extra_specs=extra_specs)
        instance = self._create_instance_obj(flavor=flavor)
        args_info = {}

        self.assertRaisesRegex(exception.ForbiddenWithAccelerators,
            'Forbidden with instances that have accelerators.',
            self._test_block_accelerators, instance, args_info)
        # myfunc was not called
        self.assertEqual({}, args_info)

    @mock.patch('nova.objects.service.get_minimum_version_all_cells',
                return_value=54)
    def test_block_accelerators_until_service(self, mock_get_min):
        """Support operating server with acclerators until compute service
        more than the version of 53.
        """
        extra_specs = {'accel:device_profile': 'mydp'}
        flavor = self._create_flavor(extra_specs=extra_specs)
        instance = self._create_instance_obj(flavor=flavor)
        args_info = {}
        expected_args, kwargs = self._test_block_accelerators(
                                    instance, args_info, until_service=53)
        self.assertEqual(expected_args, args_info['args'])
        self.assertEqual(kwargs, args_info['kwargs'])

    @mock.patch('nova.objects.service.get_minimum_version_all_cells',
                return_value=52)
    def test_block_accelerators_until_service_forbidden(self, mock_get_min):
        """Ensure a 'ForbiddenWithAccelerators' exception raises if any
        compute service less than the version of 53.
        """
        extra_specs = {'accel:device_profile': 'mydp'}
        flavor = self._create_flavor(extra_specs=extra_specs)
        instance = self._create_instance_obj(flavor=flavor)
        args_info = {}
        self.assertRaisesRegex(exception.ForbiddenWithAccelerators,
            'Forbidden with instances that have accelerators.',
            self._test_block_accelerators, instance, args_info, 53)
        # myfunc was not called
        self.assertEqual({}, args_info)

    @mock.patch('nova.accelerator.cyborg._CyborgClient.'
                'get_arq_uuids_for_instance')
    @mock.patch.object(compute_utils, 'create_image')
    def test_get_arqs_in_shelve(self, mock_create_img, mock_get_arq_uuids):
        """Test get_arq_uuids_for_instance() was called if the
        'accel:device_profile' exist in the flavor for shelve operation.
        """
        extra_specs = {'accel:device_profile': 'mydp'}
        flavor = self._create_flavor(extra_specs=extra_specs)
        params = dict(display_name="vm1")
        instance = self._create_instance_obj(params=params, flavor=flavor)
        mock_create_img.return_value = dict(id='fake-image-id')
        mock_get_arq_uuids.return_value = (
            ['983d1742-c8ca-4f8a-9f3c-3f54bbafaa7d'])
        accel_uuids = mock_get_arq_uuids.return_value

        with test.nested(
            mock.patch('nova.objects.service.get_minimum_version_all_cells',
                        return_value=54),
            mock.patch('nova.compute.utils.is_volume_backed_instance',
                          return_value=False),
            mock.patch.object(objects.Instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(compute_rpcapi.ComputeAPI, 'shelve_instance'),
        ) as (
            mock_get_min, mock_volume_backend,
            mock_instance_save, mock_record_action, mock_shelve_service
        ):
            self.compute_api.shelve(self.context, instance)
        mock_get_arq_uuids.assert_called_once()
        mock_shelve_service.assert_called_once_with(
            self.context, instance=instance, image_id='fake-image-id',
            clean_shutdown=True, accel_uuids=accel_uuids)

    @mock.patch('nova.accelerator.cyborg._CyborgClient.'
                'get_arq_uuids_for_instance')
    @mock.patch.object(compute_utils, 'create_image')
    def test_shelve_with_unsupport_accelerators(
            self, mock_create_img, mock_get_arq_uuids):
        """Test get_arq_uuids_for_instance() was called if the
        'accel:device_profile' exist in the flavor for shelve operation.
        """
        extra_specs = {'accel:device_profile': 'mydp'}
        flavor = self._create_flavor(extra_specs=extra_specs)
        params = dict(display_name="vm1")
        instance = self._create_instance_obj(params=params, flavor=flavor)

        with test.nested(
            mock.patch('nova.objects.service.get_minimum_version_all_cells',
                        return_value=54),
            mock.patch('nova.compute.utils.is_volume_backed_instance',
                          return_value=False),
            mock.patch.object(objects.Instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(compute_rpcapi.ComputeAPI, 'shelve_instance'),
        ) as (
            mock_get_min, mock_volume_backend,
            mock_instance_save, mock_record_action, mock_shelve_service
        ):
            mock_shelve_service.side_effect = (
                exception.ForbiddenWithAccelerators(
                    oldest_supported_version=54,
                    scope=mock.ANY,
                    min_service_level=54,
                    oldest_supported_service=54))
            self.assertRaises(
                exception.ForbiddenWithAccelerators,
                self.compute_api.shelve,
                self.context,
                instance)

    @mock.patch('nova.accelerator.cyborg._CyborgClient.'
                'get_arq_uuids_for_instance')
    @mock.patch('nova.objects.service.get_minimum_version_all_cells',
                return_value=53)
    def test_shelve_until_service_forbidden(self, mock_get_min,
                                            mock_get_arq_uuuids):
        """Ensure a 'ForbiddenWithAccelerators' exception raises if any
        compute service less than the version of 54.
        """
        extra_specs = {'accel:device_profile': 'mydp'}
        flavor = self._create_flavor(extra_specs=extra_specs)
        instance = self._create_instance_obj(flavor=flavor)
        self.assertRaisesRegex(exception.ForbiddenWithAccelerators,
            'Forbidden with instances that have accelerators.',
            self.compute_api.shelve, self.context, instance)
        mock_get_arq_uuuids.assert_not_called()

    @mock.patch('nova.accelerator.cyborg._CyborgClient.'
                'get_arq_uuids_for_instance')
    @mock.patch.object(compute_utils, 'create_image')
    def test_get_arqs_in_shelve_offload(self, mock_create_img,
                                        mock_get_arq_uuids):
        """Test get_arq_uuids_for_instance() was called if the
        'accel:device_profile' exist in the flavor for
        shelve offload operation.
        """
        extra_specs = {'accel:device_profile': 'mydp'}
        flavor = self._create_flavor(extra_specs=extra_specs)
        params = {'vm_state': vm_states.SHELVED}
        instance = self._create_instance_obj(params=params, flavor=flavor)
        mock_create_img.return_value = dict(id='fake-image-id')
        mock_get_arq_uuids.return_value = [uuids.fake]
        accel_uuids = mock_get_arq_uuids.return_value
        with test.nested(
            mock.patch('nova.objects.service.get_minimum_version_all_cells',
                        return_value=54),
            mock.patch.object(objects.Instance, 'save'),
            mock.patch.object(self.compute_api, '_record_action_start'),
            mock.patch.object(compute_rpcapi.ComputeAPI,
                              'shelve_offload_instance'),
        ) as (
            mock_get_min, mock_instance_save,
            mock_record_action, mock_shelve_service
        ):
            self.compute_api.shelve_offload(self.context, instance)
        mock_get_arq_uuids.assert_called_once()
        mock_shelve_service.assert_called_once_with(
            self.context, instance=instance, clean_shutdown=True,
            accel_uuids=accel_uuids)

    # TODO(huaqiang): Remove in Wallaby
    @mock.patch('nova.objects.service.get_minimum_version_all_cells')
    def test__check_compute_service_for_mixed_instance(self, mock_ver):
        """Ensure a 'MixedInstanceNotSupportByComputeService' exception raises
        if any compute node has not been upgraded to Victoria or later.
        """
        mock_ver.side_effect = [52, 51]
        fake_numa_topo = objects.InstanceNUMATopology(cells=[
            objects.InstanceNUMACell(
                id=0, cpuset=set([0]), pcpuset=set([1]), memory=512,
                cpu_policy='mixed')
        ])

        self.compute_api._check_compute_service_for_mixed_instance(
            fake_numa_topo)
        # 'get_minimum_version_all_cells' has been called
        mock_ver.assert_called()

        self.assertRaises(
            exception.MixedInstanceNotSupportByComputeService,
            self.compute_api._check_compute_service_for_mixed_instance,
            fake_numa_topo)

    def test_volume_detach_while_compute_down(self):
        """Assert that requests to detach a volume from an instance on a down
        compute are rejected with ServiceUnavailable being raised
        """
        instance = self._create_instance_obj()
        with mock.patch.object(
            self.compute_api, 'get_instance_host_status',
            return_value=fields_obj.HostStatus.DOWN
        ) as mock_host_status:
            self.assertRaises(
                exception.ServiceUnavailable,
                self.compute_api.detach_volume, self.context, instance, None)
            mock_host_status.assert_called_once_with(instance)