summaryrefslogtreecommitdiff
path: root/nova/tests/functional/test_servers.py
blob: 4c9ab739d46bb3cfedf8dc10f6fad04b7aaf5652 (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
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import collections
import copy
import datetime
import time
from unittest import mock
import zlib

from cinderclient import exceptions as cinder_exception
from keystoneauth1 import adapter
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import base64
from oslo_serialization import jsonutils
from oslo_utils import fixture as osloutils_fixture
from oslo_utils.fixture import uuidsentinel as uuids
from oslo_utils import timeutils

from nova.compute import api as compute_api
from nova.compute import instance_actions
from nova.compute import manager as compute_manager
from nova.compute import rpcapi as compute_rpcapi
from nova import context
from nova import exception
from nova.network import neutron as neutronapi
from nova import objects
from nova.objects import block_device as block_device_obj
from nova.scheduler import utils
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.functional.api import client
from nova.tests.functional import integrated_helpers
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_block_device
from nova.tests.unit import fake_requests
from nova.tests.unit.objects import test_instance_info_cache
from nova import utils as nova_utils
from nova.virt import fake
from nova import volume

CONF = cfg.CONF

LOG = logging.getLogger(__name__)


class ServersTest(integrated_helpers._IntegratedTestBase):
    api_major_version = 'v2'

    def test_get_servers(self):
        # Simple check that listing servers works.
        servers = self.api.get_servers()
        for server in servers:
            LOG.debug("server: %s", server)

    def _get_node_build_failures(self):
        ctxt = context.get_admin_context()
        computes = objects.ComputeNodeList.get_all(ctxt)
        return {
            node.hypervisor_hostname: int(node.stats.get('failed_builds', 0))
            for node in computes}

    def test_create_server_with_error(self):
        # Create a server which will enter error state.

        def throw_error(*args, **kwargs):
            raise exception.BuildAbortException(reason='',
                    instance_uuid='fake')

        self.stub_out('nova.virt.fake.FakeDriver.spawn', throw_error)

        server = self._build_server()
        created_server = self.api.post_server({"server": server})
        created_server_id = created_server['id']

        found_server = self.api.get_server(created_server_id)
        self.assertEqual(created_server_id, found_server['id'])

        found_server = self._wait_for_state_change(found_server, 'ERROR')

        # Delete the server
        self._delete_server(created_server)

        # We should have no (persisted) build failures until we update
        # resources, after which we should have one
        self.assertEqual([0], list(self._get_node_build_failures().values()))

        # BuildAbortException will not trigger a reschedule and the build
        # failure update is the last step in the compute manager after
        # instance state setting, fault recording and notification sending. So
        # we have no other way than simply wait to ensure the node build
        # failure counter updated before we assert it.
        def failed_counter_updated():
            self._run_periodics()
            self.assertEqual(
                [1], list(self._get_node_build_failures().values()))

        self._wait_for_assert(failed_counter_updated)

    def test_create_server_with_image_type_filter(self):
        self.flags(query_placement_for_image_type_support=True,
                   group='scheduler')

        raw_image = '155d900f-4e14-4e4c-a73d-069cbf4541e6'
        vhd_image = 'a440c04b-79fa-479c-bed1-0b816eaec379'

        server = self._build_server(image_uuid=vhd_image)
        server = self.api.post_server({'server': server})
        server = self.api.get_server(server['id'])
        errored_server = self._wait_for_state_change(server, 'ERROR')
        self.assertIn('No valid host', errored_server['fault']['message'])

        server = self._build_server(image_uuid=raw_image)
        server = self.api.post_server({'server': server})
        server = self.api.get_server(server['id'])
        created_server = self._wait_for_state_change(server, 'ACTIVE')

        # Delete the server
        self._delete_server(created_server)

    def _test_create_server_with_error_with_retries(self):
        # Create a server which will enter error state.

        self._start_compute('host2')

        fails = []

        def throw_error(*args, **kwargs):
            fails.append('one')
            raise test.TestingException('Please retry me')

        self.stub_out('nova.virt.fake.FakeDriver.spawn', throw_error)

        server = self._build_server()
        created_server = self.api.post_server({"server": server})
        created_server_id = created_server['id']

        found_server = self.api.get_server(created_server_id)
        self.assertEqual(created_server_id, found_server['id'])

        found_server = self._wait_for_state_change(found_server, 'ERROR')

        # Delete the server
        self._delete_server(created_server)

        return len(fails)

    def test_create_server_with_error_with_retries(self):
        self.flags(max_attempts=2, group='scheduler')
        fails = self._test_create_server_with_error_with_retries()
        self.assertEqual(2, fails)
        self._run_periodics()
        self.assertEqual(
            [1, 1], list(self._get_node_build_failures().values()))

    def test_create_server_with_error_with_no_retries(self):
        self.flags(max_attempts=1, group='scheduler')
        fails = self._test_create_server_with_error_with_retries()
        self.assertEqual(1, fails)

        # The build failure update is the last step in build_and_run_instance
        # in the compute manager after instance state setting, fault
        # recording and notification sending. So we have no other way than
        # simply wait to ensure the node build failure counter updated
        # before we assert it.
        def failed_counter_updated():
            self._run_periodics()
            self.assertEqual(
                [0, 1], list(sorted(self._get_node_build_failures().values())))

        self._wait_for_assert(failed_counter_updated)

    def test_create_and_delete_server(self):
        # Creates and deletes a server.

        # Create server
        # Build the server data gradually, checking errors along the way
        server = {}
        good_server = self._build_server()

        post = {'server': server}

        # Without an imageRef, this throws 500.
        # TODO(justinsb): Check whatever the spec says should be thrown here
        self.assertRaises(client.OpenStackApiException,
                          self.api.post_server, post)

        # With an invalid imageRef, this throws 500.
        server['imageRef'] = uuids.fake
        # TODO(justinsb): Check whatever the spec says should be thrown here
        self.assertRaises(client.OpenStackApiException,
                          self.api.post_server, post)

        # Add a valid imageRef
        server['imageRef'] = good_server.get('imageRef')

        # Without flavorRef, this throws 500
        # TODO(justinsb): Check whatever the spec says should be thrown here
        self.assertRaises(client.OpenStackApiException,
                          self.api.post_server, post)

        server['flavorRef'] = good_server.get('flavorRef')

        # Without a name, this throws 500
        # TODO(justinsb): Check whatever the spec says should be thrown here
        self.assertRaises(client.OpenStackApiException,
                          self.api.post_server, post)

        # Set a valid server name
        server['name'] = good_server['name']

        created_server = self.api.post_server(post)
        LOG.debug("created_server: %s", created_server)
        self.assertTrue(created_server['id'])
        created_server_id = created_server['id']

        # Check it's there
        found_server = self.api.get_server(created_server_id)
        self.assertEqual(created_server_id, found_server['id'])

        # It should also be in the all-servers list
        servers = self.api.get_servers()
        server_ids = [s['id'] for s in servers]
        self.assertIn(created_server_id, server_ids)

        found_server = self._wait_for_state_change(found_server, 'ACTIVE')

        servers = self.api.get_servers(detail=True)
        for server in servers:
            self.assertIn("image", server)
            self.assertIn("flavor", server)

        # Delete the server
        self._delete_server(found_server)

    def _force_reclaim(self):
        # Make sure that compute manager thinks the instance is
        # old enough to be expired
        the_past = timeutils.utcnow() + datetime.timedelta(hours=1)
        timeutils.set_time_override(override_time=the_past)
        self.addCleanup(timeutils.clear_time_override)
        ctxt = context.get_admin_context()
        self.compute._reclaim_queued_deletes(ctxt)

    def test_deferred_delete(self):
        # Creates, deletes and waits for server to be reclaimed.
        self.flags(reclaim_instance_interval=1)

        # Create server
        server = self._build_server()

        created_server = self.api.post_server({'server': server})
        LOG.debug("created_server: %s", created_server)
        self.assertTrue(created_server['id'])
        created_server_id = created_server['id']

        # Wait for it to finish being created
        found_server = self._wait_for_state_change(created_server, 'ACTIVE')

        # Cannot restore unless instance is deleted
        self.assertRaises(client.OpenStackApiException,
                          self.api.post_server_action, created_server_id,
                          {'restore': {}})

        # Delete the server
        self.api.delete_server(created_server_id)

        # Wait for queued deletion
        found_server = self._wait_for_state_change(found_server,
                                                   'SOFT_DELETED')

        self._force_reclaim()

        # Wait for real deletion
        self._wait_until_deleted(found_server)

    def test_deferred_delete_restore(self):
        # Creates, deletes and restores a server.
        self.flags(reclaim_instance_interval=3600)

        # Create server
        server = self._build_server()

        created_server = self.api.post_server({'server': server})
        LOG.debug("created_server: %s", created_server)
        self.assertTrue(created_server['id'])
        created_server_id = created_server['id']

        # Wait for it to finish being created
        found_server = self._wait_for_state_change(created_server, 'ACTIVE')

        # Delete the server
        self.api.delete_server(created_server_id)

        # Wait for queued deletion
        found_server = self._wait_for_state_change(found_server,
                                                   'SOFT_DELETED')

        # Restore server
        self.api.post_server_action(created_server_id, {'restore': {}})

        # Wait for server to become active again
        found_server = self._wait_for_state_change(found_server, 'ACTIVE')

    def test_deferred_delete_restore_overquota(self):
        # Test that a restore that would put the user over quota fails
        self.flags(instances=1, group='quota')
        # Creates, deletes and restores a server.
        self.flags(reclaim_instance_interval=3600)

        # Create server
        server = self._build_server()

        created_server1 = self.api.post_server({'server': server})
        LOG.debug("created_server: %s", created_server1)
        self.assertTrue(created_server1['id'])
        created_server_id1 = created_server1['id']

        # Wait for it to finish being created
        found_server1 = self._wait_for_state_change(created_server1, 'ACTIVE')

        # Delete the server
        self.api.delete_server(created_server_id1)

        # Wait for queued deletion
        found_server1 = self._wait_for_state_change(found_server1,
                                                    'SOFT_DELETED')

        # Create a second server
        self._create_server()

        # Try to restore the first server, it should fail
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               created_server_id1, {'restore': {}})
        self.assertEqual(403, ex.response.status_code)
        self.assertEqual('SOFT_DELETED', found_server1['status'])

    def test_deferred_delete_force(self):
        # Creates, deletes and force deletes a server.
        self.flags(reclaim_instance_interval=3600)

        # Create server
        server = self._build_server()

        created_server = self.api.post_server({'server': server})
        LOG.debug("created_server: %s", created_server)
        self.assertTrue(created_server['id'])
        created_server_id = created_server['id']

        # Wait for it to finish being created
        found_server = self._wait_for_state_change(created_server, 'ACTIVE')

        # Delete the server
        self.api.delete_server(created_server_id)

        # Wait for queued deletion
        found_server = self._wait_for_state_change(found_server,
                                                   'SOFT_DELETED')

        # Force delete server
        self.api.post_server_action(created_server_id, {'forceDelete': {}})

        # Wait for real deletion
        self._wait_until_deleted(found_server)

    def test_create_server_with_metadata(self):
        # Creates a server with metadata.

        # Build the server data gradually, checking errors along the way
        server = self._build_server()

        metadata = {}
        for i in range(30):
            metadata['key_%s' % i] = 'value_%s' % i

        server['metadata'] = metadata

        post = {'server': server}
        created_server = self.api.post_server(post)
        LOG.debug("created_server: %s", created_server)
        self.assertTrue(created_server['id'])
        created_server_id = created_server['id']

        found_server = self.api.get_server(created_server_id)
        self.assertEqual(created_server_id, found_server['id'])
        self.assertEqual(metadata, found_server.get('metadata'))

        # The server should also be in the all-servers details list
        servers = self.api.get_servers(detail=True)
        server_map = {server['id']: server for server in servers}
        found_server = server_map.get(created_server_id)
        self.assertTrue(found_server)
        # Details do include metadata
        self.assertEqual(metadata, found_server.get('metadata'))

        # The server should also be in the all-servers summary list
        servers = self.api.get_servers(detail=False)
        server_map = {server['id']: server for server in servers}
        found_server = server_map.get(created_server_id)
        self.assertTrue(found_server)
        # Summary should not include metadata
        self.assertFalse(found_server.get('metadata'))

        # Cleanup
        self._delete_server(found_server)

    def test_server_metadata_actions_negative_invalid_state(self):
        # Create server with metadata
        server = self._build_server()

        metadata = {'key_1': 'value_1'}

        server['metadata'] = metadata

        post = {'server': server}
        created_server = self.api.post_server(post)

        found_server = self._wait_for_state_change(created_server, 'ACTIVE')
        self.assertEqual(metadata, found_server.get('metadata'))
        server_id = found_server['id']

        # Change status from ACTIVE to SHELVED for negative test
        self.flags(shelved_offload_time = -1)
        self.api.post_server_action(server_id, {'shelve': {}})
        found_server = self._wait_for_state_change(found_server, 'SHELVED')

        metadata = {'key_2': 'value_2'}

        # Update Metadata item in SHELVED (not ACTIVE, etc.)
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_metadata,
                               server_id, metadata)
        self.assertEqual(409, ex.response.status_code)
        self.assertEqual('SHELVED', found_server['status'])

        # Delete Metadata item in SHELVED (not ACTIVE, etc.)
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.delete_server_metadata,
                               server_id, 'key_1')
        self.assertEqual(409, ex.response.status_code)
        self.assertEqual('SHELVED', found_server['status'])

        # Cleanup
        self._delete_server(found_server)

    def test_create_and_rebuild_server(self):
        # Rebuild a server with metadata.

        # create a server with initially has no metadata
        server = self._build_server()
        server_post = {'server': server}

        metadata = {}
        for i in range(30):
            metadata['key_%s' % i] = 'value_%s' % i

        server_post['server']['metadata'] = metadata

        created_server = self.api.post_server(server_post)
        LOG.debug("created_server: %s", created_server)
        self.assertTrue(created_server['id'])
        created_server_id = created_server['id']

        created_server = self._wait_for_state_change(created_server, 'ACTIVE')

        # rebuild the server with metadata and other server attributes
        post = {}
        post['rebuild'] = {
            'imageRef': '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6',
            'name': 'blah',
            'accessIPv4': '172.19.0.2',
            'accessIPv6': 'fe80::2',
            'metadata': {'some': 'thing'},
        }
        post['rebuild'].update({
            'accessIPv4': '172.19.0.2',
            'accessIPv6': 'fe80::2',
        })

        self.api.post_server_action(created_server_id, post)
        LOG.debug("rebuilt server: %s", created_server)
        self.assertTrue(created_server['id'])

        found_server = self.api.get_server(created_server_id)
        self.assertEqual(created_server_id, found_server['id'])
        self.assertEqual({'some': 'thing'}, found_server.get('metadata'))
        self.assertEqual('blah', found_server.get('name'))
        self.assertEqual(post['rebuild']['imageRef'],
                         found_server.get('image')['id'])
        self.assertEqual('172.19.0.2', found_server['accessIPv4'])
        self.assertEqual('fe80::2', found_server['accessIPv6'])

        # rebuild the server with empty metadata and nothing else
        post = {}
        post['rebuild'] = {
            'imageRef': "76fa36fc-c930-4bf3-8c8a-ea2a2420deb6",
            "metadata": {},
        }

        self.api.post_server_action(created_server_id, post)
        LOG.debug("rebuilt server: %s", created_server)
        self.assertTrue(created_server['id'])

        found_server = self.api.get_server(created_server_id)
        self.assertEqual(created_server_id, found_server['id'])
        self.assertEqual({}, found_server.get('metadata'))
        self.assertEqual('blah', found_server.get('name'))
        self.assertEqual(post['rebuild']['imageRef'],
                         found_server.get('image')['id'])
        self.assertEqual('172.19.0.2', found_server['accessIPv4'])
        self.assertEqual('fe80::2', found_server['accessIPv6'])

        # Cleanup
        self._delete_server(found_server)

    def test_rename_server(self):
        # Test building and renaming a server.

        # Create a server
        server = self._build_server()
        created_server = self.api.post_server({'server': server})
        LOG.debug("created_server: %s", created_server)
        server_id = created_server['id']
        self.assertTrue(server_id)

        # Rename the server to 'new-name'
        self.api.put_server(server_id, {'server': {'name': 'new-name'}})

        # Check the name of the server
        created_server = self.api.get_server(server_id)
        self.assertEqual(created_server['name'], 'new-name')

        # Cleanup
        self._delete_server(created_server)

    def test_create_multiple_servers(self):
        # Creates multiple servers and checks for reservation_id.

        # Create 2 servers, setting 'return_reservation_id, which should
        # return a reservation_id
        server = self._build_server()
        server['min_count'] = 2
        server['return_reservation_id'] = True
        post = {'server': server}
        response = self.api.post_server(post)
        self.assertIn('reservation_id', response)
        reservation_id = response['reservation_id']
        self.assertNotIn(reservation_id, ['', None])
        # Assert that the reservation_id itself has the expected format
        self.assertRegex(reservation_id, 'r-[0-9a-zA-Z]{8}')

        # Create 1 more server, which should not return a reservation_id
        server = self._build_server()
        post = {'server': server}
        created_server = self.api.post_server(post)
        self.assertTrue(created_server['id'])
        created_server_id = created_server['id']

        # lookup servers created by the first request.
        servers = self.api.get_servers(detail=True,
                search_opts={'reservation_id': reservation_id})
        server_map = {server['id']: server for server in servers}
        found_server = server_map.get(created_server_id)
        # The server from the 2nd request should not be there.
        self.assertIsNone(found_server)
        # Should have found 2 servers.
        self.assertEqual(len(server_map), 2)

        # Cleanup
        self._delete_server(created_server)
        for server in server_map.values():
            self._delete_server(server)

    def test_create_server_with_injected_files(self):
        # Creates a server with injected_files.
        personality = []

        # Inject a text file
        data = 'Hello, World!'
        personality.append({
            'path': '/helloworld.txt',
            'contents': base64.encode_as_bytes(data),
        })

        # Inject a binary file
        data = zlib.compress(b'Hello, World!')
        personality.append({
            'path': '/helloworld.zip',
            'contents': base64.encode_as_bytes(data),
        })

        # Create server
        server = self._build_server()
        server['personality'] = personality

        post = {'server': server}

        created_server = self.api.post_server(post)
        LOG.debug("created_server: %s", created_server)
        self.assertTrue(created_server['id'])
        created_server_id = created_server['id']

        # Check it's there
        found_server = self.api.get_server(created_server_id)
        self.assertEqual(created_server_id, found_server['id'])

        found_server = self._wait_for_state_change(found_server, 'ACTIVE')

        # Cleanup
        self._delete_server(found_server)

    def test_stop_start_servers_negative_invalid_state(self):
        # Create server
        server = self._build_server()
        created_server = self.api.post_server({"server": server})
        created_server_id = created_server['id']

        found_server = self._wait_for_state_change(created_server, 'ACTIVE')

        # Start server in ACTIVE
        # NOTE(mkoshiya): When os-start API runs, the server status
        # must be SHUTOFF.
        # By returning 409, I want to confirm that the ACTIVE server does not
        # cause unexpected behavior.
        post = {'os-start': {}}
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               created_server_id, post)
        self.assertEqual(409, ex.response.status_code)
        self.assertEqual('ACTIVE', found_server['status'])

        # Stop server
        post = {'os-stop': {}}
        self.api.post_server_action(created_server_id, post)
        found_server = self._wait_for_state_change(found_server, 'SHUTOFF')

        # Stop server in SHUTOFF
        # NOTE(mkoshiya): When os-stop API runs, the server status
        # must be ACTIVE or ERROR.
        # By returning 409, I want to confirm that the SHUTOFF server does not
        # cause unexpected behavior.
        post = {'os-stop': {}}
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               created_server_id, post)
        self.assertEqual(409, ex.response.status_code)
        self.assertEqual('SHUTOFF', found_server['status'])

        # Cleanup
        self._delete_server(found_server)

    def test_revert_resized_server_negative_invalid_state(self):
        # Create server
        server = self._build_server()
        created_server = self.api.post_server({"server": server})
        created_server_id = created_server['id']
        found_server = self._wait_for_state_change(created_server, 'ACTIVE')

        # Revert resized server in ACTIVE
        # NOTE(yatsumi): When revert resized server API runs,
        # the server status must be VERIFY_RESIZE.
        # By returning 409, I want to confirm that the ACTIVE server does not
        # cause unexpected behavior.
        post = {'revertResize': {}}
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               created_server_id, post)
        self.assertEqual(409, ex.response.status_code)
        self.assertEqual('ACTIVE', found_server['status'])

        # Cleanup
        self._delete_server(found_server)

    def test_resize_server_negative_invalid_state(self):
        # Avoid migration
        self.flags(allow_resize_to_same_host=True)

        # Create server
        server = self._build_server()
        created_server = self.api.post_server({"server": server})
        created_server_id = created_server['id']
        found_server = self._wait_for_state_change(created_server, 'ACTIVE')

        # Resize server(flavorRef: 1 -> 2)
        post = {'resize': {"flavorRef": "2", "OS-DCF:diskConfig": "AUTO"}}
        self.api.post_server_action(created_server_id, post)
        found_server = self._wait_for_state_change(found_server,
                                                   'VERIFY_RESIZE')

        # Resize server in VERIFY_RESIZE(flavorRef: 2 -> 1)
        # NOTE(yatsumi): When resize API runs, the server status
        # must be ACTIVE or SHUTOFF.
        # By returning 409, I want to confirm that the VERIFY_RESIZE server
        # does not cause unexpected behavior.
        post = {'resize': {"flavorRef": "1", "OS-DCF:diskConfig": "AUTO"}}
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               created_server_id, post)
        self.assertEqual(409, ex.response.status_code)
        self.assertEqual('VERIFY_RESIZE', found_server['status'])

        # Cleanup
        self._delete_server(found_server)

    def test_confirm_resized_server_negative_invalid_state(self):
        # Create server
        server = self._build_server()
        created_server = self.api.post_server({"server": server})
        created_server_id = created_server['id']
        found_server = self._wait_for_state_change(created_server, 'ACTIVE')

        # Confirm resized server in ACTIVE
        # NOTE(yatsumi): When confirm resized server API runs,
        # the server status must be VERIFY_RESIZE.
        # By returning 409, I want to confirm that the ACTIVE server does not
        # cause unexpected behavior.
        post = {'confirmResize': {}}
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               created_server_id, post)
        self.assertEqual(409, ex.response.status_code)
        self.assertEqual('ACTIVE', found_server['status'])

        # Cleanup
        self._delete_server(found_server)

    def test_resize_server_overquota(self):
        self.flags(cores=1, group='quota')
        self.flags(ram=512, group='quota')
        # Create server with default flavor, 1 core, 512 ram
        server = self._build_server()
        created_server = self.api.post_server({"server": server})
        created_server_id = created_server['id']

        self._wait_for_state_change(created_server, 'ACTIVE')

        # Try to resize to flavorid 2, 1 core, 2048 ram
        post = {'resize': {'flavorRef': '2'}}
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               created_server_id, post)
        self.assertEqual(403, ex.response.status_code)

    def test_attach_vol_maximum_disk_devices_exceeded(self):
        server = self._build_server()
        created_server = self.api.post_server({"server": server})
        server_id = created_server['id']
        self._wait_for_state_change(created_server, 'ACTIVE')

        volume_id = '9a695496-44aa-4404-b2cc-ccab2501f87e'
        LOG.info('Attaching volume %s to server %s', volume_id, server_id)

        # The fake driver doesn't implement get_device_name_for_instance, so
        # we'll just raise the exception directly here, instead of simulating
        # an instance with 26 disk devices already attached.
        with mock.patch.object(self.compute.driver,
                               'get_device_name_for_instance') as mock_get:
            mock_get.side_effect = exception.TooManyDiskDevices(maximum=26)
            ex = self.assertRaises(
                client.OpenStackApiException, self.api.post_server_volume,
                server_id, dict(volumeAttachment=dict(volumeId=volume_id)))
            expected = ('The maximum allowed number of disk devices (26) to '
                        'attach to a single instance has been exceeded.')
            self.assertEqual(403, ex.response.status_code)
            self.assertIn(expected, str(ex))


class ServersTestV21(ServersTest):
    api_major_version = 'v2.1'


class ServersTestV219(integrated_helpers._IntegratedTestBase):
    api_major_version = 'v2.1'

    def _create_server(self, set_desc = True, desc = None):
        server = self._build_server()
        if set_desc:
            server['description'] = desc
        post = {'server': server}
        response = self.api.api_post('/servers', post).body
        return (server, response['server'])

    def _update_server(self, server_id, set_desc = True, desc = None):
        new_name = integrated_helpers.generate_random_alphanumeric(8)
        server = {'server': {'name': new_name}}
        if set_desc:
            server['server']['description'] = desc
        self.api.api_put('/servers/%s' % server_id, server)

    def _rebuild_server(self, server_id, set_desc = True, desc = None):
        new_name = integrated_helpers.generate_random_alphanumeric(8)
        post = {}
        post['rebuild'] = {
            'name': new_name,
            'imageRef': '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6',
            'accessIPv4': '172.19.0.2',
            'accessIPv6': 'fe80::2',
            'metadata': {'some': 'thing'},
        }
        post['rebuild'].update({
            'accessIPv4': '172.19.0.2',
            'accessIPv6': 'fe80::2',
        })
        if set_desc:
            post['rebuild']['description'] = desc
        self.api.api_post('/servers/%s/action' % server_id, post)

    def _create_server_and_verify(self, set_desc = True, expected_desc = None):
        # Creates a server with a description and verifies it is
        # in the GET responses.
        created_server = self._create_server(set_desc, expected_desc)[1]
        self._verify_server_description(created_server['id'], expected_desc)
        self._delete_server(created_server)

    def _update_server_and_verify(self, server_id, set_desc = True,
                                  expected_desc = None):
        # Updates a server with a description and verifies it is
        # in the GET responses.
        self._update_server(server_id, set_desc, expected_desc)
        self._verify_server_description(server_id, expected_desc)

    def _rebuild_server_and_verify(self, server_id, set_desc = True,
                                  expected_desc = None):
        # Rebuilds a server with a description and verifies it is
        # in the GET responses.
        self._rebuild_server(server_id, set_desc, expected_desc)
        self._verify_server_description(server_id, expected_desc)

    def _verify_server_description(self, server_id, expected_desc = None,
                                   desc_in_resp = True):
        # Calls GET on the servers and verifies that the description
        # is set as expected in the response, or not set at all.
        response = self.api.api_get('/servers/%s' % server_id)
        found_server = response.body['server']
        self.assertEqual(server_id, found_server['id'])
        if desc_in_resp:
            # Verify the description is set as expected (can be None)
            self.assertEqual(expected_desc, found_server.get('description'))
        else:
            # Verify the description is not included in the response.
            self.assertNotIn('description', found_server)

        servers = self.api.api_get('/servers/detail').body['servers']
        server_map = {server['id']: server for server in servers}
        found_server = server_map.get(server_id)
        self.assertTrue(found_server)
        if desc_in_resp:
            # Verify the description is set as expected (can be None)
            self.assertEqual(expected_desc, found_server.get('description'))
        else:
            # Verify the description is not included in the response.
            self.assertNotIn('description', found_server)

    def _create_assertRaisesRegex(self, desc):
        # Verifies that a 400 error is thrown on create server
        with self.assertRaisesRegex(client.OpenStackApiException,
                                    ".*Unexpected status code.*") as cm:
            self._create_server(True, desc)
            self.assertEqual(400, cm.exception.response.status_code)

    def _update_assertRaisesRegex(self, server_id, desc):
        # Verifies that a 400 error is thrown on update server
        with self.assertRaisesRegex(client.OpenStackApiException,
                                    ".*Unexpected status code.*") as cm:
            self._update_server(server_id, True, desc)
            self.assertEqual(400, cm.exception.response.status_code)

    def _rebuild_assertRaisesRegex(self, server_id, desc):
        # Verifies that a 400 error is thrown on rebuild server
        with self.assertRaisesRegex(client.OpenStackApiException,
                                    ".*Unexpected status code.*") as cm:
            self._rebuild_server(server_id, True, desc)
            self.assertEqual(400, cm.exception.response.status_code)

    def test_create_server_with_description(self):
        self.api.microversion = '2.19'
        # Create and get a server with a description
        self._create_server_and_verify(True, 'test description')
        # Create and get a server with an empty description
        self._create_server_and_verify(True, '')
        # Create and get a server with description set to None
        self._create_server_and_verify()
        # Create and get a server without setting the description
        self._create_server_and_verify(False)

    def test_update_server_with_description(self):
        self.api.microversion = '2.19'
        # Create a server with an initial description
        server = self._create_server(True, 'test desc 1')[1]
        server_id = server['id']

        # Update and get the server with a description
        self._update_server_and_verify(server_id, True, 'updated desc')
        # Update and get the server name without changing the description
        self._update_server_and_verify(server_id, False, 'updated desc')
        # Update and get the server with an empty description
        self._update_server_and_verify(server_id, True, '')
        # Update and get the server by removing the description (set to None)
        self._update_server_and_verify(server_id)
        # Update and get the server with a 2nd new description
        self._update_server_and_verify(server_id, True, 'updated desc2')

        # Cleanup
        self._delete_server(server)

    def test_rebuild_server_with_description(self):
        self.api.microversion = '2.19'

        # Create a server with an initial description
        server = self._create_server(True, 'test desc 1')[1]
        server_id = server['id']
        self._wait_for_state_change(server, 'ACTIVE')

        # Rebuild and get the server with a description
        self._rebuild_server_and_verify(server_id, True, 'updated desc')
        # Rebuild and get the server name without changing the description
        self._rebuild_server_and_verify(server_id, False, 'updated desc')
        # Rebuild and get the server with an empty description
        self._rebuild_server_and_verify(server_id, True, '')
        # Rebuild and get the server by removing the description (set to None)
        self._rebuild_server_and_verify(server_id)
        # Rebuild and get the server with a 2nd new description
        self._rebuild_server_and_verify(server_id, True, 'updated desc2')

        # Cleanup
        self._delete_server(server)

    def test_version_compatibility(self):
        # Create a server with microversion v2.19 and a description.
        self.api.microversion = '2.19'
        server = self._create_server(True, 'test desc 1')[1]
        server_id = server['id']
        # Verify that the description is not included on V2.18 GETs
        self.api.microversion = '2.18'
        self._verify_server_description(server_id, desc_in_resp = False)
        # Verify that updating the server with description on V2.18
        # results in a 400 error
        self._update_assertRaisesRegex(server_id, 'test update 2.18')
        # Verify that rebuilding the server with description on V2.18
        # results in a 400 error
        self._rebuild_assertRaisesRegex(server_id, 'test rebuild 2.18')

        # Cleanup
        self._delete_server(server)

        # Create a server on V2.18 and verify that the description
        # defaults to the name on a V2.19 GET
        server_req, server = self._create_server(False)
        server_id = server['id']
        self.api.microversion = '2.19'
        self._verify_server_description(server_id, server_req['name'])

        # Cleanup
        self._delete_server(server)

        # Verify that creating a server with description on V2.18
        # results in a 400 error
        self.api.microversion = '2.18'
        self._create_assertRaisesRegex('test create 2.18')

    def test_description_errors(self):
        self.api.microversion = '2.19'
        # Create servers with invalid descriptions.  These throw 400.
        # Invalid unicode with non-printable control char
        self._create_assertRaisesRegex(u'invalid\0dstring')
        # Description is longer than 255 chars
        self._create_assertRaisesRegex('x' * 256)

        # Update and rebuild servers with invalid descriptions.
        # These throw 400.
        server_id = self._create_server(True, "desc")[1]['id']
        # Invalid unicode with non-printable control char
        self._update_assertRaisesRegex(server_id, u'invalid\u0604string')
        self._rebuild_assertRaisesRegex(server_id, u'invalid\u0604string')
        # Description is longer than 255 chars
        self._update_assertRaisesRegex(server_id, 'x' * 256)
        self._rebuild_assertRaisesRegex(server_id, 'x' * 256)


class ServerTestV220(integrated_helpers._IntegratedTestBase):
    api_major_version = 'v2.1'

    def setUp(self):
        super(ServerTestV220, self).setUp()
        self.api.microversion = '2.20'
        self.ctxt = context.get_admin_context()

    def _create_server(self):
        server = self._build_server()
        post = {'server': server}
        response = self.api.api_post('/servers', post).body
        return (server, response['server'])

    def _shelve_server(self):
        server = self._create_server()[1]
        server_id = server['id']
        self._wait_for_state_change(server, 'ACTIVE')
        self.api.post_server_action(server_id, {'shelve': None})
        return self._wait_for_state_change(server, 'SHELVED_OFFLOADED')

    def _get_fake_bdms(self, ctxt):
        return block_device_obj.block_device_make_list(self.ctxt,
                    [fake_block_device.FakeDbBlockDeviceDict(
                    {'device_name': '/dev/vda',
                     'source_type': 'volume',
                     'destination_type': 'volume',
                     'volume_id': '5d721593-f033-4f6d-ab6f-b5b067e61bc4'})])

    def test_attach_detach_vol_to_shelved_offloaded_server_new_flow(self):
        self.flags(shelved_offload_time=0)
        found_server = self._shelve_server()
        server_id = found_server['id']
        fake_bdms = self._get_fake_bdms(self.ctxt)

        # Test attach volume
        self.stub_out('nova.volume.cinder.API.get', fakes.stub_volume_get)
        with test.nested(mock.patch.object(compute_api.API,
                            '_check_volume_already_attached'),
                         mock.patch.object(volume.cinder.API,
                                        'check_availability_zone'),
                         mock.patch.object(volume.cinder.API,
                                        'attachment_create'),
                         mock.patch.object(volume.cinder.API,
                                        'attachment_complete')
                         ) as (mock_check_vol_attached,
                               mock_check_av_zone, mock_attach_create,
                               mock_attachment_complete):
            mock_attach_create.return_value = {'id': uuids.volume}
            volume_attachment = {"volumeAttachment": {"volumeId":
                                       "5d721593-f033-4f6d-ab6f-b5b067e61bc4"}}
            attach_response = self.api.api_post(
                             '/servers/%s/os-volume_attachments' % (server_id),
                             volume_attachment).body['volumeAttachment']
            self.assertTrue(mock_attach_create.called)
            mock_attachment_complete.assert_called_once_with(
                mock.ANY, uuids.volume)
            self.assertIsNone(attach_response['device'])

        # Test detach volume
        with test.nested(mock.patch.object(objects.BlockDeviceMappingList,
                                           'get_by_instance_uuid'),
                         mock.patch.object(compute_api.API,
                                           '_local_cleanup_bdm_volumes')
                         ) as (mock_get_bdms, mock_clean_vols):

            mock_get_bdms.return_value = fake_bdms
            attachment_id = mock_get_bdms.return_value[0]['volume_id']
            self.api.api_delete('/servers/%s/os-volume_attachments/%s' %
                            (server_id, attachment_id))
            self.assertTrue(mock_clean_vols.called)

        self._delete_server(found_server)


class ServerTestV269(integrated_helpers._IntegratedTestBase):
    api_major_version = 'v2.1'
    NUMBER_OF_CELLS = 3

    def setUp(self):
        super(ServerTestV269, self).setUp()
        self.api.microversion = '2.69'

        self.ctxt = context.get_admin_context()
        self.project_id = self.api.project_id
        self.cells = objects.CellMappingList.get_all(self.ctxt)
        self.down_cell_insts = []
        self.up_cell_insts = []
        self.down_cell_mappings = objects.CellMappingList()
        flavor = objects.Flavor(id=1, name='flavor1',
                                memory_mb=256, vcpus=1,
                                root_gb=1, ephemeral_gb=1,
                                flavorid='1',
                                swap=0, rxtx_factor=1.0,
                                vcpu_weight=1,
                                disabled=False,
                                is_public=True,
                                extra_specs={},
                                projects=[])
        _info_cache = objects.InstanceInfoCache(context)
        objects.InstanceInfoCache._from_db_object(context, _info_cache,
            test_instance_info_cache.fake_info_cache)
        # cell1 and cell2 will be the down cells while
        # cell0 and cell3 will be the up cells.
        down_cell_names = ['cell1', 'cell2']
        for cell in self.cells:
            # create 2 instances and their mappings in all the 4 cells
            for i in range(2):
                with context.target_cell(self.ctxt, cell) as cctxt:
                    inst = objects.Instance(
                        context=cctxt,
                        project_id=self.project_id,
                        user_id=self.project_id,
                        instance_type_id=flavor.id,
                        hostname='%s-inst%i' % (cell.name, i),
                        flavor=flavor,
                        info_cache=_info_cache,
                        display_name='server-test')
                    inst.create()
                im = objects.InstanceMapping(context=self.ctxt,
                                             instance_uuid=inst.uuid,
                                             cell_mapping=cell,
                                             project_id=self.project_id,
                                             queued_for_delete=False)
                im.create()
                if cell.name in down_cell_names:
                    self.down_cell_insts.append(inst.uuid)
                else:
                    self.up_cell_insts.append(inst.uuid)
            # In cell1 and cell3 add a third instance in a different project
            # to show the --all-tenants case.
            if cell.name == 'cell1' or cell.name == 'cell3':
                with context.target_cell(self.ctxt, cell) as cctxt:
                    inst = objects.Instance(
                        context=cctxt,
                        project_id='faker',
                        user_id='faker',
                        instance_type_id=flavor.id,
                        hostname='%s-inst%i' % (cell.name, 3),
                        flavor=flavor,
                        info_cache=_info_cache,
                        display_name='server-test')
                    inst.create()
                im = objects.InstanceMapping(context=self.ctxt,
                                             instance_uuid=inst.uuid,
                                             cell_mapping=cell,
                                             project_id='faker',
                                             queued_for_delete=False)
                im.create()
            if cell.name in down_cell_names:
                self.down_cell_mappings.objects.append(cell)
        self.useFixture(nova_fixtures.DownCellFixture(self.down_cell_mappings))

    def test_get_servers_with_down_cells(self):
        servers = self.api.get_servers(detail=False)
        # 4 servers from the up cells and 4 servers from the down cells
        self.assertEqual(8, len(servers))
        for server in servers:
            if 'name' not in server:
                # server is in the down cell.
                self.assertEqual('UNKNOWN', server['status'])
                self.assertIn(server['id'], self.down_cell_insts)
                self.assertIn('links', server)
                # the partial construct will have only the above 3 keys
                self.assertEqual(3, len(server))
            else:
                # server in up cell
                self.assertIn(server['id'], self.up_cell_insts)
                # has all the keys
                self.assertEqual(server['name'], 'server-test')
                self.assertIn('links', server)

    def test_get_servers_detail_with_down_cells(self):
        servers = self.api.get_servers()
        # 4 servers from the up cells and 4 servers from the down cells
        self.assertEqual(8, len(servers))
        for server in servers:
            if 'user_id' not in server:
                # server is in the down cell.
                self.assertEqual('UNKNOWN', server['status'])
                self.assertIn(server['id'], self.down_cell_insts)
                # the partial construct will only have 5 keys: created,
                # tenant_id, status, id and links. security_groups should be
                # present too but isn't since we haven't created a network
                # interface
                self.assertEqual(5, len(server))
            else:
                # server in up cell
                self.assertIn(server['id'], self.up_cell_insts)
                # has all the keys
                self.assertEqual(server['user_id'], self.project_id)
                self.assertIn('image', server)

    def test_get_servers_detail_limits_with_down_cells(self):
        servers = self.api.get_servers(search_opts={'limit': 5})
        # 4 servers from the up cells since we skip down cell
        # results by default for paging.
        self.assertEqual(4, len(servers), servers)
        for server in servers:
            # server in up cell
            self.assertIn(server['id'], self.up_cell_insts)
            # has all the keys
            self.assertEqual(server['user_id'], self.project_id)
            self.assertIn('image', server)

    def test_get_servers_detail_limits_with_down_cells_the_500_gift(self):
        self.flags(list_records_by_skipping_down_cells=False, group='api')
        # We get an API error with a 500 response code since the
        # list_records_by_skipping_down_cells config option is False.
        exp = self.assertRaises(client.OpenStackApiException,
                                self.api.get_servers,
                                search_opts={'limit': 5})
        self.assertEqual(500, exp.response.status_code)
        self.assertIn('NovaException', str(exp))

    def test_get_servers_detail_marker_in_down_cells(self):
        marker = self.down_cell_insts[2]
        # It will fail with a 500 if the marker is in the down cell.
        exp = self.assertRaises(client.OpenStackApiException,
                                self.api.get_servers,
                                search_opts={'marker': marker})
        self.assertEqual(500, exp.response.status_code)
        self.assertIn('oslo_db.exception.DBError', str(exp))

    def test_get_servers_detail_marker_sorting(self):
        marker = self.up_cell_insts[1]
        # It will give the results from the up cell if
        # list_records_by_skipping_down_cells config option is True.
        servers = self.api.get_servers(search_opts={'marker': marker,
                                                    'sort_key': "created_at",
                                                    'sort_dir': "asc"})
        # since there are 4 servers from the up cells, when giving the
        # second instance as marker, sorted by creation time in ascending
        # third and fourth instances will be returned.
        self.assertEqual(2, len(servers))
        for server in servers:
            self.assertIn(
                server['id'], [self.up_cell_insts[2], self.up_cell_insts[3]])

    def test_get_servers_detail_non_admin_with_deleted_flag(self):
        # if list_records_by_skipping_down_cells config option is True
        # this deleted option should be ignored and the rest of the instances
        # from the up cells and the partial results from the down cells should
        # be returned.
        # Set the policy so we don't have permission to allow
        # all filters but are able to get server details.
        servers_rule = 'os_compute_api:servers:detail'
        extraspec_rule = 'os_compute_api:servers:allow_all_filters'
        self.policy.set_rules({
            extraspec_rule: 'rule:admin_api',
            servers_rule: '@'})
        servers = self.api.get_servers(search_opts={'deleted': True})
        # gets 4 results from up cells and 4 from down cells.
        self.assertEqual(8, len(servers))
        for server in servers:
            if "image" not in server:
                self.assertIn(server['id'], self.down_cell_insts)
            else:
                self.assertIn(server['id'], self.up_cell_insts)

    def test_get_servers_detail_filters(self):
        # We get the results only from the up cells, this ignoring the down
        # cells if list_records_by_skipping_down_cells config option is True.
        self.admin_api = self.api_fixture.admin_api
        self.admin_api.microversion = '2.69'
        servers = self.admin_api.get_servers(
            search_opts={'hostname': "cell3-inst0"})
        self.assertEqual(1, len(servers))
        self.assertEqual(self.up_cell_insts[2], servers[0]['id'])

    def test_get_servers_detail_all_tenants_with_down_cells(self):
        self.admin_api = self.api_fixture.admin_api
        self.admin_api.microversion = '2.69'
        servers = self.admin_api.get_servers(search_opts={'all_tenants': True})
        # 4 servers from the up cells and 4 servers from the down cells
        # plus the 2 instances from cell1 and cell3 which are in a different
        # project.
        self.assertEqual(10, len(servers))
        for server in servers:
            if 'user_id' not in server:
                # server is in the down cell.
                self.assertEqual('UNKNOWN', server['status'])
                if server['tenant_id'] != 'faker':
                    self.assertIn(server['id'], self.down_cell_insts)
                # the partial construct will only have 5 keys: created,
                # tenant_id, status, id and links. security_groups should be
                # present too but isn't since we haven't created a network
                # interface
                self.assertEqual(5, len(server))
            else:
                # server in up cell
                if server['tenant_id'] != 'faker':
                    self.assertIn(server['id'], self.up_cell_insts)
                    self.assertEqual(server['user_id'], self.project_id)
                self.assertIn('image', server)


class ServerRebuildTestCase(integrated_helpers._IntegratedTestBase):
    api_major_version = 'v2.1'
    # We have to cap the microversion at 2.38 because that's the max we
    # can use to update image metadata via our compute images proxy API.
    microversion = '2.38'

    def _disable_compute_for(self, server):
        # Refresh to get its host
        server = self.admin_api.get_server(server['id'])
        host = server['OS-EXT-SRV-ATTR:host']

        # Disable the service it is on
        self.admin_api.put_service(
            'disable', {'host': host, 'binary': 'nova-compute'})

    def test_rebuild_with_image_novalidhost(self):
        """Creates a server with an image that is valid for the single compute
        that we have. Then rebuilds the server, passing in an image with
        metadata that does not fit the single compute which should result in
        a NoValidHost error. The ImagePropertiesFilter filter is enabled by
        default so that should filter out the host based on the image meta.
        """

        self.compute2 = self.start_service('compute', host='host2')

        # We hard-code from a fake image since we can't get images
        # via the compute /images proxy API with microversion > 2.35.
        original_image_ref = '155d900f-4e14-4e4c-a73d-069cbf4541e6'
        server_req_body = {
            'server': {
                'imageRef': original_image_ref,
                'flavorRef': '1',   # m1.tiny from DefaultFlavorsFixture,
                'name': 'test_rebuild_with_image_novalidhost',
                # We don't care about networking for this test. This requires
                # microversion >= 2.37.
                'networks': 'none'
            }
        }
        server = self.api.post_server(server_req_body)
        self._wait_for_state_change(server, 'ACTIVE')

        # Disable the host we're on so ComputeFilter would have ruled it out
        # normally
        self._disable_compute_for(server)

        # Now update the image metadata to be something that won't work with
        # the fake compute driver we're using since the fake driver has an
        # "x86_64" architecture.
        rebuild_image_ref = self.glance.auto_disk_config_enabled_image['id']
        self.api.put_image_meta_key(
            rebuild_image_ref, 'hw_architecture', 'unicore32')
        # Now rebuild the server with that updated image and it should result
        # in a NoValidHost failure from the scheduler.
        rebuild_req_body = {
            'rebuild': {
                'imageRef': rebuild_image_ref
            }
        }
        # Since we're using CastAsCallFixture, the NoValidHost error
        # should actually come back to the API and result in a 500 error.
        # Normally the user would get a 202 response because nova-api RPC casts
        # to nova-conductor which RPC calls the scheduler which raises the
        # NoValidHost. We can mimic the end user way to figure out the failure
        # by looking for the failed 'rebuild' instance action event.
        self.api.api_post('/servers/%s/action' % server['id'],
                          rebuild_req_body, check_response_status=[500])
        # Look for the failed rebuild action.
        self._wait_for_action_fail_completion(
            server, instance_actions.REBUILD, 'rebuild_server')
        # Assert the server image_ref was rolled back on failure.
        server = self.api.get_server(server['id'])
        self.assertEqual(original_image_ref, server['image']['id'])

        # The server should be in ERROR state
        self.assertEqual('ERROR', server['status'])
        self.assertIn('No valid host', server['fault']['message'])

        # Rebuild it again with the same bad image to make sure it's rejected
        # again. Since we're using CastAsCallFixture here, there is no 202 from
        # the API, and the exception from conductor gets passed back through
        # the API.
        ex = self.assertRaises(
            client.OpenStackApiException, self.api.api_post,
            '/servers/%s/action' % server['id'], rebuild_req_body)
        self.assertIn('NoValidHost', str(ex))

    # A rebuild to the same host should never attempt a rebuild claim.
    @mock.patch('nova.compute.resource_tracker.ResourceTracker.rebuild_claim',
                new_callable=mock.NonCallableMock)
    def test_rebuild_with_new_image(self, mock_rebuild_claim):
        """Rebuilds a server with a different image which will run it through
        the scheduler to validate the image is still OK with the compute host
        that the instance is running on.

        Validates that additional resources are not allocated against the
        instance.host in Placement due to the rebuild on same host.
        """
        admin_api = self.api_fixture.admin_api
        admin_api.microversion = '2.53'

        def _get_provider_uuid_by_host(host):
            resp = admin_api.api_get(
                'os-hypervisors?hypervisor_hostname_pattern=%s' % host).body
            return resp['hypervisors'][0]['id']

        def _get_provider_usages(provider_uuid):
            return self.placement.get(
                '/resource_providers/%s/usages' % provider_uuid).body['usages']

        def _get_allocations_by_server_uuid(server_uuid):
            return self.placement.get(
                '/allocations/%s' % server_uuid).body['allocations']

        def _set_provider_inventory(rp_uuid, resource_class, inventory):
            # Get the resource provider generation for the inventory update.
            rp = self.placement.get(
                '/resource_providers/%s' % rp_uuid).body
            inventory['resource_provider_generation'] = rp['generation']
            return self.placement.put(
                '/resource_providers/%s/inventories/%s' %
                (rp_uuid, resource_class), inventory).body

        def assertFlavorMatchesAllocation(flavor, allocation):
            self.assertEqual(flavor['vcpus'], allocation['VCPU'])
            self.assertEqual(flavor['ram'], allocation['MEMORY_MB'])
            self.assertEqual(flavor['disk'], allocation['DISK_GB'])

        nodename = self.compute.manager._get_nodename(None)
        rp_uuid = _get_provider_uuid_by_host(nodename)
        # make sure we start with no usage on the compute node
        rp_usages = _get_provider_usages(rp_uuid)
        self.assertEqual({'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0}, rp_usages)

        server_req_body = {
            'server': {
                # We hard-code from a fake image since we can't get images
                # via the compute /images proxy API with microversion > 2.35.
                'imageRef': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
                'flavorRef': '1',   # m1.tiny from DefaultFlavorsFixture,
                'name': 'test_rebuild_with_new_image',
                # We don't care about networking for this test. This requires
                # microversion >= 2.37.
                'networks': 'none'
            }
        }
        server = self.api.post_server(server_req_body)
        self._wait_for_state_change(server, 'ACTIVE')

        flavor = self.api.api_get('/flavors/1').body['flavor']

        # make the compute node full and ensure rebuild still succeed
        _set_provider_inventory(rp_uuid, "VCPU", {"total": 1})

        # There should be usage for the server on the compute node now.
        rp_usages = _get_provider_usages(rp_uuid)
        assertFlavorMatchesAllocation(flavor, rp_usages)
        allocs = _get_allocations_by_server_uuid(server['id'])
        self.assertIn(rp_uuid, allocs)
        allocs = allocs[rp_uuid]['resources']
        assertFlavorMatchesAllocation(flavor, allocs)

        rebuild_image_ref = self.glance.auto_disk_config_enabled_image['id']
        # Now rebuild the server with a different image.
        rebuild_req_body = {
            'rebuild': {
                'imageRef': rebuild_image_ref
            }
        }
        self.api.api_post('/servers/%s/action' % server['id'],
                          rebuild_req_body)
        self._wait_for_server_parameter(
            server, {'OS-EXT-STS:task_state': None})

        # The usage and allocations should not have changed.
        rp_usages = _get_provider_usages(rp_uuid)
        assertFlavorMatchesAllocation(flavor, rp_usages)

        allocs = _get_allocations_by_server_uuid(server['id'])
        self.assertIn(rp_uuid, allocs)
        allocs = allocs[rp_uuid]['resources']
        assertFlavorMatchesAllocation(flavor, allocs)

    def test_volume_backed_rebuild_different_image(self):
        """Tests that trying to rebuild a volume-backed instance with a
        different image than what is in the root disk of the root volume
        will result in a 400 BadRequest error.
        """
        # First create our server as normal.
        server_req_body = {
            # There is no imageRef because this is boot from volume.
            'server': {
                'flavorRef': '1',  # m1.tiny from DefaultFlavorsFixture,
                'name': 'test_volume_backed_rebuild_different_image',
                # We don't care about networking for this test. This requires
                # microversion >= 2.37.
                'networks': 'none',
                'block_device_mapping_v2': [{
                    'boot_index': 0,
                    'uuid':
                    nova_fixtures.CinderFixture.IMAGE_BACKED_VOL,
                    'source_type': 'volume',
                    'destination_type': 'volume'
                }]
            }
        }
        server = self.api.post_server(server_req_body)
        server = self._wait_for_state_change(server, 'ACTIVE')
        # For a volume-backed server, the image ref will be an empty string
        # in the server response.
        self.assertEqual('', server['image'])

        # Now rebuild the server with a different image than was used to create
        # our fake volume.
        rebuild_image_ref = self.glance.auto_disk_config_enabled_image['id']
        rebuild_req_body = {
            'rebuild': {
                'imageRef': rebuild_image_ref
            }
        }
        resp = self.api.api_post('/servers/%s/action' % server['id'],
                                 rebuild_req_body, check_response_status=[400])
        # Assert that we failed because of the image change and not something
        # else.
        self.assertIn('Unable to rebuild with a different image for a '
                      'volume-backed server', str(resp))


class ServerRebuildTestCaseV293(integrated_helpers._IntegratedTestBase):
    api_major_version = 'v2.1'

    def setUp(self):
        super(ServerRebuildTestCaseV293, self).setUp()
        self.cinder = nova_fixtures.CinderFixture(self)
        self.useFixture(self.cinder)

    def _bfv_server(self):
        server_req_body = {
            # There is no imageRef because this is boot from volume.
            'server': {
                'flavorRef': '1',  # m1.tiny from DefaultFlavorsFixture,
                'name': 'test_volume_backed_rebuild_different_image',
                'networks': [],
                'block_device_mapping_v2': [{
                    'boot_index': 0,
                    'uuid':
                    nova_fixtures.CinderFixture.IMAGE_BACKED_VOL,
                    'source_type': 'volume',
                    'destination_type': 'volume'
                }]
            }
        }
        server = self.api.post_server(server_req_body)
        return self._wait_for_state_change(server, 'ACTIVE')

    def _test_rebuild(self, server):
        self.api.microversion = '2.93'
        # Now rebuild the server with a different image than was used to create
        # our fake volume.
        rebuild_image_ref = self.glance.auto_disk_config_enabled_image['id']
        rebuild_req_body = {'rebuild': {'imageRef': rebuild_image_ref}}

        with mock.patch.object(self.compute.manager.virtapi,
                               'wait_for_instance_event'):
            self.api.api_post('/servers/%s/action' % server['id'],
                              rebuild_req_body,
                              check_response_status=[202])

    def test_volume_backed_rebuild_root_v293(self):
        server = self._bfv_server()
        self._test_rebuild(server)

    def test_volume_backed_rebuild_root_create_failed(self):
        server = self._bfv_server()
        error = cinder_exception.ClientException(code=500)
        with mock.patch.object(volume.cinder.API, 'attachment_create',
                               side_effect=error):
            # We expect this to fail because we are doing cast-as-call
            self.assertRaises(client.OpenStackApiException,
                              self._test_rebuild, server)
            server = self.api.get_server(server['id'])
            self.assertIn('Failed to rebuild volume backed instance',
                          server['fault']['message'])
            self.assertEqual('ERROR', server['status'])

    def test_volume_backed_rebuild_root_instance_deleted(self):
        server = self._bfv_server()
        error = exception.InstanceNotFound(instance_id=server['id'])
        with mock.patch.object(self.compute.manager, '_detach_root_volume',
                               side_effect=error):
            # We expect this to fail because we are doing cast-as-call
            self.assertRaises(client.OpenStackApiException,
                              self._test_rebuild, server)
            server = self.api.get_server(server['id'])
            self.assertIn('Failed to rebuild volume backed instance',
                          server['fault']['message'])
            self.assertEqual('ERROR', server['status'])

    def test_volume_backed_rebuild_root_delete_old_failed(self):
        server = self._bfv_server()
        error = cinder_exception.ClientException(code=500)
        with mock.patch.object(volume.cinder.API, 'attachment_delete',
                               side_effect=error):
            # We expect this to fail because we are doing cast-as-call
            self.assertRaises(client.OpenStackApiException,
                              self._test_rebuild, server)
            server = self.api.get_server(server['id'])
            self.assertIn('Failed to rebuild volume backed instance',
                          server['fault']['message'])
            self.assertEqual('ERROR', server['status'])


class ServersTestV280(integrated_helpers._IntegratedTestBase):
    api_major_version = 'v2.1'

    def setUp(self):
        super(ServersTestV280, self).setUp()
        self.api = self.api_fixture.api
        self.admin_api = self.api_fixture.admin_api

        self.api.microversion = '2.80'
        self.admin_api.microversion = '2.80'

    def test_get_migrations_after_cold_migrate_server_in_same_project(
            self):
        # Create a server by non-admin
        server = self.api.post_server({
            'server': {
                'flavorRef': 1,
                'imageRef': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
                'name': 'migrate-server-test',
                'networks': 'none'
            }})
        server_id = server['id']

        # Check it's there
        found_server = self.api.get_server(server_id)
        self.assertEqual(server_id, found_server['id'])

        self.start_service('compute', host='host2')

        post = {'migrate': {}}
        self.admin_api.post_server_action(server_id, post)

        # Get the migration records by admin
        migrations = self.admin_api.get_migrations(
            user_id=self.admin_api.auth_user)
        self.assertEqual(1, len(migrations))
        self.assertEqual(server_id, migrations[0]['instance_uuid'])

        # Get the migration records by non-admin
        migrations = self.admin_api.get_migrations(
            user_id=self.api.auth_user)
        self.assertEqual([], migrations)

    def test_get_migrations_after_live_migrate_server_in_different_project(
            self):
        # Create a server by non-admin
        server = self.api.post_server({
            'server': {
                'flavorRef': 1,
                'imageRef': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
                'name': 'migrate-server-test',
                'networks': 'none'
            }})
        server_id = server['id']

        # Check it's there
        found_server = self.api.get_server(server_id)
        self.assertEqual(server_id, found_server['id'])

        server = self._wait_for_state_change(found_server, 'BUILD')

        self.start_service('compute', host='host2')

        project_id_1 = '4906260553374bf0a5d566543b320516'
        project_id_2 = 'c850298c1b6b4796a8f197ac310b2469'
        new_admin_api = self.api_fixture.alternative_admin_api
        new_admin_api.project_id = project_id_1
        new_admin_api.microversion = '2.80'

        post = {
            'os-migrateLive': {
                'host': 'host2',
                'block_migration': True
            }
        }
        new_admin_api.post_server_action(server_id, post)
        # Get the migration records
        migrations = new_admin_api.get_migrations(project_id=project_id_1)
        self.assertEqual(1, len(migrations))
        self.assertEqual(server_id, migrations[0]['instance_uuid'])

        # Get the migration records by not exist project_id
        migrations = new_admin_api.get_migrations(project_id=project_id_2)
        self.assertEqual([], migrations)


class ServerMovingTests(integrated_helpers.ProviderUsageBaseTestCase):
    """Tests moving servers while checking the resource allocations and usages

    These tests use two compute hosts. Boot a server on one of them then try to
    move the server to the other. At every step resource allocation of the
    server and the resource usages of the computes are queried from placement
    API and asserted.
    """

    REQUIRES_LOCKING = True
    # NOTE(danms): The test defaults to using SmallFakeDriver,
    # which only has one vcpu, which can't take the doubled allocation
    # we're now giving it. So, use the bigger MediumFakeDriver here.
    compute_driver = 'fake.MediumFakeDriver'

    def setUp(self):
        super(ServerMovingTests, self).setUp()

        self.compute1 = self._start_compute(host='host1')
        self.compute2 = self._start_compute(host='host2')

        flavors = self.api.get_flavors()
        self.flavor1 = flavors[0]
        self.flavor2 = flavors[1]
        # create flavor3 which has less MEMORY_MB but more DISK_GB than flavor2
        flavor_body = {'flavor':
                           {'name': 'test_flavor3',
                            'ram': int(self.flavor2['ram'] / 2),
                            'vcpus': 1,
                            'disk': self.flavor2['disk'] * 2,
                            'id': 'a22d5517-147c-4147-a0d1-e698df5cd4e3'
                            }}

        self.flavor3 = self.api.post_flavor(flavor_body)

    def _other_hostname(self, host):
        other_host = {'host1': 'host2',
                      'host2': 'host1'}
        return other_host[host]

    def _run_periodics(self):
        # NOTE(jaypipes): We always run periodics in the same order: first on
        # compute1, then on compute2. However, we want to test scenarios when
        # the periodics run at different times during mover operations. This is
        # why we have the "reverse" tests which simply switch the source and
        # dest host while keeping the order in which we run the
        # periodics. This effectively allows us to test the matrix of timing
        # scenarios during move operations.
        ctx = context.get_admin_context()
        LOG.info('Running periodic for compute1 (%s)',
            self.compute1.manager.host)
        self.compute1.manager.update_available_resource(ctx)
        LOG.info('Running periodic for compute2 (%s)',
            self.compute2.manager.host)
        self.compute2.manager.update_available_resource(ctx)
        LOG.info('Finished with periodics')

    def test_resize_revert(self):
        self._test_resize_revert(dest_hostname='host1')

    def test_resize_revert_reverse(self):
        self._test_resize_revert(dest_hostname='host2')

    def test_resize_confirm(self):
        self._test_resize_confirm(dest_hostname='host1')

    def test_resize_confirm_reverse(self):
        self._test_resize_confirm(dest_hostname='host2')

    def test_migration_confirm_resize_error(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host

        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(self.flavor1,
                                                  source_hostname)

        self._move_and_check_allocations(
            server, request={'migrate': None}, old_flavor=self.flavor1,
            new_flavor=self.flavor1, source_rp_uuid=source_rp_uuid,
            dest_rp_uuid=dest_rp_uuid)

        # Mock failure
        def fake_confirm_migration(context, migration, instance, network_info):
            raise exception.MigrationPreCheckError(
                reason='test_migration_confirm_resize_error')

        with mock.patch('nova.virt.fake.FakeDriver.'
                        'confirm_migration',
                        side_effect=fake_confirm_migration):

            # Confirm the migration/resize and check the usages
            post = {'confirmResize': None}
            self.api.post_server_action(
                server['id'], post, check_response_status=[204])
            server = self._wait_for_state_change(server, 'ERROR')

        # After confirming and error, we should have an allocation only on the
        # destination host

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)
        self.assertRequestMatchesUsage({'VCPU': 0,
                                        'MEMORY_MB': 0,
                                        'DISK_GB': 0}, source_rp_uuid)
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           dest_rp_uuid)

        self._run_periodics()

        # Check we're still accurate after running the periodics

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)
        self.assertRequestMatchesUsage({'VCPU': 0,
                                        'MEMORY_MB': 0,
                                        'DISK_GB': 0}, source_rp_uuid)
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def _test_resize_revert(self, dest_hostname):
        source_hostname = self._other_hostname(dest_hostname)
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(self.flavor1,
            source_hostname)

        self._resize_and_check_allocations(server, self.flavor1, self.flavor2,
            source_rp_uuid, dest_rp_uuid)

        # Revert the resize and check the usages
        post = {'revertResize': None}
        self.api.post_server_action(server['id'], post)
        self._wait_for_state_change(server, 'ACTIVE')

        # Make sure the RequestSpec.flavor matches the original flavor.
        ctxt = context.get_admin_context()
        reqspec = objects.RequestSpec.get_by_instance_uuid(ctxt, server['id'])
        self.assertEqual(self.flavor1['id'], reqspec.flavor.flavorid)

        self._run_periodics()

        # the original host expected to have the old resource allocation
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertRequestMatchesUsage({'VCPU': 0,
                                        'MEMORY_MB': 0,
                                        'DISK_GB': 0}, dest_rp_uuid)

        # Check that the server only allocates resource from the original host
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def _test_resize_confirm(self, dest_hostname):
        source_hostname = self._other_hostname(dest_hostname)
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(self.flavor1,
            source_hostname)

        self._resize_and_check_allocations(server, self.flavor1, self.flavor2,
            source_rp_uuid, dest_rp_uuid)

        # Confirm the resize and check the usages
        self._confirm_resize(server)

        # After confirming, we should have an allocation only on the
        # destination host

        # The target host usage should be according to the new flavor
        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor2)
        self.assertRequestMatchesUsage({'VCPU': 0,
                                        'MEMORY_MB': 0,
                                        'DISK_GB': 0}, source_rp_uuid)

        # and the target host allocation should be according to the new flavor
        self.assertFlavorMatchesAllocation(self.flavor2, server['id'],
                                           dest_rp_uuid)

        self._run_periodics()

        # Check we're still accurate after running the periodics

        # and the target host usage should be according to the new flavor
        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor2)
        self.assertRequestMatchesUsage({'VCPU': 0,
                                        'MEMORY_MB': 0,
                                        'DISK_GB': 0}, source_rp_uuid)

        # and the server allocates only from the target host
        self.assertFlavorMatchesAllocation(self.flavor2, server['id'],
                                           dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_resize_revert_same_host(self):
        # make sure that the test only uses a single host
        compute2_service_id = self.admin_api.get_services(
            host=self.compute2.host, binary='nova-compute')[0]['id']
        self.admin_api.put_service(compute2_service_id, {'status': 'disabled'})

        hostname = self.compute1.manager.host
        rp_uuid = self._get_provider_uuid_by_host(hostname)

        server = self._boot_and_check_allocations(self.flavor2, hostname)

        self._resize_to_same_host_and_check_allocations(
            server, self.flavor2, self.flavor3, rp_uuid)

        # Revert the resize and check the usages
        post = {'revertResize': None}
        self.api.post_server_action(server['id'], post)
        self._wait_for_state_change(server, 'ACTIVE')

        self._run_periodics()

        # after revert only allocations due to the old flavor should remain
        self.assertFlavorMatchesUsage(rp_uuid, self.flavor2)

        self.assertFlavorMatchesAllocation(self.flavor2, server['id'],
                                           rp_uuid)

        self._delete_and_check_allocations(server)

    def test_resize_confirm_same_host(self):
        # make sure that the test only uses a single host
        compute2_service_id = self.admin_api.get_services(
            host=self.compute2.host, binary='nova-compute')[0]['id']
        self.admin_api.put_service(compute2_service_id, {'status': 'disabled'})

        hostname = self.compute1.manager.host
        rp_uuid = self._get_provider_uuid_by_host(hostname)

        server = self._boot_and_check_allocations(self.flavor2, hostname)

        self._resize_to_same_host_and_check_allocations(
            server, self.flavor2, self.flavor3, rp_uuid)

        # Confirm the resize and check the usages
        self._confirm_resize(server)

        self._run_periodics()

        # after confirm only allocations due to the new flavor should remain
        self.assertFlavorMatchesUsage(rp_uuid, self.flavor3)

        self.assertFlavorMatchesAllocation(self.flavor3, server['id'],
                                           rp_uuid)

        self._delete_and_check_allocations(server)

    def test_resize_not_enough_resource(self):
        # Try to resize to a flavor that requests more VCPU than what the
        # compute hosts has available and expect the resize to fail

        flavor_body = {'flavor':
                           {'name': 'test_too_big_flavor',
                            'ram': 1024,
                            'vcpus': fake.MediumFakeDriver.vcpus + 1,
                            'disk': 20,
                            }}

        big_flavor = self.api.post_flavor(flavor_body)

        dest_hostname = self.compute2.host
        source_hostname = self._other_hostname(dest_hostname)
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        self.flags(allow_resize_to_same_host=False)
        resize_req = {
            'resize': {
                'flavorRef': big_flavor['id']
            }
        }

        self.api.post_server_action(
            server['id'], resize_req, check_response_status=[202])
        event = self._assert_resize_migrate_action_fail(
            server, instance_actions.RESIZE, 'NoValidHost')
        self.assertIn('details', event)
        # This test case works in microversion 2.84.
        self.assertIn('No valid host was found', event['details'])
        server = self.admin_api.get_server(server['id'])
        self.assertEqual(source_hostname, server['OS-EXT-SRV-ATTR:host'])
        # The server is still ACTIVE and thus there is no fault message.
        self.assertEqual('ACTIVE', server['status'])
        self.assertNotIn('fault', server)

        # only the source host shall have usages after the failed resize
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        # Check that the other provider has no usage
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        # Check that the server only allocates resource from the host it is
        # booted on
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_resize_delete_while_verify(self):
        """Test scenario where the server is deleted while in the
        VERIFY_RESIZE state and ensures the allocations are properly
        cleaned up from the source and target compute node resource providers.
        The _confirm_resize_on_deleting() method in the API is actually
        responsible for making sure the migration-based allocations get
        cleaned up by confirming the resize on the source host before deleting
        the server from the target host.
        """
        dest_hostname = 'host2'
        source_hostname = self._other_hostname(dest_hostname)
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(self.flavor1,
                                                  source_hostname)

        self._resize_and_check_allocations(server, self.flavor1, self.flavor2,
                                           source_rp_uuid, dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_resize_confirm_assert_hypervisor_usage_no_periodics(self):
        """Resize confirm test for bug 1818914 to make sure the tracked
        resource usage in the os-hypervisors API (not placement) is as
        expected during a confirmed resize. This intentionally does not
        use _test_resize_confirm in order to avoid running periodics.
        """
        # There should be no usage from a server on either hypervisor.
        source_rp_uuid = self._get_provider_uuid_by_host('host1')
        dest_rp_uuid = self._get_provider_uuid_by_host('host2')
        no_usage = {'vcpus': 0, 'disk': 0, 'ram': 0}
        for rp_uuid in (source_rp_uuid, dest_rp_uuid):
            self.assert_hypervisor_usage(
                rp_uuid, no_usage, volume_backed=False)

        # Create the server and wait for it to be ACTIVE.
        server = self._boot_and_check_allocations(self.flavor1, 'host1')

        # There should be resource usage for flavor1 on the source host.
        self.assert_hypervisor_usage(
            source_rp_uuid, self.flavor1, volume_backed=False)
        # And still no usage on the dest host.
        self.assert_hypervisor_usage(
            dest_rp_uuid, no_usage, volume_backed=False)

        # Resize the server to flavor2 and wait for VERIFY_RESIZE.
        self.flags(allow_resize_to_same_host=False)
        resize_req = {
            'resize': {
                'flavorRef': self.flavor2['id']
            }
        }
        self.api.post_server_action(server['id'], resize_req)
        self._wait_for_state_change(server, 'VERIFY_RESIZE')

        # There should be resource usage for flavor1 on the source host.
        self.assert_hypervisor_usage(
            source_rp_uuid, self.flavor1, volume_backed=False)
        # And resource usage for flavor2 on the target host.
        self.assert_hypervisor_usage(
            dest_rp_uuid, self.flavor2, volume_backed=False)

        # Now confirm the resize and check hypervisor usage again.
        self._confirm_resize(server)

        # There should no resource usage for flavor1 on the source host.
        self.assert_hypervisor_usage(
            source_rp_uuid, no_usage, volume_backed=False)
        # And resource usage for flavor2 should still be on the target host.
        self.assert_hypervisor_usage(
            dest_rp_uuid, self.flavor2, volume_backed=False)

        # Run periodics and make sure usage is still as expected.
        self._run_periodics()
        self.assert_hypervisor_usage(
            source_rp_uuid, no_usage, volume_backed=False)
        self.assert_hypervisor_usage(
            dest_rp_uuid, self.flavor2, volume_backed=False)

    def test_evacuate_with_no_compute(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        # Disable compute service on destination host
        compute2_service_id = self.admin_api.get_services(
            host=dest_hostname, binary='nova-compute')[0]['id']
        self.admin_api.put_service(compute2_service_id, {'status': 'disabled'})

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        # Force source compute down
        source_compute_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']
        self.compute1.stop()
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        # Initiate evacuation
        # There is no other host to evacuate to so the rebuild should put the
        # VM to ERROR state, but it should remain on source compute
        server = self._evacuate_server(
            server, expected_state='ERROR', expected_host=source_hostname,
            expected_migration_status='error')

        self.notifier.wait_for_versioned_notifications(
            'compute_task.rebuild_server.error')
        self._run_periodics()

        # Check migrations
        migrations = self.api.get_migrations()
        self.assertEqual(1, len(migrations))
        self.assertEqual('evacuation', migrations[0]['migration_type'])
        self.assertEqual(server['id'], migrations[0]['instance_uuid'])
        self.assertEqual(source_hostname, migrations[0]['source_compute'])
        self.assertEqual('error', migrations[0]['status'])

        # Restart source host
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'false'})
        self.compute1.start()

        self._run_periodics()

        # Check allocation and usages: should only use resources on source host
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)
        zero_usage = {'VCPU': 0, 'DISK_GB': 0, 'MEMORY_MB': 0}
        self.assertRequestMatchesUsage(zero_usage, dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_migrate_no_valid_host(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        dest_compute_id = self.admin_api.get_services(
            host=dest_hostname, binary='nova-compute')[0]['id']
        self.compute2.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            dest_compute_id, {'forced_down': 'true'})

        # migrate the server
        post = {'migrate': None}
        self.api.post_server_action(server['id'], post)
        self._assert_resize_migrate_action_fail(
            server, instance_actions.MIGRATE, 'NoValidHost')
        expected_params = {'OS-EXT-SRV-ATTR:host': source_hostname,
                           'status': 'ACTIVE'}
        self._wait_for_server_parameter(server, expected_params)

        self._run_periodics()

        # Expect to have allocation only on source_host
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)
        zero_usage = {'VCPU': 0, 'DISK_GB': 0, 'MEMORY_MB': 0}
        self.assertRequestMatchesUsage(zero_usage, dest_rp_uuid)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def _test_evacuate(self, keep_hypervisor_state):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        source_compute_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']

        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        # evacuate the server
        server = self._evacuate_server(server, expected_host=dest_hostname)

        # Expect to have allocation and usages on both computes as the
        # source compute is still down
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        self._check_allocation_during_evacuate(
            self.flavor1, server['id'], source_rp_uuid, dest_rp_uuid)

        # restart the source compute
        self.compute1 = self.restart_compute_service(
            self.compute1, keep_hypervisor_state=keep_hypervisor_state)

        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'false'})

        source_usages = self._get_provider_usages(source_rp_uuid)
        self.assertEqual({'VCPU': 0,
                          'MEMORY_MB': 0,
                          'DISK_GB': 0},
                         source_usages)

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_evacuate_instance_kept_on_the_hypervisor(self):
        self._test_evacuate(keep_hypervisor_state=True)

    def test_evacuate_clean_hypervisor(self):
        self._test_evacuate(keep_hypervisor_state=False)

    def _test_evacuate_forced_host(self, keep_hypervisor_state):
        """Evacuating a server with a forced host bypasses the scheduler
        which means conductor has to create the allocations against the
        destination node. This test recreates the scenarios and asserts
        the allocations on the source and destination nodes are as expected.
        """
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host

        # the ability to force evacuate a server is removed entirely in 2.68
        self.api.microversion = '2.67'

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        source_compute_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']

        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        # evacuate the server and force the destination host which bypasses
        # the scheduler

        post = {
            'host': dest_hostname,
            'force': True
        }

        server = self._evacuate_server(
            server, extra_post_args=post, expected_host=dest_hostname)

        # Run the periodics to show those don't modify allocations.
        self._run_periodics()

        # Expect to have allocation and usages on both computes as the
        # source compute is still down
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        self._check_allocation_during_evacuate(
            self.flavor1, server['id'], source_rp_uuid, dest_rp_uuid)

        # restart the source compute
        self.compute1 = self.restart_compute_service(
            self.compute1, keep_hypervisor_state=keep_hypervisor_state)
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'false'})

        # Run the periodics again to show they don't change anything.
        self._run_periodics()

        # When the source node starts up, the instance has moved so the
        # ResourceTracker should cleanup allocations for the source node.
        source_usages = self._get_provider_usages(source_rp_uuid)
        self.assertEqual(
            {'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0}, source_usages)

        # The usages/allocations should still exist on the destination node
        # after the source node starts back up.
        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_evacuate_forced_host_instance_kept_on_the_hypervisor(self):
        self._test_evacuate_forced_host(keep_hypervisor_state=True)

    def test_evacuate_forced_host_clean_hypervisor(self):
        self._test_evacuate_forced_host(keep_hypervisor_state=False)

    def test_evacuate_forced_host_v268(self):
        """Evacuating a server with a forced host was removed in API
        microversion 2.68. This test ensures that the request is rejected.
        """
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        # evacuate the server and force the destination host which bypasses
        # the scheduler
        post = {
            'evacuate': {
                'host': dest_hostname,
                'force': True
            }
        }
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               server['id'], post)
        self.assertIn("'force' was unexpected", str(ex))

    # NOTE(gibi): there is a similar test in SchedulerOnlyChecksTargetTest but
    # we want this test here as well because ServerMovingTest is a parent class
    # of multiple test classes that run this test case with different compute
    # node setups.
    def test_evacuate_host_specified_but_not_forced(self):
        """Evacuating a server with a host but using the scheduler to create
        the allocations against the destination node. This test recreates the
        scenarios and asserts the allocations on the source and destination
        nodes are as expected.
        """
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        source_compute_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']

        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        # evacuate the server specify the target but do not force the
        # destination host to use the scheduler to validate the target host
        post = {
            'host': dest_hostname
        }

        server = self._evacuate_server(
            server, extra_post_args=post, expected_host=dest_hostname)

        # Run the periodics to show those don't modify allocations.
        self._run_periodics()

        # Expect to have allocation and usages on both computes as the
        # source compute is still down
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        self._check_allocation_during_evacuate(
            self.flavor1, server['id'], source_rp_uuid, dest_rp_uuid)

        # restart the source compute
        self.compute1 = self.restart_compute_service(self.compute1)
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'false'})

        # Run the periodics again to show they don't change anything.
        self._run_periodics()

        # When the source node starts up, the instance has moved so the
        # ResourceTracker should cleanup allocations for the source node.
        source_usages = self._get_provider_usages(source_rp_uuid)
        self.assertEqual(
            {'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0}, source_usages)

        # The usages/allocations should still exist on the destination node
        # after the source node starts back up.
        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def _test_evacuate_claim_on_dest_fails(self, keep_hypervisor_state):
        """Tests that the allocations on the destination node are cleaned up
        when the rebuild move claim fails due to insufficient resources.
        """
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        source_compute_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']

        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        # NOTE(mriedem): This isn't great, and I'd like to fake out the driver
        # to make the claim fail, by doing something like returning a too high
        # memory_mb overhead, but the limits dict passed to the claim is empty
        # so the claim test is considering it as unlimited and never actually
        # performs a claim test.
        def fake_move_claim(*args, **kwargs):
            # Assert the destination node allocation exists.
            self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)
            raise exception.ComputeResourcesUnavailable(
                    reason='test_evacuate_claim_on_dest_fails')

        with mock.patch('nova.compute.claims.MoveClaim', fake_move_claim):
            # evacuate the server
            # the migration will fail on the dest node and the instance will
            # stay ACTIVE and task_state will be set to None.
            server = self._evacuate_server(
                server, expected_task_state=None,
                expected_migration_status='failed')

        # Run the periodics to show those don't modify allocations.
        self._run_periodics()

        # The allocation should still exist on the source node since it's
        # still down, and the allocation on the destination node should be
        # cleaned up.
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        # restart the source compute
        self.compute1 = self.restart_compute_service(
            self.compute1, keep_hypervisor_state=keep_hypervisor_state)
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'false'})

        # Run the periodics again to show they don't change anything.
        self._run_periodics()

        # The source compute shouldn't have cleaned up the allocation for
        # itself since the instance didn't move.
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

    def test_evacuate_claim_on_dest_fails_instance_kept_on_the_hypervisor(
            self):
        self._test_evacuate_claim_on_dest_fails(keep_hypervisor_state=True)

    def test_evacuate_claim_on_dest_fails_clean_hypervisor(self):
        self._test_evacuate_claim_on_dest_fails(keep_hypervisor_state=False)

    def _test_evacuate_rebuild_on_dest_fails(self, keep_hypervisor_state):
        """Tests that the allocations on the destination node are cleaned up
        automatically when the claim is made but the actual rebuild
        via the driver fails.

        """
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        source_compute_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']

        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        def fake_rebuild(*args, **kwargs):
            # Assert the destination node allocation exists.
            self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)
            raise test.TestingException('test_evacuate_rebuild_on_dest_fails')

        with mock.patch.object(
                self.compute2.driver, 'rebuild', fake_rebuild):
            # evacuate the server
            # the migration will fail on the dest node and the instance will
            # go into error state
            server = self._evacuate_server(
                server, expected_state='ERROR',
                expected_migration_status='failed')

        # Run the periodics to show those don't modify allocations.
        self._run_periodics()

        # The allocation should still exist on the source node since it's
        # still down, and the allocation on the destination node should be
        # cleaned up.
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        # restart the source compute
        self.compute1 = self.restart_compute_service(
            self.compute1, keep_hypervisor_state=keep_hypervisor_state)
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'false'})

        # Run the periodics again to show they don't change anything.
        self._run_periodics()

        # The source compute shouldn't have cleaned up the allocation for
        # itself since the instance didn't move.
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

    def test_evacuate_rebuild_on_dest_fails_instance_kept_on_the_hypervisor(
            self):
        self._test_evacuate_rebuild_on_dest_fails(keep_hypervisor_state=True)

    def test_evacuate_rebuild_on_dest_fails_clean_hypervisor(self):
        self._test_evacuate_rebuild_on_dest_fails(keep_hypervisor_state=False)

    def _boot_then_shelve_and_check_allocations(self, hostname, rp_uuid):
        # avoid automatic shelve offloading
        self.flags(shelved_offload_time=-1)
        server = self._boot_and_check_allocations(
            self.flavor1, hostname)
        req = {
            'shelve': {}
        }
        self.api.post_server_action(server['id'], req)
        self._wait_for_state_change(server, 'SHELVED')
        # the host should maintain the existing allocation for this instance
        # while the instance is shelved
        self.assertFlavorMatchesUsage(rp_uuid, self.flavor1)
        # Check that the server only allocates resource from the host it is
        # booted on
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           rp_uuid)
        return server

    def test_shelve_unshelve(self):
        source_hostname = self.compute1.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        server = self._boot_then_shelve_and_check_allocations(
            source_hostname, source_rp_uuid)

        req = {
            'unshelve': None
        }
        self.api.post_server_action(server['id'], req)
        self._wait_for_state_change(server, 'ACTIVE')

        # the host should have resource usage as the instance is ACTIVE
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        # Check that the server only allocates resource from the host it is
        # booted on
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_shelve_unshelve_to_host(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = \
            self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_then_shelve_and_check_allocations(
            source_hostname, source_rp_uuid)

        self._shelve_offload_and_check_allocations(server, source_rp_uuid)

        req = {
            'unshelve': {'host': dest_hostname}
        }

        self.api.post_server_action(server['id'], req)
        self._wait_for_server_parameter(
            server, {'OS-EXT-SRV-ATTR:host': dest_hostname, 'status': 'ACTIVE'}
        )

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        # the server has an allocation on only the dest node
        self.assertFlavorMatchesAllocation(
                self.flavor1, server['id'], dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_shelve_unshelve_to_host_instance_not_offloaded(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)

        server = self._boot_then_shelve_and_check_allocations(
            source_hostname, source_rp_uuid)

        req = {
            'unshelve': {'host': dest_hostname}
        }

        ex = self.assertRaises(
                client.OpenStackApiException,
                self.api.post_server_action,
                server['id'], req
                )
        self.assertEqual(409, ex.response.status_code)
        self.assertIn(
                "The server status must be SHELVED_OFFLOADED",
                ex.response.text)

    def _shelve_offload_and_check_allocations(self, server, source_rp_uuid):
        req = {
            'shelveOffload': {}
        }
        self.api.post_server_action(server['id'], req)
        self._wait_for_server_parameter(server, {'status': 'SHELVED_OFFLOADED',
                               'OS-EXT-SRV-ATTR:host': None,
                               'OS-EXT-AZ:availability_zone': ''})
        source_usages = self._get_provider_usages(source_rp_uuid)
        self.assertEqual({'VCPU': 0,
                          'MEMORY_MB': 0,
                          'DISK_GB': 0},
                         source_usages)

        allocations = self._get_allocations_by_server_uuid(server['id'])
        self.assertEqual(0, len(allocations))

    def test_shelve_offload_unshelve_diff_host(self):
        source_hostname = self.compute1.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        server = self._boot_then_shelve_and_check_allocations(
            source_hostname, source_rp_uuid)

        self._shelve_offload_and_check_allocations(server, source_rp_uuid)

        # unshelve after shelve offload will do scheduling. this test case
        # wants to test the scenario when the scheduler select a different host
        # to ushelve the instance. So we disable the original host.
        source_service_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']
        self.admin_api.put_service(source_service_id, {'status': 'disabled'})

        req = {
            'unshelve': None
        }
        self.api.post_server_action(server['id'], req)
        server = self._wait_for_state_change(server, 'ACTIVE')
        # unshelving an offloaded instance will call the scheduler so the
        # instance might end up on a different host
        current_hostname = server['OS-EXT-SRV-ATTR:host']
        self.assertEqual(current_hostname, self._other_hostname(
            source_hostname))

        # the host running the instance should have resource usage
        current_rp_uuid = self._get_provider_uuid_by_host(current_hostname)
        self.assertFlavorMatchesUsage(current_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           current_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_shelve_offload_unshelve_same_host(self):
        source_hostname = self.compute1.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        server = self._boot_then_shelve_and_check_allocations(
            source_hostname, source_rp_uuid)

        self._shelve_offload_and_check_allocations(server, source_rp_uuid)

        # unshelve after shelve offload will do scheduling. this test case
        # wants to test the scenario when the scheduler select the same host
        # to ushelve the instance. So we disable the other host.
        source_service_id = self.admin_api.get_services(
            host=self._other_hostname(source_hostname),
            binary='nova-compute')[0]['id']
        self.admin_api.put_service(source_service_id, {'status': 'disabled'})

        req = {
            'unshelve': None
        }
        self.api.post_server_action(server['id'], req)
        server = self._wait_for_state_change(server, 'ACTIVE')
        # unshelving an offloaded instance will call the scheduler so the
        # instance might end up on a different host
        current_hostname = server['OS-EXT-SRV-ATTR:host']
        self.assertEqual(current_hostname, source_hostname)

        # the host running the instance should have resource usage
        current_rp_uuid = self._get_provider_uuid_by_host(current_hostname)
        self.assertFlavorMatchesUsage(current_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           current_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_live_migrate_force(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        # the ability to force live migrate a server is removed entirely in
        # 2.68
        self.api.microversion = '2.67'

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        # live migrate the server and force the destination host which bypasses
        # the scheduler
        post = {
            'os-migrateLive': {
                'host': dest_hostname,
                'block_migration': True,
                'force': True,
            }
        }

        self.api.post_server_action(server['id'], post)
        self._wait_for_server_parameter(server,
            {'OS-EXT-SRV-ATTR:host': dest_hostname,
             'status': 'ACTIVE'})

        self._run_periodics()

        # NOTE(danms): There should be no usage for the source
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, source_rp_uuid)

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        # the server has an allocation on only the dest node
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_live_migrate_forced_v268(self):
        """Live migrating a server with a forced host was removed in API
        microversion 2.68. This test ensures that the request is rejected.
        """
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        # live migrate the server and force the destination host which bypasses
        # the scheduler
        post = {
            'os-migrateLive': {
                'host': dest_hostname,
                'block_migration': True,
                'force': True,
            }
        }

        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               server['id'], post)
        self.assertIn("'force' was unexpected", str(ex))

    def test_live_migrate(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname,
            networks=[{'port': self.neutron.port_1['id']}])
        post = {
            'os-migrateLive': {
                'host': dest_hostname,
                'block_migration': True,
            }
        }

        self.api.post_server_action(server['id'], post)
        self._wait_for_server_parameter(server,
                                        {'OS-EXT-SRV-ATTR:host': dest_hostname,
                                         'status': 'ACTIVE'})

        self._run_periodics()

        # NOTE(danms): There should be no usage for the source
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, source_rp_uuid)

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_live_migrate_pre_check_fails(self):
        """Tests the case that the LiveMigrationTask in conductor has
        called the scheduler which picked a host and created allocations
        against it in Placement, but then when the conductor task calls
        check_can_live_migrate_destination on the destination compute it
        fails. The allocations on the destination compute node should be
        cleaned up before the conductor task asks the scheduler for another
        host to try the live migration.
        """
        self.failed_hostname = None
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        def fake_check_can_live_migrate_destination(
                context, instance, src_compute_info, dst_compute_info,
                block_migration=False, disk_over_commit=False):
            self.failed_hostname = dst_compute_info['host']
            raise exception.MigrationPreCheckError(
                reason='test_live_migrate_pre_check_fails')

        with mock.patch('nova.virt.fake.FakeDriver.'
                        'check_can_live_migrate_destination',
                        side_effect=fake_check_can_live_migrate_destination):
            post = {
                'os-migrateLive': {
                    'host': dest_hostname,
                    'block_migration': True,
                }
            }
            self.api.post_server_action(server['id'], post)
            # As there are only two computes and we failed to live migrate to
            # the only other destination host, the LiveMigrationTask raises
            # MaxRetriesExceeded back to the conductor manager which handles it
            # generically and sets the instance back to ACTIVE status and
            # clears the task_state. The migration record status is set to
            # 'error', so that's what we need to look for to know when this
            # is done.
            migration = self._wait_for_migration_status(server, ['error'])

        # The source_compute should be set on the migration record, but the
        # destination shouldn't be as we never made it to one.
        self.assertEqual(source_hostname, migration['source_compute'])
        self.assertIsNone(migration['dest_compute'])
        # Make sure the destination host (the only other host) is the failed
        # host.
        self.assertEqual(dest_hostname, self.failed_hostname)

        # Since the instance didn't move, assert the allocations are still
        # on the source node.
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        # Assert the allocations, created by the scheduler, are cleaned up
        # after the migration pre-check error happens.
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        # There should only be 1 allocation for the instance on the source node
        self.assertFlavorMatchesAllocation(
            self.flavor1, server['id'], source_rp_uuid)

        self._delete_and_check_allocations(server)

    @mock.patch('nova.virt.fake.FakeDriver.pre_live_migration')
    def test_live_migrate_rollback_cleans_dest_node_allocations(
            self, mock_pre_live_migration, force=False):
        """Tests the case that when live migration fails, either during the
        call to pre_live_migration on the destination, or during the actual
        live migration in the virt driver, the allocations on the destination
        node are rolled back since the instance is still on the source node.
        """
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        # the ability to force live migrate a server is removed entirely in
        # 2.68
        self.api.microversion = '2.67'

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        def stub_pre_live_migration(context, instance, block_device_info,
                                    network_info, disk_info, migrate_data):
            # Make sure the source node allocations are against the migration
            # record and the dest node allocations are against the instance.
            self.assertFlavorMatchesAllocation(
                self.flavor1, migrate_data.migration.uuid, source_rp_uuid)

            self.assertFlavorMatchesAllocation(
                self.flavor1, server['id'], dest_rp_uuid)
            # The actual type of exception here doesn't matter. The point
            # is that the virt driver raised an exception from the
            # pre_live_migration method on the destination host.
            raise test.TestingException(
                'test_live_migrate_rollback_cleans_dest_node_allocations')

        mock_pre_live_migration.side_effect = stub_pre_live_migration

        post = {
            'os-migrateLive': {
                'host': dest_hostname,
                'block_migration': True,
                'force': force
            }
        }
        self.api.post_server_action(server['id'], post)
        # The compute manager will put the migration record into error status
        # when start _cleanup_pre_live_migration, then set it to failed status
        # at the end of _rollback_live_migration
        migration = self._wait_for_migration_status(
            server, ['error', 'failed'])
        # The _rollback_live_migration method in the compute manager will reset
        # the task_state on the instance, so wait for that to happen.
        server = self._wait_for_server_parameter(
            server, {'OS-EXT-STS:task_state': None})

        self.assertEqual(source_hostname, migration['source_compute'])
        self.assertEqual(dest_hostname, migration['dest_compute'])

        # Since the instance didn't move, assert the allocations are still
        # on the source node.
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        # Assert the allocations, created by the scheduler, are cleaned up
        # after the rollback happens.
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        # There should only be 1 allocation for the instance on the source node
        self.assertFlavorMatchesAllocation(
            self.flavor1, server['id'], source_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_live_migrate_rollback_cleans_dest_node_allocations_forced(self):
        """Tests the case that when a forced host live migration fails, either
        during the call to pre_live_migration on the destination, or during
        the actual live migration in the virt driver, the allocations on the
        destination node are rolled back since the instance is still on the
        source node.
        """
        self.test_live_migrate_rollback_cleans_dest_node_allocations(
            force=True)

    def test_rescheduling_when_migrating_instance(self):
        """Tests that allocations are removed from the destination node by
        the compute service when a cold migrate / resize fails and a reschedule
        request is sent back to conductor.
        """
        source_hostname = self.compute1.manager.host
        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        def fake_prep_resize(*args, **kwargs):
            dest_hostname = self._other_hostname(source_hostname)
            dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)
            self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)
            allocations = self._get_allocations_by_server_uuid(server['id'])
            self.assertIn(dest_rp_uuid, allocations)

            source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
            self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)
            migration_uuid = self.get_migration_uuid_for_instance(server['id'])
            allocations = self._get_allocations_by_server_uuid(migration_uuid)
            self.assertIn(source_rp_uuid, allocations)

            raise test.TestingException('Simulated _prep_resize failure.')

        # Yes this isn't great in a functional test, but it's simple.
        self.stub_out('nova.compute.manager.ComputeManager._prep_resize',
                      fake_prep_resize)

        # Now migrate the server which is going to fail on the destination.
        self.api.post_server_action(server['id'], {'migrate': None})

        self._wait_for_action_fail_completion(
            server, instance_actions.MIGRATE, 'compute_prep_resize')

        dest_hostname = self._other_hostname(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        # Expects no allocation records on the failed host.
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        # Ensure the allocation records still exist on the source host.
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)
        allocations = self._get_allocations_by_server_uuid(server['id'])
        self.assertIn(source_rp_uuid, allocations)

    def _test_resize_to_same_host_instance_fails(self, failing_method,
                                                 event_name):
        """Tests that when we resize to the same host and resize fails in
        the given method, we cleanup the allocations before rescheduling.
        """
        # make sure that the test only uses a single host
        compute2_service_id = self.admin_api.get_services(
            host=self.compute2.host, binary='nova-compute')[0]['id']
        self.admin_api.put_service(compute2_service_id, {'status': 'disabled'})

        hostname = self.compute1.manager.host
        rp_uuid = self._get_provider_uuid_by_host(hostname)

        server = self._boot_and_check_allocations(self.flavor1, hostname)

        def fake_resize_method(*args, **kwargs):
            # Ensure the allocations are doubled now before we fail.
            self.assertFlavorMatchesUsage(rp_uuid, self.flavor1, self.flavor2)
            raise test.TestingException('Simulated resize failure.')

        # Yes this isn't great in a functional test, but it's simple.
        self.stub_out(
            'nova.compute.manager.ComputeManager.%s' % failing_method,
            fake_resize_method)

        self.flags(allow_resize_to_same_host=True)
        resize_req = {
            'resize': {
                'flavorRef': self.flavor2['id']
            }
        }
        self.api.post_server_action(server['id'], resize_req)

        self._wait_for_action_fail_completion(
            server, instance_actions.RESIZE, event_name)

        # Ensure the allocation records still exist on the host.
        source_rp_uuid = self._get_provider_uuid_by_host(hostname)
        if failing_method == '_finish_resize':
            # finish_resize will drop the old flavor allocations.
            self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor2)
        else:
            # The new_flavor should have been subtracted from the doubled
            # allocation which just leaves us with the original flavor.
            self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

    def test_resize_to_same_host_prep_resize_fails(self):
        self._test_resize_to_same_host_instance_fails(
            '_prep_resize', 'compute_prep_resize')

    def test_resize_instance_fails_allocation_cleanup(self):
        self._test_resize_to_same_host_instance_fails(
            '_resize_instance', 'compute_resize_instance')

    def test_finish_resize_fails_allocation_cleanup(self):
        self._test_resize_to_same_host_instance_fails(
            '_finish_resize', 'compute_finish_resize')

    def _server_created_with_host(self):
        hostname = self.compute1.host
        server_req = self._build_server(
            image_uuid="155d900f-4e14-4e4c-a73d-069cbf4541e6",
            flavor_id=self.flavor1["id"],
            networks='none')
        server_req['host'] = hostname

        created_server = self.api.post_server({"server": server_req})
        server = self._wait_for_state_change(created_server, "ACTIVE")
        return server

    def test_live_migration_after_server_created_with_host(self):
        """Test after creating server with requested host, and then
        do live-migration for the server. The requested host will not
        effect the new moving operation.
        """
        dest_hostname = self.compute2.host
        created_server = self._server_created_with_host()

        post = {
            'os-migrateLive': {
                'host': None,
                'block_migration': 'auto'
            }
        }
        self.api.post_server_action(created_server['id'], post)
        new_server = self._wait_for_server_parameter(
            created_server, {'status': 'ACTIVE'})
        inst_dest_host = new_server["OS-EXT-SRV-ATTR:host"]

        self.assertEqual(dest_hostname, inst_dest_host)

    def test_evacuate_after_server_created_with_host(self):
        """Test after creating server with requested host, and then
        do evacuation for the server. The requested host will not
        effect the new moving operation.
        """
        dest_hostname = self.compute2.host
        created_server = self._server_created_with_host()

        source_compute_id = self.admin_api.get_services(
            host=created_server["OS-EXT-SRV-ATTR:host"],
            binary='nova-compute')[0]['id']

        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        new_server = self._evacuate_server(
            created_server, expected_host=dest_hostname)

        inst_dest_host = new_server["OS-EXT-SRV-ATTR:host"]

        self.assertEqual(dest_hostname, inst_dest_host)

    def test_resize_and_confirm_after_server_created_with_host(self):
        """Test after creating server with requested host, and then
        do resize for the server. The requested host will not
        effect the new moving operation.
        """
        dest_hostname = self.compute2.host
        created_server = self._server_created_with_host()

        # resize server
        self.flags(allow_resize_to_same_host=False)
        resize_req = {
            'resize': {
                'flavorRef': self.flavor2['id']
            }
        }
        self.api.post_server_action(created_server['id'], resize_req)
        self._wait_for_state_change(created_server, 'VERIFY_RESIZE')

        # Confirm the resize
        new_server = self._confirm_resize(created_server)
        inst_dest_host = new_server["OS-EXT-SRV-ATTR:host"]

        self.assertEqual(dest_hostname, inst_dest_host)

    def test_shelve_unshelve_after_server_created_with_host(self):
        """Test after creating server with requested host, and then
        do shelve and unshelve for the server. The requested host
        will not effect the new moving operation.
        """
        dest_hostname = self.compute2.host
        created_server = self._server_created_with_host()

        self.flags(shelved_offload_time=-1)
        req = {'shelve': {}}
        self.api.post_server_action(created_server['id'], req)
        self._wait_for_state_change(created_server, 'SHELVED')

        req = {'shelveOffload': {}}
        self.api.post_server_action(created_server['id'], req)
        self._wait_for_server_parameter(created_server, {
            'status': 'SHELVED_OFFLOADED',
            'OS-EXT-SRV-ATTR:host': None,
            'OS-EXT-AZ:availability_zone': ''})

        # unshelve after shelve offload will do scheduling. this test case
        # wants to test the scenario when the scheduler select a different host
        # to ushelve the instance. So we disable the original host.
        source_service_id = self.admin_api.get_services(
            host=created_server["OS-EXT-SRV-ATTR:host"],
            binary='nova-compute')[0]['id']
        self.admin_api.put_service(source_service_id, {'status': 'disabled'})

        req = {'unshelve': None}
        self.api.post_server_action(created_server['id'], req)
        new_server = self._wait_for_state_change(created_server, 'ACTIVE')
        inst_dest_host = new_server["OS-EXT-SRV-ATTR:host"]

        self.assertEqual(dest_hostname, inst_dest_host)

    @mock.patch.object(utils, 'fill_provider_mapping',
                       wraps=utils.fill_provider_mapping)
    def _test_resize_reschedule_uses_host_lists(self, mock_fill_provider_map,
                                                fails, num_alts=None):
        """Test that when a resize attempt fails, the retry comes from the
        supplied host_list, and does not call the scheduler.
        """
        server_req = self._build_server(
            image_uuid="155d900f-4e14-4e4c-a73d-069cbf4541e6",
            flavor_id=self.flavor1["id"],
            networks='none')

        created_server = self.api.post_server({"server": server_req})
        server = self._wait_for_state_change(created_server,
                "ACTIVE")
        inst_host = server["OS-EXT-SRV-ATTR:host"]
        uuid_orig = self._get_provider_uuid_by_host(inst_host)

        # We will need four new compute nodes to test the resize, representing
        # the host selected by select_destinations(), along with 3 alternates.
        self._start_compute(host="selection")
        self._start_compute(host="alt_host1")
        self._start_compute(host="alt_host2")
        self._start_compute(host="alt_host3")
        uuid_sel = self._get_provider_uuid_by_host("selection")
        uuid_alt1 = self._get_provider_uuid_by_host("alt_host1")
        uuid_alt2 = self._get_provider_uuid_by_host("alt_host2")
        uuid_alt3 = self._get_provider_uuid_by_host("alt_host3")
        hosts = [{"name": "selection", "uuid": uuid_sel},
                 {"name": "alt_host1", "uuid": uuid_alt1},
                 {"name": "alt_host2", "uuid": uuid_alt2},
                 {"name": "alt_host3", "uuid": uuid_alt3},
                ]

        self.useFixture(nova_fixtures.HostNameWeigherFixture(
            weights={
                "selection": 999, "alt_host1": 888, "alt_host2": 777,
                "alt_host3": 666, "host1": 0, "host2": 0}))
        self.scheduler_service.stop()
        self.scheduler_service = self.start_service('scheduler')

        def fake_prep_resize(*args, **kwargs):
            if self.num_fails < fails:
                self.num_fails += 1
                raise Exception("fake_prep_resize")
            actual_prep_resize(*args, **kwargs)

        # Yes this isn't great in a functional test, but it's simple.
        actual_prep_resize = compute_manager.ComputeManager._prep_resize
        self.stub_out("nova.compute.manager.ComputeManager._prep_resize",
                      fake_prep_resize)
        self.num_fails = 0
        num_alts = 4 if num_alts is None else num_alts
        # Make sure we have enough retries available for the number of
        # requested fails.
        attempts = min(fails + 2, num_alts)
        self.flags(max_attempts=attempts, group='scheduler')
        server_uuid = server["id"]
        data = {"resize": {"flavorRef": self.flavor2["id"]}}
        self.api.post_server_action(server_uuid, data)

        if num_alts < fails:
            # We will run out of alternates before populate_retry will
            # raise a MaxRetriesExceeded exception, so the migration will
            # fail and the server should be in status "ERROR"
            server = self._wait_for_state_change(created_server,
                    "ERROR")
            # The usage should be unchanged from the original flavor
            self.assertFlavorMatchesUsage(uuid_orig, self.flavor1)
            # There should be no usages on any of the hosts
            target_uuids = (uuid_sel, uuid_alt1, uuid_alt2, uuid_alt3)
            empty_usage = {"VCPU": 0, "MEMORY_MB": 0, "DISK_GB": 0}
            for target_uuid in target_uuids:
                usage = self._get_provider_usages(target_uuid)
                self.assertEqual(empty_usage, usage)
        else:
            server = self._wait_for_state_change(created_server,
                    "VERIFY_RESIZE")
            # Verify that the selected host failed, and was rescheduled to
            # an alternate host.
            new_server_host = server.get("OS-EXT-SRV-ATTR:host")
            expected_host = hosts[fails]["name"]
            self.assertEqual(expected_host, new_server_host)
            uuid_dest = hosts[fails]["uuid"]
            # The usage should match the resized flavor
            self.assertFlavorMatchesUsage(uuid_dest, self.flavor2)
            # Verify that the other host have no allocations
            target_uuids = (uuid_sel, uuid_alt1, uuid_alt2, uuid_alt3)
            empty_usage = {"VCPU": 0, "MEMORY_MB": 0, "DISK_GB": 0}
            for target_uuid in target_uuids:
                if target_uuid == uuid_dest:
                    continue
                usage = self._get_provider_usages(target_uuid)
                self.assertEqual(empty_usage, usage)

            # Verify that there is only one migration record for the instance.
            ctxt = context.get_admin_context()
            filters = {"instance_uuid": server["id"]}
            migrations = objects.MigrationList.get_by_filters(ctxt, filters)
            self.assertEqual(1, len(migrations.objects))

        # fill_provider_mapping should have been called once for the initial
        # build, once for the resize scheduling to the primary host and then
        # once per reschedule.
        expected_fill_count = 2
        if num_alts > 1:
            expected_fill_count += self.num_fails - 1
        self.assertGreaterEqual(mock_fill_provider_map.call_count,
                                expected_fill_count)

    def test_resize_reschedule_uses_host_lists_1_fail(self):
        self._test_resize_reschedule_uses_host_lists(fails=1)

    def test_resize_reschedule_uses_host_lists_3_fails(self):
        self._test_resize_reschedule_uses_host_lists(fails=3)

    def test_resize_reschedule_uses_host_lists_not_enough_alts(self):
        self._test_resize_reschedule_uses_host_lists(fails=3, num_alts=1)

    def test_migrate_confirm(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        self._migrate_and_check_allocations(
            server, self.flavor1, source_rp_uuid, dest_rp_uuid)

        # Confirm the move and check the usages
        self._confirm_resize(server)

        def _check_allocation():
            # the target host usage should be according to the flavor
            self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)
            # the source host has no usage
            self.assertRequestMatchesUsage({'VCPU': 0,
                                            'MEMORY_MB': 0,
                                            'DISK_GB': 0}, source_rp_uuid)

            # and the target host allocation should be according to the flavor
            self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                               dest_rp_uuid)

        # After confirming, we should have an allocation only on the
        # destination host
        _check_allocation()
        self._run_periodics()

        # Check we're still accurate after running the periodics
        _check_allocation()

        self._delete_and_check_allocations(server)

    def test_migrate_revert(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        self._migrate_and_check_allocations(
            server, self.flavor1, source_rp_uuid, dest_rp_uuid)

        # Revert the move and check the usages
        post = {'revertResize': None}
        self.api.post_server_action(server['id'], post)
        self._wait_for_state_change(server, 'ACTIVE')

        def _check_allocation():
            self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)
            self.assertRequestMatchesUsage({'VCPU': 0,
                                            'MEMORY_MB': 0,
                                            'DISK_GB': 0}, dest_rp_uuid)

            # Check that the server only allocates resource from the original
            # host
            self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                               source_rp_uuid)

        # the original host expected to have the old resource allocation
        _check_allocation()
        self._run_periodics()
        _check_allocation()

        self._delete_and_check_allocations(server)


class PollUnconfirmedResizesTest(integrated_helpers.ProviderUsageBaseTestCase):
    """Tests for the _poll_unconfirmed_resizes periodic task."""
    compute_driver = 'fake.MediumFakeDriver'

    def setUp(self):
        super(PollUnconfirmedResizesTest, self).setUp()
        # Start two computes for the resize.
        self._start_compute('host1')
        self._start_compute('host2')

    def test_source_host_down_during_confirm(self):
        """Tests the scenario that between the time that the server goes to
        VERIFY_RESIZE status and the _poll_unconfirmed_resizes periodic task
        runs the source compute service goes down so the confirm task fails.
        """
        server = self._build_server(networks='none', host='host1')
        server = self.api.post_server({'server': server})
        server = self._wait_for_state_change(server, 'ACTIVE')
        # Cold migrate the server to the other host.
        self.api.post_server_action(server['id'], {'migrate': None})
        server = self._wait_for_state_change(server, 'VERIFY_RESIZE')
        self.assertEqual('host2', server['OS-EXT-SRV-ATTR:host'])
        # Make sure the migration is finished.
        self._wait_for_migration_status(server, ['finished'])
        # Stop and force down the source compute service.
        self.computes['host1'].stop()
        source_service = self.api.get_services(
            binary='nova-compute', host='host1')[0]
        self.api.put_service(
            source_service['id'], {'status': 'disabled', 'forced_down': True})
        # Now configure auto-confirm and call the method on the target compute
        # so we do not have to wait for the periodic to run.
        self.flags(resize_confirm_window=1)
        # Stub timeutils so the DB API query finds the unconfirmed migration.
        future = timeutils.utcnow() + datetime.timedelta(hours=1)
        ctxt = context.get_admin_context()
        with osloutils_fixture.TimeFixture(future):
            self.computes['host2'].manager._poll_unconfirmed_resizes(ctxt)
        self.assertIn('Error auto-confirming resize',
                      self.stdlog.logger.output)
        self.assertIn('Service is unavailable at this time',
                      self.stdlog.logger.output)
        # The source compute service check should have been done before the
        # migration status was updated so it should still be "finished".
        self._wait_for_migration_status(server, ['finished'])
        # Try to confirm in the API while the source compute service is still
        # down to assert the 409 (rather than a 500) error.
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               server['id'], {'confirmResize': None})
        self.assertEqual(409, ex.response.status_code)
        self.assertIn('Service is unavailable at this time', str(ex))
        # Bring the source compute back up and try to confirm the resize which
        # should work since the migration status is still "finished".
        self.restart_compute_service(self.computes['host1'])
        self.api.put_service(
            source_service['id'], {'status': 'enabled', 'forced_down': False})
        # Use the API to confirm the resize because _poll_unconfirmed_resizes
        # requires mucking with the current time which causes problems with
        # the service_is_up check in the API.
        self.api.post_server_action(server['id'], {'confirmResize': None})
        self._wait_for_state_change(server, 'ACTIVE')


class ServerLiveMigrateForceAndAbort(
        integrated_helpers.ProviderUsageBaseTestCase):
    """Test Server live migrations, which delete the migration or
    force_complete it, and check the allocations after the operations.

    The test are using fakedriver to handle the force_completion and deletion
    of live migration.
    """

    compute_driver = 'fake.FakeLiveMigrateDriver'

    def setUp(self):
        super(ServerLiveMigrateForceAndAbort, self).setUp()

        self.compute1 = self._start_compute(host='host1')
        self.compute2 = self._start_compute(host='host2')

        flavors = self.api.get_flavors()
        self.flavor1 = flavors[0]

    def test_live_migrate_force_complete(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        post = {
            'os-migrateLive': {
                'host': dest_hostname,
                'block_migration': True,
            }
        }
        self.api.post_server_action(server['id'], post)

        migration = self._wait_for_migration_status(server, ['running'])
        self.api.force_complete_migration(server['id'],
                                          migration['id'])

        self._wait_for_server_parameter(server,
                                        {'OS-EXT-SRV-ATTR:host': dest_hostname,
                                         'status': 'ACTIVE'})

        self._run_periodics()

        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, source_rp_uuid)

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           dest_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_live_migrate_delete(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        post = {
            'os-migrateLive': {
                'host': dest_hostname,
                'block_migration': True,
            }
        }
        self.api.post_server_action(server['id'], post)

        migration = self._wait_for_migration_status(server, ['running'])

        self.api.delete_migration(server['id'], migration['id'])
        self._wait_for_server_parameter(server,
            {'OS-EXT-SRV-ATTR:host': source_hostname,
             'status': 'ACTIVE'})

        self._run_periodics()

        allocations = self._get_allocations_by_server_uuid(server['id'])
        self.assertNotIn(dest_rp_uuid, allocations)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self.assertRequestMatchesUsage({'VCPU': 0,
                                        'MEMORY_MB': 0,
                                        'DISK_GB': 0}, dest_rp_uuid)

        self._delete_and_check_allocations(server)


class ServerLiveMigrateForceAndAbortWithNestedResourcesRequest(
        ServerLiveMigrateForceAndAbort):
    compute_driver = 'fake.FakeLiveMigrateDriverWithNestedCustomResources'

    def setUp(self):
        super(ServerLiveMigrateForceAndAbortWithNestedResourcesRequest,
              self).setUp()
        # modify the flavor used in the test base class to require one piece of
        # CUSTOM_MAGIC resource as well.

        self.api.post_extra_spec(
            self.flavor1['id'], {'extra_specs': {'resources:CUSTOM_MAGIC': 1}})
        # save the extra_specs in the flavor stored in the test case as
        # well
        self.flavor1['extra_specs'] = {'resources:CUSTOM_MAGIC': 1}


class ServerRescheduleTests(integrated_helpers.ProviderUsageBaseTestCase):
    """Tests server create scenarios which trigger a reschedule during
    a server build and validates that allocations in Placement
    are properly cleaned up.

    Uses a fake virt driver that fails the build on the first attempt.
    """

    compute_driver = 'fake.FakeRescheduleDriver'

    def setUp(self):
        super(ServerRescheduleTests, self).setUp()
        self.compute1 = self._start_compute(host='host1')
        self.compute2 = self._start_compute(host='host2')

        flavors = self.api.get_flavors()
        self.flavor1 = flavors[0]

    def _other_hostname(self, host):
        other_host = {'host1': 'host2',
                      'host2': 'host1'}
        return other_host[host]

    def test_rescheduling_when_booting_instance(self):
        """Tests that allocations, created by the scheduler, are cleaned
        from the source node when the build fails on that node and is
        rescheduled to another node.
        """
        server_req = self._build_server(
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            flavor_id=self.flavor1['id'],
            networks='none')

        created_server = self.api.post_server({'server': server_req})
        server = self._wait_for_state_change(created_server, 'ACTIVE')
        dest_hostname = server['OS-EXT-SRV-ATTR:host']
        failed_hostname = self._other_hostname(dest_hostname)

        LOG.info('failed on %s', failed_hostname)
        LOG.info('booting on %s', dest_hostname)

        failed_rp_uuid = self._get_provider_uuid_by_host(failed_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        # Expects no allocation records on the failed host.
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, failed_rp_uuid)

        # Ensure the allocation records on the destination host.
        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1)

    def test_allocation_fails_during_reschedule(self):
        """Verify that if nova fails to allocate resources during re-schedule
        then the server is put into ERROR state properly.
        """

        server_req = self._build_server(
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            flavor_id=self.flavor1['id'],
            networks='none')

        orig_claim = utils.claim_resources
        # First call is during boot, we want that to succeed normally. Then the
        # fake virt driver triggers a re-schedule. During that re-schedule we
        # simulate that the placement call fails.
        with mock.patch('nova.scheduler.utils.claim_resources',
                        side_effect=[
                            orig_claim,
                            exception.AllocationUpdateFailed(
                                consumer_uuid=uuids.inst1, error='testing')]):

            server = self.api.post_server({'server': server_req})
            server = self._wait_for_state_change(server, 'ERROR')

        self._delete_and_check_allocations(server)


class ServerRescheduleTestsWithNestedResourcesRequest(ServerRescheduleTests):
    compute_driver = 'fake.FakeRescheduleDriverWithNestedCustomResources'

    def setUp(self):
        super(ServerRescheduleTestsWithNestedResourcesRequest, self).setUp()
        # modify the flavor used in the test base class to require one piece of
        # CUSTOM_MAGIC resource as well.

        self.api.post_extra_spec(
            self.flavor1['id'], {'extra_specs': {'resources:CUSTOM_MAGIC': 1}})
        # save the extra_specs in the flavor stored in the test case as
        # well
        self.flavor1['extra_specs'] = {'resources:CUSTOM_MAGIC': 1}


class ServerBuildAbortTests(integrated_helpers.ProviderUsageBaseTestCase):
    """Tests server create scenarios which trigger a build abort during
    a server build and validates that allocations in Placement
    are properly cleaned up.

    Uses a fake virt driver that aborts the build on the first attempt.
    """

    compute_driver = 'fake.FakeBuildAbortDriver'

    def setUp(self):
        super(ServerBuildAbortTests, self).setUp()
        # We only need one compute service/host/node for these tests.
        self.compute1 = self._start_compute(host='host1')

        flavors = self.api.get_flavors()
        self.flavor1 = flavors[0]

    def test_abort_when_booting_instance(self):
        """Tests that allocations, created by the scheduler, are cleaned
        from the source node when the build is aborted on that node.
        """
        server_req = self._build_server(
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            flavor_id=self.flavor1['id'],
            networks='none')

        created_server = self.api.post_server({'server': server_req})
        self._wait_for_state_change(created_server, 'ERROR')

        failed_hostname = self.compute1.manager.host

        # BuildAbortException coming from the FakeBuildAbortDriver will not
        # trigger a reschedule and the placement cleanup is the last step in
        # the compute manager after instance state setting, fault recording
        # and notification sending. So we have no other way than simply wait
        # to ensure the placement cleanup happens before we assert it.
        def placement_cleanup():
            failed_rp_uuid = self._get_provider_uuid_by_host(failed_hostname)
            # Expects no allocation records on the failed host.
            self.assertRequestMatchesUsage({'VCPU': 0,
                                            'MEMORY_MB': 0,
                                            'DISK_GB': 0}, failed_rp_uuid)
        self._wait_for_assert(placement_cleanup)


class ServerDeleteBuildTests(integrated_helpers.ProviderUsageBaseTestCase):
    """Tests server delete during instance in build and validates that
        allocations in Placement are properly cleaned up.
    """
    compute_driver = 'fake.SmallFakeDriver'

    def setUp(self):
        super(ServerDeleteBuildTests, self).setUp()
        self.compute1 = self._start_compute(host='host1')
        flavors = self.api.get_flavors()
        self.flavor1 = flavors[0]

    def test_delete_stuck_build_instance_after_claim(self):
        """Test for bug 1859496 where an instance allocation can leaks after
        deletion if build process have been interrupted after resource claim
        """

        # To reproduce the issue we need to interrupt instance spawn
        # when build request has already reached the scheduler service,
        # so that instance resource get claims.
        # Real case can typically be a conductor restart during
        # instance claim.
        # To emulate conductor restart we raise an Exception in
        # filter_scheduler after instance is claimed and mock
        # _bury_in_cell0 in that case conductor thread return.
        # Then we delete server after ensuring allocation is made and check
        # There is no leak.
        # Note that because deletion occurs early, conductor did not populate
        # instance DB entries in cells, preventing the compute
        # update_available_resource periodic task to heal leaked allocations.

        server_req = self._build_server(
            'interrupted-server', flavor_id=self.flavor1['id'],
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks='none')

        with test.nested(
            mock.patch('nova.scheduler.manager.SchedulerManager'
                       '._ensure_sufficient_hosts'),
            mock.patch('nova.conductor.manager.ComputeTaskManager'
                       '._bury_in_cell0'),
        ) as (mock_suff_hosts, mock_bury):
            mock_suff_hosts.side_effect = test.TestingException('oops')
            server = self.api.post_server({'server': server_req})
            self._wait_for_server_allocations(server['id'])
            self.api.api_delete('/servers/%s' % server['id'])
            allocations = self._get_allocations_by_server_uuid(server['id'])
            self.assertEqual({}, allocations)


class ServerBuildAbortTestsWithNestedResourceRequest(ServerBuildAbortTests):
    compute_driver = 'fake.FakeBuildAbortDriverWithNestedCustomResources'

    def setUp(self):
        super(ServerBuildAbortTestsWithNestedResourceRequest, self).setUp()
        # modify the flavor used in the test base class to require one piece of
        # CUSTOM_MAGIC resource as well.

        self.api.post_extra_spec(
            self.flavor1['id'], {'extra_specs': {'resources:CUSTOM_MAGIC': 1}})
        # save the extra_specs in the flavor stored in the test case as
        # well
        self.flavor1['extra_specs'] = {'resources:CUSTOM_MAGIC': 1}


class ServerUnshelveSpawnFailTests(
        integrated_helpers.ProviderUsageBaseTestCase):
    """Tests server unshelve scenarios which trigger a
    VirtualInterfaceCreateException during driver.spawn() and validates that
    allocations in Placement are properly cleaned up.
    """

    compute_driver = 'fake.FakeUnshelveSpawnFailDriver'

    def setUp(self):
        super(ServerUnshelveSpawnFailTests, self).setUp()
        # We only need one compute service/host/node for these tests.
        self.compute1 = self._start_compute('host1')

        flavors = self.api.get_flavors()
        self.flavor1 = flavors[0]

    def test_driver_spawn_fail_when_unshelving_instance(self):
        """Tests that allocations, created by the scheduler, are cleaned
        from the target node when the unshelve driver.spawn fails on that node.
        """
        hostname = self.compute1.manager.host
        rp_uuid = self._get_provider_uuid_by_host(hostname)
        # We start with no usages on the host.
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, rp_uuid)

        server_req = self._build_server(
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            flavor_id=self.flavor1['id'],
            networks='none')

        server = self.api.post_server({'server': server_req})
        self._wait_for_state_change(server, 'ACTIVE')

        # assert allocations exist for the host
        self.assertFlavorMatchesUsage(rp_uuid, self.flavor1)

        # shelve offload the server
        self.flags(shelved_offload_time=0)
        self.api.post_server_action(server['id'], {'shelve': None})
        self._wait_for_server_parameter(server, {'status': 'SHELVED_OFFLOADED',
                               'OS-EXT-SRV-ATTR:host': None})

        # assert allocations were removed from the host
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, rp_uuid)

        # unshelve the server, which should fail
        self.api.post_server_action(server['id'], {'unshelve': None})
        self._wait_for_action_fail_completion(
            server, instance_actions.UNSHELVE, 'compute_unshelve_instance')

        # assert allocations were removed from the host
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, rp_uuid)


class ServerUnshelveSpawnFailTestsWithNestedResourceRequest(
    ServerUnshelveSpawnFailTests):
    compute_driver = ('fake.'
                      'FakeUnshelveSpawnFailDriverWithNestedCustomResources')

    def setUp(self):
        super(ServerUnshelveSpawnFailTestsWithNestedResourceRequest,
              self).setUp()
        # modify the flavor used in the test base class to require one piece of
        # CUSTOM_MAGIC resource as well.

        self.api.post_extra_spec(
            self.flavor1['id'], {'extra_specs': {'resources:CUSTOM_MAGIC': 1}})
        # save the extra_specs in the flavor stored in the test case as
        # well
        self.flavor1['extra_specs'] = {'resources:CUSTOM_MAGIC': 1}


class ServerSoftDeleteTests(integrated_helpers.ProviderUsageBaseTestCase):

    compute_driver = 'fake.SmallFakeDriver'

    def setUp(self):
        super(ServerSoftDeleteTests, self).setUp()
        # We only need one compute service/host/node for these tests.
        self.compute1 = self._start_compute('host1')

        flavors = self.api.get_flavors()
        self.flavor1 = flavors[0]

    def _soft_delete_and_check_allocation(self, server, hostname):
        self.api.delete_server(server['id'])
        server = self._wait_for_state_change(server, 'SOFT_DELETED')

        self._run_periodics()

        # in soft delete state nova should keep the resource allocation as
        # the instance can be restored
        rp_uuid = self._get_provider_uuid_by_host(hostname)

        self.assertFlavorMatchesUsage(rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           rp_uuid)

        # run the periodic reclaim but as time isn't advanced it should not
        # reclaim the instance
        ctxt = context.get_admin_context()
        self.compute1._reclaim_queued_deletes(ctxt)

        self._run_periodics()

        self.assertFlavorMatchesUsage(rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           rp_uuid)

    def test_soft_delete_then_reclaim(self):
        """Asserts that the automatic reclaim of soft deleted instance cleans
        up the allocations in placement.
        """

        # make sure that instance will go to SOFT_DELETED state instead of
        # deleted immediately
        self.flags(reclaim_instance_interval=30)

        hostname = self.compute1.host
        rp_uuid = self._get_provider_uuid_by_host(hostname)

        server = self._boot_and_check_allocations(self.flavor1, hostname)

        self._soft_delete_and_check_allocation(server, hostname)

        # advance the time and run periodic reclaim, instance should be deleted
        # and resources should be freed
        the_past = timeutils.utcnow() + datetime.timedelta(hours=1)
        timeutils.set_time_override(override_time=the_past)
        self.addCleanup(timeutils.clear_time_override)
        ctxt = context.get_admin_context()
        self.compute1._reclaim_queued_deletes(ctxt)

        # Wait for real deletion
        self._wait_until_deleted(server)

        usages = self._get_provider_usages(rp_uuid)
        self.assertEqual({'VCPU': 0,
                          'MEMORY_MB': 0,
                          'DISK_GB': 0}, usages)
        allocations = self._get_allocations_by_server_uuid(server['id'])
        self.assertEqual(0, len(allocations))

    def test_soft_delete_then_restore(self):
        """Asserts that restoring a soft deleted instance keeps the proper
        allocation in placement.
        """

        # make sure that instance will go to SOFT_DELETED state instead of
        # deleted immediately
        self.flags(reclaim_instance_interval=30)

        hostname = self.compute1.host
        rp_uuid = self._get_provider_uuid_by_host(hostname)

        server = self._boot_and_check_allocations(
            self.flavor1, hostname)

        self._soft_delete_and_check_allocation(server, hostname)

        post = {'restore': {}}
        self.api.post_server_action(server['id'], post)
        server = self._wait_for_state_change(server, 'ACTIVE')

        # after restore the allocations should be kept
        self.assertFlavorMatchesUsage(rp_uuid, self.flavor1)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           rp_uuid)

        # Now we want a real delete
        self.flags(reclaim_instance_interval=0)
        self._delete_and_check_allocations(server)


class ServerSoftDeleteTestsWithNestedResourceRequest(ServerSoftDeleteTests):
    compute_driver = 'fake.MediumFakeDriverWithNestedCustomResources'

    def setUp(self):
        super(ServerSoftDeleteTestsWithNestedResourceRequest, self).setUp()
        # modify the flavor used in the test base class to require one piece of
        # CUSTOM_MAGIC resource as well.

        self.api.post_extra_spec(
            self.flavor1['id'], {'extra_specs': {'resources:CUSTOM_MAGIC': 1}})
        # save the extra_specs in the flavor stored in the test case as
        # well
        self.flavor1['extra_specs'] = {'resources:CUSTOM_MAGIC': 1}


class VolumeBackedServerTest(integrated_helpers.ProviderUsageBaseTestCase):
    """Tests for volume-backed servers."""

    compute_driver = 'fake.SmallFakeDriver'

    def setUp(self):
        super(VolumeBackedServerTest, self).setUp()
        self.compute1 = self._start_compute('host1')
        self.flavor_id = self._create_flavor(
            disk=10, ephemeral=20, swap=5 * 1024)

    def _create_server(self):
        server_req = self._build_server(
            flavor_id=self.flavor_id,
            networks='none')
        server = self.api.post_server({'server': server_req})
        server = self._wait_for_state_change(server, 'ACTIVE')
        return server

    def _create_volume_backed_server(self):
        self.useFixture(nova_fixtures.CinderFixture(self))
        volume_id = nova_fixtures.CinderFixture.IMAGE_BACKED_VOL
        server_req_body = {
            # There is no imageRef because this is boot from volume.
            'server': {
                'flavorRef': self.flavor_id,
                'name': 'test_volume_backed',
                # We don't care about networking for this test. This
                # requires microversion >= 2.37.
                'networks': 'none',
                'block_device_mapping_v2': [{
                    'boot_index': 0,
                    'uuid': volume_id,
                    'source_type': 'volume',
                    'destination_type': 'volume'
                }]
            }
        }
        server = self.api.post_server(server_req_body)
        server = self._wait_for_state_change(server, 'ACTIVE')
        return server

    def test_ephemeral_has_disk_allocation(self):
        server = self._create_server()
        allocs = self._get_allocations_by_server_uuid(server['id'])
        resources = list(allocs.values())[0]['resources']
        self.assertIn('MEMORY_MB', resources)
        # 10gb root, 20gb ephemeral, 5gb swap
        expected_usage = 35
        self.assertEqual(expected_usage, resources['DISK_GB'])
        # Ensure the compute node is reporting the correct disk usage. We're
        # using v2.87 explicitly as the api returns 404 starting with 2.88
        with nova_utils.temporary_mutation(self.api, microversion='2.87'):
            self.assertEqual(
                expected_usage,
                self.admin_api.get_hypervisor_stats()['local_gb_used'])

    def test_volume_backed_image_type_filter(self):
        # Enable the image type support filter and ensure that a
        # non-image-having volume-backed server can still boot
        self.flags(query_placement_for_image_type_support=True,
                   group='scheduler')
        server = self._create_volume_backed_server()
        created_server = self.api.get_server(server['id'])
        self.assertEqual('ACTIVE', created_server['status'])

    def test_volume_backed_no_disk_allocation(self):
        server = self._create_volume_backed_server()
        allocs = self._get_allocations_by_server_uuid(server['id'])
        resources = list(allocs.values())[0]['resources']
        self.assertIn('MEMORY_MB', resources)
        # 0gb root, 20gb ephemeral, 5gb swap
        expected_usage = 25
        self.assertEqual(expected_usage, resources['DISK_GB'])
        # Ensure the compute node is reporting the correct disk usage. We're
        # using v2.87 explicitly as the api returns 404 starting with 2.88
        with nova_utils.temporary_mutation(self.api, microversion='2.87'):
            self.assertEqual(
                expected_usage,
                self.admin_api.get_hypervisor_stats()['local_gb_used'])

        # Now let's hack the RequestSpec.is_bfv field to mimic migrating an
        # old instance created before RequestSpec.is_bfv was set in the API,
        # move the instance and verify that the RequestSpec.is_bfv is set
        # and the instance still reports the same DISK_GB allocations as during
        # the initial create.
        ctxt = context.get_admin_context()
        reqspec = objects.RequestSpec.get_by_instance_uuid(ctxt, server['id'])
        # Make sure it's set.
        self.assertTrue(reqspec.is_bfv)
        del reqspec.is_bfv
        reqspec.save()
        reqspec = objects.RequestSpec.get_by_instance_uuid(ctxt, server['id'])
        # Make sure it's not set.
        self.assertNotIn('is_bfv', reqspec)
        # Now migrate the instance to another host and check the request spec
        # and allocations after the migration.
        self._start_compute('host2')
        self.admin_api.post_server_action(server['id'], {'migrate': None})
        # Wait for the server to complete the cold migration.
        server = self._wait_for_state_change(server, 'VERIFY_RESIZE')
        self.assertEqual('host2', server['OS-EXT-SRV-ATTR:host'])
        # Confirm the cold migration and check usage and the request spec.
        self._confirm_resize(server)
        reqspec = objects.RequestSpec.get_by_instance_uuid(ctxt, server['id'])
        # Make sure it's set.
        self.assertTrue(reqspec.is_bfv)
        allocs = self._get_allocations_by_server_uuid(server['id'])
        resources = list(allocs.values())[0]['resources']
        self.assertEqual(expected_usage, resources['DISK_GB'])

        # Now shelve and unshelve the server to make sure root_gb DISK_GB
        # isn't reported for allocations after we unshelve the server.
        self.api.post_server_action(server['id'], {'shelve': None})
        self._wait_for_state_change(server, 'SHELVED_OFFLOADED')
        self.notifier.wait_for_versioned_notifications(
                'instance.shelve_offload.end')
        # The server should not have any allocations since it's not currently
        # hosted on any compute service.
        allocs = self._get_allocations_by_server_uuid(server['id'])
        self.assertDictEqual({}, allocs)
        # Now unshelve the server and make sure there are still no DISK_GB
        # allocations for the root disk.
        self.api.post_server_action(server['id'], {'unshelve': None})
        self._wait_for_state_change(server, 'ACTIVE')
        allocs = self._get_allocations_by_server_uuid(server['id'])
        resources = list(allocs.values())[0]['resources']
        self.assertEqual(expected_usage, resources['DISK_GB'])


class TraitsBasedSchedulingTest(integrated_helpers.ProviderUsageBaseTestCase):
    """Tests for requesting a server with required traits in Placement"""

    compute_driver = 'fake.SmallFakeDriver'

    def setUp(self):
        super(TraitsBasedSchedulingTest, self).setUp()
        self.compute1 = self._start_compute('host1')
        self.compute2 = self._start_compute('host2')
        # Using a standard trait from the os-traits library, set a required
        # trait extra spec on the flavor.
        flavors = self.api.get_flavors()
        self.flavor_with_trait = flavors[0]
        self.admin_api.post_extra_spec(
            self.flavor_with_trait['id'],
            {'extra_specs': {'trait:HW_CPU_X86_VMX': 'required'}})
        self.flavor_without_trait = flavors[1]
        self.flavor_with_forbidden_trait = flavors[2]
        self.admin_api.post_extra_spec(
            self.flavor_with_forbidden_trait['id'],
            {'extra_specs': {'trait:HW_CPU_X86_SGX': 'forbidden'}})

        # Note that we're using v2.35 explicitly as the api returns 404
        # starting with 2.36
        with nova_utils.temporary_mutation(self.api, microversion='2.35'):
            images = self.api.get_images()
            self.image_id_with_trait = images[0]['id']
            self.api.api_put('/images/%s/metadata' % self.image_id_with_trait,
                             {'metadata': {
                                 'trait:HW_CPU_X86_SGX': 'required'}})
            self.image_id_without_trait = images[1]['id']

    def _create_server_with_traits(self, flavor_id, image_id):
        """Create a server with given flavor and image id's
        :param flavor_id: the flavor id
        :param image_id: the image id
        :return: create server response
        """

        server_req = self._build_server(
            image_uuid=image_id,
            flavor_id=flavor_id,
            networks='none')
        return self.api.post_server({'server': server_req})

    def _create_volume_backed_server_with_traits(self, flavor_id, volume_id):
        """Create a server with block device mapping(volume) with the given
        flavor and volume id's. Either the flavor or the image backing the
        volume is expected to have the traits
        :param flavor_id: the flavor id
        :param volume_id: the volume id
        :return: create server response
        """

        server_req_body = {
            # There is no imageRef because this is boot from volume.
            'server': {
                'flavorRef': flavor_id,
                'name': 'test_image_trait_on_volume_backed',
                # We don't care about networking for this test. This
                # requires microversion >= 2.37.
                'networks': 'none',
                'block_device_mapping_v2': [{
                    'boot_index': 0,
                    'uuid': volume_id,
                    'source_type': 'volume',
                    'destination_type': 'volume'
                }]
            }
        }
        server = self.api.post_server(server_req_body)
        return server

    def test_flavor_traits_based_scheduling(self):
        """Tests that a server create request using a required trait in the
        flavor ends up on the single compute node resource provider that also
        has that trait in Placement. That test will however pass half of the
        times even if the trait is not taken into consideration, so we are
        also disabling the compute node that has the required trait and try
        again, which should result in a no valid host error.
        """

        # Decorate compute1 resource provider with the required trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute1.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_VMX'])

        # Create server using flavor with required trait
        server = self._create_server_with_traits(self.flavor_with_trait['id'],
                                                 self.image_id_without_trait)
        server = self._wait_for_state_change(server, 'ACTIVE')
        # Assert the server ended up on the expected compute host that has
        # the required trait.
        self.assertEqual(self.compute1.host, server['OS-EXT-SRV-ATTR:host'])

        # Disable the compute node that has the required trait
        compute1_service_id = self.admin_api.get_services(
            host=self.compute1.host, binary='nova-compute')[0]['id']
        self.admin_api.put_service(compute1_service_id, {'status': 'disabled'})

        # Create server using flavor with required trait
        server = self._create_server_with_traits(self.flavor_with_trait['id'],
                                                 self.image_id_without_trait)

        # The server should go to ERROR state because there is no valid host.
        server = self._wait_for_state_change(server, 'ERROR')
        self.assertIsNone(server['OS-EXT-SRV-ATTR:host'])
        # Make sure the failure was due to NoValidHost by checking the fault.
        self.assertIn('fault', server)
        self.assertIn('No valid host', server['fault']['message'])

    def test_flavor_forbidden_traits_based_scheduling(self):
        """Tests that a server create request using a forbidden trait in the
        flavor ends up on the single compute host that doesn't have that
        trait in Placement. That test will however pass half of the times even
        if the trait is not taken into consideration, so we are also disabling
        the compute node that doesn't have the forbidden trait and try again,
        which should result in a no valid host error.
        """

        # Decorate compute1 resource provider with forbidden trait
        rp_uuid = self._get_provider_uuid_by_host(self.compute1.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_SGX'])

        # Create server using flavor with forbidden trait
        server = self._create_server_with_traits(
            self.flavor_with_forbidden_trait['id'],
            self.image_id_without_trait
        )

        server = self._wait_for_state_change(server, 'ACTIVE')

        # Assert the server ended up on the expected compute host that doesn't
        # have the forbidden trait.
        self.assertEqual(self.compute2.host, server['OS-EXT-SRV-ATTR:host'])

        # Disable the compute node that doesn't have the forbidden trait
        compute2_service_id = self.admin_api.get_services(
            host=self.compute2.host, binary='nova-compute')[0]['id']
        self.admin_api.put_service(compute2_service_id, {'status': 'disabled'})

        # Create server using flavor with forbidden trait
        server = self._create_server_with_traits(
            self.flavor_with_forbidden_trait['id'],
            self.image_id_without_trait
        )

        # The server should go to ERROR state because there is no valid host.
        server = self._wait_for_state_change(server, 'ERROR')
        self.assertIsNone(server['OS-EXT-SRV-ATTR:host'])
        # Make sure the failure was due to NoValidHost by checking the fault.
        self.assertIn('fault', server)
        self.assertIn('No valid host', server['fault']['message'])

    def test_image_traits_based_scheduling(self):
        """Tests that a server create request using a required trait on image
        ends up on the single compute node resource provider that also has that
        trait in Placement.
        """

        # Decorate compute2 resource provider with image trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute2.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_SGX'])

        # Create server using only image trait
        server = self._create_server_with_traits(
            self.flavor_without_trait['id'], self.image_id_with_trait)
        server = self._wait_for_state_change(server, 'ACTIVE')
        # Assert the server ended up on the expected compute host that has
        # the required trait.
        self.assertEqual(self.compute2.host, server['OS-EXT-SRV-ATTR:host'])

    def test_flavor_image_traits_based_scheduling(self):
        """Tests that a server create request using a required trait on flavor
        AND a required trait on the image ends up on the single compute node
        resource provider that also has that trait in Placement.
        """

        # Decorate compute2 resource provider with both flavor and image trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute2.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_VMX',
                                            'HW_CPU_X86_SGX'])

        # Create server using flavor and image trait
        server = self._create_server_with_traits(
            self.flavor_with_trait['id'], self.image_id_with_trait)
        server = self._wait_for_state_change(server, 'ACTIVE')
        # Assert the server ended up on the expected compute host that has
        # the required trait.
        self.assertEqual(self.compute2.host, server['OS-EXT-SRV-ATTR:host'])

    def test_image_trait_on_volume_backed_instance(self):
        """Tests that when trying to launch a volume-backed instance with a
        required trait on the image metadata contained within the volume,
        the instance ends up on the single compute node resource provider
        that also has that trait in Placement.
        """
        # Decorate compute2 resource provider with volume image metadata trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute2.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_SGX'])

        self.useFixture(nova_fixtures.CinderFixture(self))
        # Create our server with a volume containing the image meta data with a
        # required trait
        server = self._create_volume_backed_server_with_traits(
            self.flavor_without_trait['id'],
            nova_fixtures.CinderFixture.
            IMAGE_WITH_TRAITS_BACKED_VOL)

        server = self._wait_for_state_change(server, 'ACTIVE')
        # Assert the server ended up on the expected compute host that has
        # the required trait.
        self.assertEqual(self.compute2.host, server['OS-EXT-SRV-ATTR:host'])

    def test_flavor_image_trait_on_volume_backed_instance(self):
        """Tests that when trying to launch a volume-backed instance with a
        required trait on flavor AND a required trait on the image metadata
        contained within the volume, the instance ends up on the single
        compute node resource provider that also has those traits in Placement.
        """
        # Decorate compute2 resource provider with volume image metadata trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute2.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_VMX',
                                            'HW_CPU_X86_SGX'])

        self.useFixture(nova_fixtures.CinderFixture(self))
        # Create our server with a flavor trait and a volume containing the
        # image meta data with a required trait
        server = self._create_volume_backed_server_with_traits(
            self.flavor_with_trait['id'],
            nova_fixtures.CinderFixture.
            IMAGE_WITH_TRAITS_BACKED_VOL)

        server = self._wait_for_state_change(server, 'ACTIVE')
        # Assert the server ended up on the expected compute host that has
        # the required trait.
        self.assertEqual(self.compute2.host, server['OS-EXT-SRV-ATTR:host'])

    def test_flavor_traits_based_scheduling_no_valid_host(self):
        """Tests that a server create request using a required trait expressed
         in flavor fails to find a valid host since no compute node resource
         providers have the trait.
        """

        # Decorate compute1 resource provider with the image trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute1.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_SGX'])

        server = self._create_server_with_traits(self.flavor_with_trait['id'],
                                                 self.image_id_without_trait)
        # The server should go to ERROR state because there is no valid host.
        server = self._wait_for_state_change(server, 'ERROR')
        self.assertIsNone(server['OS-EXT-SRV-ATTR:host'])
        # Make sure the failure was due to NoValidHost by checking the fault.
        self.assertIn('fault', server)
        self.assertIn('No valid host', server['fault']['message'])

    def test_image_traits_based_scheduling_no_valid_host(self):
        """Tests that a server create request using a required trait expressed
         in image fails to find a valid host since no compute node resource
         providers have the trait.
        """

        # Decorate compute1 resource provider with that flavor trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute1.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_VMX'])

        server = self._create_server_with_traits(
            self.flavor_without_trait['id'], self.image_id_with_trait)
        # The server should go to ERROR state because there is no valid host.
        server = self._wait_for_state_change(server, 'ERROR')
        self.assertIsNone(server['OS-EXT-SRV-ATTR:host'])
        # Make sure the failure was due to NoValidHost by checking the fault.
        self.assertIn('fault', server)
        self.assertIn('No valid host', server['fault']['message'])

    def test_flavor_image_traits_based_scheduling_no_valid_host(self):
        """Tests that a server create request using a required trait expressed
         in flavor AND a required trait expressed in the image fails to find a
         valid host since no compute node resource providers have the trait.
        """

        server = self._create_server_with_traits(
            self.flavor_with_trait['id'], self.image_id_with_trait)
        # The server should go to ERROR state because there is no valid host.
        server = self._wait_for_state_change(server, 'ERROR')
        self.assertIsNone(server['OS-EXT-SRV-ATTR:host'])
        # Make sure the failure was due to NoValidHost by checking the fault.
        self.assertIn('fault', server)
        self.assertIn('No valid host', server['fault']['message'])

    def test_image_trait_on_volume_backed_instance_no_valid_host(self):
        """Tests that when trying to launch a volume-backed instance with a
        required trait on the image metadata contained within the volume
        fails to find a valid host since no compute node resource providers
        have the trait.
        """
        self.useFixture(nova_fixtures.CinderFixture(self))
        # Create our server with a volume
        server = self._create_volume_backed_server_with_traits(
            self.flavor_without_trait['id'],
            nova_fixtures.CinderFixture.
            IMAGE_WITH_TRAITS_BACKED_VOL)

        # The server should go to ERROR state because there is no valid host.
        server = self._wait_for_state_change(server, 'ERROR')
        self.assertIsNone(server['OS-EXT-SRV-ATTR:host'])
        # Make sure the failure was due to NoValidHost by checking the fault.
        self.assertIn('fault', server)
        self.assertIn('No valid host', server['fault']['message'])

    def test_rebuild_instance_with_image_traits(self):
        """Rebuilds a server with a different image which has traits
        associated with it and which will run it through the scheduler to
        validate the image is still OK with the compute host that the
        instance is running on.
         """
        # Decorate compute2 resource provider with both flavor and image trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute2.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_VMX',
                                            'HW_CPU_X86_SGX'])
        # make sure we start with no usage on the compute node
        rp_usages = self._get_provider_usages(rp_uuid)
        self.assertEqual({'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0}, rp_usages)

        # create a server without traits on image and with traits on flavour
        server = self._create_server_with_traits(
            self.flavor_with_trait['id'], self.image_id_without_trait)
        server = self._wait_for_state_change(server, 'ACTIVE')

        # make the compute node full and ensure rebuild still succeed
        inv = {"resource_class": "VCPU",
               "total": 1}
        self._set_inventory(rp_uuid, inv)

        # Now rebuild the server with a different image with traits
        rebuild_req_body = {
            'rebuild': {
                'imageRef': self.image_id_with_trait
            }
        }
        self.api.api_post('/servers/%s/action' % server['id'],
                          rebuild_req_body)
        self._wait_for_server_parameter(
            server, {'OS-EXT-STS:task_state': None})

        allocs = self._get_allocations_by_server_uuid(server['id'])
        self.assertIn(rp_uuid, allocs)

        # Assert the server ended up on the expected compute host that has
        # the required trait.
        self.assertEqual(self.compute2.host, server['OS-EXT-SRV-ATTR:host'])

    def test_rebuild_instance_with_image_traits_no_host(self):
        """Rebuilding a server with a different image which has required
        traits on the image fails to valid the host that this server is
        currently running, cause the compute host resource provider is not
        associated with similar trait.
        """
        # Decorate compute2 resource provider with traits on flavor
        rp_uuid = self._get_provider_uuid_by_host(self.compute2.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_VMX'])

        # make sure we start with no usage on the compute node
        rp_usages = self._get_provider_usages(rp_uuid)
        self.assertEqual({'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0}, rp_usages)

        # create a server without traits on image and with traits on flavour
        server = self._create_server_with_traits(
            self.flavor_with_trait['id'], self.image_id_without_trait)
        server = self._wait_for_state_change(server, 'ACTIVE')

        # Now rebuild the server with a different image with traits
        rebuild_req_body = {
            'rebuild': {
                'imageRef': self.image_id_with_trait
            }
        }

        self.api.api_post('/servers/%s/action' % server['id'],
                          rebuild_req_body)
        # Look for the failed rebuild action.
        self._wait_for_action_fail_completion(
            server, instance_actions.REBUILD, 'rebuild_server')
        # Assert the server image_ref was rolled back on failure.
        server = self.api.get_server(server['id'])
        self.assertEqual(self.image_id_without_trait, server['image']['id'])

        # The server should be in ERROR state
        self.assertEqual('ERROR', server['status'])
        self.assertEqual("No valid host was found. Image traits cannot be "
                         "satisfied by the current resource providers. "
                         "Either specify a different image during rebuild "
                         "or create a new server with the specified image.",
                         server['fault']['message'])

    def test_rebuild_instance_with_image_traits_no_image_change(self):
        """Rebuilds a server with a same image which has traits
        associated with it and which will run it through the scheduler to
        validate the image is still OK with the compute host that the
        instance is running on.
         """
        # Decorate compute2 resource provider with both flavor and image trait.
        rp_uuid = self._get_provider_uuid_by_host(self.compute2.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_VMX',
                                            'HW_CPU_X86_SGX'])
        # make sure we start with no usage on the compute node
        rp_usages = self._get_provider_usages(rp_uuid)
        self.assertEqual({'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0},
                         rp_usages)

        # create a server with traits in both image and flavour
        server = self._create_server_with_traits(
            self.flavor_with_trait['id'], self.image_id_with_trait)
        server = self._wait_for_state_change(server,
                                             'ACTIVE')

        # Now rebuild the server with a different image with traits
        rebuild_req_body = {
            'rebuild': {
                'imageRef': self.image_id_with_trait
            }
        }
        self.api.api_post('/servers/%s/action' % server['id'],
                          rebuild_req_body)
        self._wait_for_server_parameter(
            server, {'OS-EXT-STS:task_state': None})

        allocs = self._get_allocations_by_server_uuid(server['id'])
        self.assertIn(rp_uuid, allocs)

        # Assert the server ended up on the expected compute host that has
        # the required trait.
        self.assertEqual(self.compute2.host,
                         server['OS-EXT-SRV-ATTR:host'])

    def test_rebuild_instance_with_image_traits_and_forbidden_flavor_traits(
                                                                        self):
        """Rebuilding a server with a different image which has required
        traits on the image fails to validate image traits because flavor
        associated with the current instance has the similar trait that is
        forbidden
        """
        # Decorate compute2 resource provider with traits on flavor
        rp_uuid = self._get_provider_uuid_by_host(self.compute2.host)
        self._set_provider_traits(rp_uuid, ['HW_CPU_X86_VMX'])

        # make sure we start with no usage on the compute node
        rp_usages = self._get_provider_usages(rp_uuid)
        self.assertEqual({'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0}, rp_usages)

        # create a server with forbidden traits on flavor and no triats on
        # image
        server = self._create_server_with_traits(
            self.flavor_with_forbidden_trait['id'],
            self.image_id_without_trait)
        server = self._wait_for_state_change(server, 'ACTIVE')

        # Now rebuild the server with a different image with traits
        rebuild_req_body = {
            'rebuild': {
                'imageRef': self.image_id_with_trait
            }
        }

        self.api.api_post('/servers/%s/action' % server['id'],
                          rebuild_req_body)
        # Look for the failed rebuild action.
        self._wait_for_action_fail_completion(
            server, instance_actions.REBUILD, 'rebuild_server')
        # Assert the server image_ref was rolled back on failure.
        server = self.api.get_server(server['id'])
        self.assertEqual(self.image_id_without_trait, server['image']['id'])

        # The server should be in ERROR state
        self.assertEqual('ERROR', server['status'])
        self.assertEqual("No valid host was found. Image traits are part of "
                         "forbidden traits in flavor associated with the "
                         "server. Either specify a different image during "
                         "rebuild or create a new server with the specified "
                         "image and a compatible flavor.",
                         server['fault']['message'])


class ServerTestV256Common(integrated_helpers._IntegratedTestBase):
    api_major_version = 'v2.1'
    microversion = '2.56'
    ADMIN_API = True

    def _setup_compute_service(self):
        # Set up 3 compute services in the same cell
        for host in ('host1', 'host2', 'host3'):
            self.start_service('compute', host=host)

    def _create_server(self, target_host=None):
        server = self._build_server(
            image_uuid='a2459075-d96c-40d5-893e-577ff92e721c')
        server.update({'networks': 'auto'})
        if target_host is not None:
            server['availability_zone'] = 'nova:%s' % target_host
        post = {'server': server}
        response = self.api.api_post('/servers', post).body
        return response['server']

    @staticmethod
    def _get_target_and_other_hosts(host):
        target_other_hosts = {'host1': ['host2', 'host3'],
                              'host2': ['host3', 'host1'],
                              'host3': ['host1', 'host2']}
        return target_other_hosts[host]


class ServerTestV256MultiCellTestCase(ServerTestV256Common):
    """Negative test to ensure we fail with ComputeHostNotFound if we try to
    target a host in another cell from where the instance lives.
    """
    NUMBER_OF_CELLS = 2

    def _setup_compute_service(self):
        # Set up 2 compute services in different cells
        host_to_cell_mappings = {
            'host1': 'cell1',
            'host2': 'cell2'}
        for host in sorted(host_to_cell_mappings):
            self.start_service('compute', host=host,
                               cell_name=host_to_cell_mappings[host])

    def test_migrate_server_to_host_in_different_cell(self):
        # We target host1 specifically so that we have a predictable target for
        # the cold migration in cell2.
        server = self._create_server(target_host='host1')
        server = self._wait_for_state_change(server, 'ACTIVE')

        self.assertEqual('host1', server['OS-EXT-SRV-ATTR:host'])
        ex = self.assertRaises(client.OpenStackApiException,
                               self.api.post_server_action,
                               server['id'],
                               {'migrate': {'host': 'host2'}})
        # When the API pulls the instance out of cell1, the context is targeted
        # to cell1, so when the compute API resize() method attempts to lookup
        # the target host in cell1, it will result in a ComputeHostNotFound
        # error.
        self.assertEqual(400, ex.response.status_code)
        self.assertIn('Compute host host2 could not be found', str(ex))


class ServerTestV256SingleCellMultiHostTestCase(ServerTestV256Common):
    """Happy path test where we create a server on one host, migrate it to
    another host of our choosing and ensure it lands there.
    """

    def test_migrate_server_to_host_in_same_cell(self):
        server = self._create_server()
        server = self._wait_for_state_change(server, 'ACTIVE')
        source_host = server['OS-EXT-SRV-ATTR:host']
        target_host = self._get_target_and_other_hosts(source_host)[0]
        self.api.post_server_action(server['id'],
                                    {'migrate': {'host': target_host}})
        # Assert the server is now on the target host.
        server = self.api.get_server(server['id'])
        self.assertEqual(target_host, server['OS-EXT-SRV-ATTR:host'])


class ServerTestV256RescheduleTestCase(ServerTestV256Common):

    @mock.patch.object(compute_manager.ComputeManager, '_prep_resize',
                       side_effect=exception.MigrationError(
                           reason='Test Exception'))
    def test_migrate_server_not_reschedule(self, mock_prep_resize):
        server = self._create_server()
        found_server = self._wait_for_state_change(server, 'ACTIVE')

        target_host, other_host = self._get_target_and_other_hosts(
            found_server['OS-EXT-SRV-ATTR:host'])

        self.assertRaises(client.OpenStackApiException,
                          self.api.post_server_action,
                          server['id'],
                          {'migrate': {'host': target_host}})
        self.assertEqual(1, mock_prep_resize.call_count)
        found_server = self.api.get_server(server['id'])
        # Check that rescheduling is not occurred.
        self.assertNotEqual(other_host, found_server['OS-EXT-SRV-ATTR:host'])


class ConsumerGenerationConflictTest(
        integrated_helpers.ProviderUsageBaseTestCase):

    # we need the medium driver to be able to allocate resource not just for
    # a single instance
    compute_driver = 'fake.MediumFakeDriver'

    def setUp(self):
        super(ConsumerGenerationConflictTest, self).setUp()
        flavors = self.api.get_flavors()
        self.flavor = flavors[0]
        self.other_flavor = flavors[1]
        self.compute1 = self._start_compute('compute1')
        self.compute2 = self._start_compute('compute2')

    def test_create_server_fails_as_placement_reports_consumer_conflict(self):
        server_req = self._build_server(
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            flavor_id=self.flavor['id'],
            networks='none')

        # We cannot pre-create a consumer with the uuid of the instance created
        # below as that uuid is generated. Instead we have to simulate that
        # Placement returns 409, consumer generation conflict for the PUT
        # /allocation request the scheduler does for the instance.
        with mock.patch('keystoneauth1.adapter.Adapter.put') as mock_put:
            rsp = fake_requests.FakeResponse(
                409,
                jsonutils.dumps(
                    {'errors': [
                        {'code': 'placement.concurrent_update',
                         'detail': 'consumer generation conflict'}]}))
            mock_put.return_value = rsp

            created_server = self.api.post_server({'server': server_req})
            server = self._wait_for_state_change(created_server, 'ERROR')

        # This is not a conflict that the API user can ever resolve. It is a
        # serious inconsistency in our database or a bug in the scheduler code
        # doing the claim.
        self.assertEqual(500, server['fault']['code'])
        self.assertIn('Failed to update allocations for consumer',
                      server['fault']['message'])

        allocations = self._get_allocations_by_server_uuid(server['id'])
        self.assertEqual(0, len(allocations))

        self._delete_and_check_allocations(server)

    def test_migrate_claim_on_dest_fails(self):
        source_hostname = self.compute1.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)

        server = self._boot_and_check_allocations(self.flavor, source_hostname)

        # We have to simulate that Placement returns 409, consumer generation
        # conflict for the PUT /allocation request the scheduler does on the
        # destination host for the instance.
        with mock.patch('keystoneauth1.adapter.Adapter.put') as mock_put:
            rsp = fake_requests.FakeResponse(
                409,
                jsonutils.dumps(
                    {'errors': [
                        {'code': 'placement.concurrent_update',
                         'detail': 'consumer generation conflict'}]}))
            mock_put.return_value = rsp

            request = {'migrate': None}
            self.api.post_server_action(server['id'], request,
                                        check_response_status=[202])
            self._wait_for_server_parameter(server,
                                            {'OS-EXT-STS:task_state': None})

        self._assert_resize_migrate_action_fail(
            server, instance_actions.MIGRATE, 'claim_resources')

        # The migration is aborted so the instance is ACTIVE on the source
        # host instead of being in VERIFY_RESIZE state.
        server = self.api.get_server(server['id'])
        self.assertEqual('ACTIVE', server['status'])
        self.assertEqual(source_hostname, server['OS-EXT-SRV-ATTR:host'])

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor)

        self.assertFlavorMatchesAllocation(self.flavor, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_migrate_move_allocation_fails_due_to_conflict(self):
        source_hostname = self.compute1.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)

        server = self._boot_and_check_allocations(self.flavor, source_hostname)

        rsp = fake_requests.FakeResponse(
            409,
            jsonutils.dumps(
                {'errors': [
                    {'code': 'placement.concurrent_update',
                     'detail': 'consumer generation conflict'}]}))

        with mock.patch('keystoneauth1.adapter.Adapter.post',
                        autospec=True) as mock_post:
            mock_post.return_value = rsp

            request = {'migrate': None}
            self.api.post_server_action(server['id'], request,
                                        check_response_status=[202])
            self._wait_for_server_parameter(server,
                                            {'OS-EXT-STS:task_state': None})

        self._assert_resize_migrate_action_fail(
            server, instance_actions.MIGRATE, 'move_allocations')

        self.assertEqual(1, mock_post.call_count)

        migrations = self.api.get_migrations()
        self.assertEqual(1, len(migrations))
        self.assertEqual('migration', migrations[0]['migration_type'])
        self.assertEqual(server['id'], migrations[0]['instance_uuid'])
        self.assertEqual(source_hostname, migrations[0]['source_compute'])
        self.assertEqual('error', migrations[0]['status'])

        # The migration is aborted so the instance is ACTIVE on the source
        # host instead of being in VERIFY_RESIZE state.
        server = self.api.get_server(server['id'])
        self.assertEqual('ACTIVE', server['status'])
        self.assertEqual(source_hostname, server['OS-EXT-SRV-ATTR:host'])

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor)

        self.assertFlavorMatchesAllocation(self.flavor, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_confirm_migrate_delete_alloc_on_source_fails(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(self.flavor, source_hostname)
        self._migrate_and_check_allocations(
            server, self.flavor, source_rp_uuid, dest_rp_uuid)

        rsp = fake_requests.FakeResponse(
            409,
            jsonutils.dumps(
                {'errors': [
                    {'code': 'placement.concurrent_update',
                     'detail': 'consumer generation conflict'}]}))

        with mock.patch('keystoneauth1.adapter.Adapter.put',
                        autospec=True) as mock_put:
            mock_put.return_value = rsp

            post = {'confirmResize': None}
            self.api.post_server_action(
                server['id'], post, check_response_status=[204])
            server = self._wait_for_state_change(server, 'ERROR')
            self.assertIn('Failed to delete allocations',
                          server['fault']['message'])

        self.assertEqual(1, mock_put.call_count)

        migrations = self.api.get_migrations()
        self.assertEqual(1, len(migrations))
        self.assertEqual('migration', migrations[0]['migration_type'])
        self.assertEqual(server['id'], migrations[0]['instance_uuid'])
        self.assertEqual(source_hostname, migrations[0]['source_compute'])
        self.assertEqual('error', migrations[0]['status'])

        # NOTE(gibi): Nova leaks the allocation held by the migration_uuid even
        # after the instance is deleted. At least nova logs a fat ERROR.
        self.assertIn('Deleting allocation in placement for migration %s '
                      'failed. The instance %s will be put to ERROR state but '
                      'the allocation held by the migration is leaked.' %
                      (migrations[0]['uuid'], server['id']),
                      self.stdlog.logger.output)
        self._delete_server(server)
        self.notifier.wait_for_versioned_notifications('instance.delete.end')

        allocations = self._get_allocations_by_server_uuid(
            migrations[0]['uuid'])
        self.assertEqual(1, len(allocations))

    def test_revert_migrate_delete_dest_allocation_fails_due_to_conflict(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        server = self._boot_and_check_allocations(self.flavor, source_hostname)
        self._migrate_and_check_allocations(
            server, self.flavor, source_rp_uuid, dest_rp_uuid)

        rsp = fake_requests.FakeResponse(
            409,
            jsonutils.dumps(
                {'errors': [
                    {'code': 'placement.concurrent_update',
                     'detail': 'consumer generation conflict'}]}))

        with mock.patch('keystoneauth1.adapter.Adapter.post',
                        autospec=True) as mock_post:
            mock_post.return_value = rsp

            post = {'revertResize': None}
            self.api.post_server_action(server['id'], post)
            server = self._wait_for_state_change(server, 'ERROR')

        self.assertEqual(1, mock_post.call_count)

        migrations = self.api.get_migrations()
        self.assertEqual(1, len(migrations))
        self.assertEqual('migration', migrations[0]['migration_type'])
        self.assertEqual(server['id'], migrations[0]['instance_uuid'])
        self.assertEqual(source_hostname, migrations[0]['source_compute'])
        self.assertEqual('error', migrations[0]['status'])

        # NOTE(gibi): Nova leaks the allocation held by the migration_uuid even
        # after the instance is deleted. At least nova logs a fat ERROR.
        self.assertIn('Reverting allocation in placement for migration %s '
                      'failed. The instance %s will be put into ERROR state '
                      'but the allocation held by the migration is leaked.' %
                      (migrations[0]['uuid'], server['id']),
                      self.stdlog.logger.output)
        self._delete_server(server)
        self.notifier.wait_for_versioned_notifications('instance.delete.end')

        allocations = self._get_allocations_by_server_uuid(
            migrations[0]['uuid'])
        self.assertEqual(1, len(allocations))

    def test_revert_resize_same_host_delete_dest_fails_due_to_conflict(self):
        # make sure that the test only uses a single host
        compute2_service_id = self.admin_api.get_services(
            host=self.compute2.host, binary='nova-compute')[0]['id']
        self.admin_api.put_service(compute2_service_id, {'status': 'disabled'})

        hostname = self.compute1.manager.host
        rp_uuid = self._get_provider_uuid_by_host(hostname)

        server = self._boot_and_check_allocations(self.flavor, hostname)

        self._resize_to_same_host_and_check_allocations(
            server, self.flavor, self.other_flavor, rp_uuid)

        rsp = fake_requests.FakeResponse(
            409,
            jsonutils.dumps(
                {'errors': [
                    {'code': 'placement.concurrent_update',
                     'detail': 'consumer generation conflict'}]}))
        with mock.patch('keystoneauth1.adapter.Adapter.post',
                        autospec=True) as mock_post:
            mock_post.return_value = rsp

            post = {'revertResize': None}
            self.api.post_server_action(server['id'], post)
            server = self._wait_for_state_change(server, 'ERROR',)

        self.assertEqual(1, mock_post.call_count)

        migrations = self.api.get_migrations()
        self.assertEqual(1, len(migrations))
        self.assertEqual('resize', migrations[0]['migration_type'])
        self.assertEqual(server['id'], migrations[0]['instance_uuid'])
        self.assertEqual(hostname, migrations[0]['source_compute'])
        self.assertEqual('error', migrations[0]['status'])

        # NOTE(gibi): Nova leaks the allocation held by the migration_uuid even
        # after the instance is deleted. At least nova logs a fat ERROR.
        self.assertIn('Reverting allocation in placement for migration %s '
                      'failed. The instance %s will be put into ERROR state '
                      'but the allocation held by the migration is leaked.' %
                      (migrations[0]['uuid'], server['id']),
                      self.stdlog.logger.output)
        self._delete_server(server)
        self.notifier.wait_for_versioned_notifications('instance.delete.end')

        allocations = self._get_allocations_by_server_uuid(
            migrations[0]['uuid'])
        self.assertEqual(1, len(allocations))

    def test_force_live_migrate_claim_on_dest_fails(self):
        # Normal live migrate moves source allocation from instance to
        # migration like a normal migrate tested above.
        # Normal live migrate claims on dest like a normal boot tested above.
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host

        # the ability to force live migrate a server is removed entirely in
        # 2.68
        self.api.microversion = '2.67'

        server = self._boot_and_check_allocations(
            self.flavor, source_hostname)

        rsp = fake_requests.FakeResponse(
            409,
            jsonutils.dumps(
                {'errors': [
                    {'code': 'placement.concurrent_update',
                     'detail': 'consumer generation conflict'}]}))
        with mock.patch('keystoneauth1.adapter.Adapter.put',
                        autospec=True) as mock_put:
            mock_put.return_value = rsp

            post = {
                'os-migrateLive': {
                    'host': dest_hostname,
                    'block_migration': True,
                    'force': True,
                }
            }

            self.api.post_server_action(server['id'], post)
            server = self._wait_for_state_change(server, 'ERROR')

        self.assertEqual(1, mock_put.call_count)

        # This is not a conflict that the API user can ever resolve. It is a
        # serious inconsistency in our database or a bug in the scheduler code
        # doing the claim.
        self.assertEqual(500, server['fault']['code'])
        # The instance is in ERROR state so the allocations are in limbo but
        # at least we expect that when the instance is deleted the allocations
        # are cleaned up properly.
        self._delete_and_check_allocations(server)

    def test_live_migrate_drop_allocation_on_source_fails(self):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        # the ability to force live migrate a server is removed entirely in
        # 2.68
        self.api.microversion = '2.67'

        server = self._boot_and_check_allocations(
            self.flavor, source_hostname)

        orig_put = adapter.Adapter.put

        rsp = fake_requests.FakeResponse(
            409,
            jsonutils.dumps(
                {'errors': [
                    {'code': 'placement.concurrent_update',
                     'detail': 'consumer generation conflict'}]}))

        self.adapter_put_call_count = 0

        def fake_put(_self, url, **kwargs):
            self.adapter_put_call_count += 1
            migration_uuid = self.get_migration_uuid_for_instance(server['id'])
            if url == '/allocations/%s' % migration_uuid:
                return rsp
            else:
                return orig_put(_self, url, **kwargs)

        with mock.patch('keystoneauth1.adapter.Adapter.put', new=fake_put):
            post = {
                'os-migrateLive': {
                    'host': dest_hostname,
                    'block_migration': True,
                    'force': True,
                }
            }

            self.api.post_server_action(server['id'], post)

            # nova does the source host cleanup _after_ setting the migration
            # to completed and sending end notifications so we have to wait
            # here a bit.
            time.sleep(1)

            # Nova failed to clean up on the source host. This right now puts
            # the instance to ERROR state and fails the migration.
            server = self._wait_for_server_parameter(server,
                {'OS-EXT-SRV-ATTR:host': dest_hostname,
                 'status': 'ERROR'})
            self._wait_for_migration_status(server, ['error'])
            self.notifier.wait_for_versioned_notifications(
                'instance.live_migration_post.end')

        # 1 claim on destination, 1 normal delete on dest that fails,
        self.assertEqual(2, self.adapter_put_call_count)

        # As the cleanup on the source host failed Nova leaks the allocation
        # held by the migration.
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor)
        migration_uuid = self.get_migration_uuid_for_instance(server['id'])
        self.assertFlavorMatchesAllocation(self.flavor, migration_uuid,
                                           source_rp_uuid)

        self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor)

        self.assertFlavorMatchesAllocation(self.flavor, server['id'],
                                           dest_rp_uuid)

        # NOTE(gibi): Nova leaks the allocation held by the migration_uuid even
        # after the instance is deleted. At least nova logs a fat ERROR.
        self.assertIn('Deleting allocation in placement for migration %s '
                      'failed. The instance %s will be put to ERROR state but '
                      'the allocation held by the migration is leaked.' %
                      (migration_uuid, server['id']),
                      self.stdlog.logger.output)

        self._delete_server(server)
        self.notifier.wait_for_versioned_notifications('instance.delete.end')

        self.assertFlavorMatchesAllocation(self.flavor, migration_uuid,
                                           source_rp_uuid)

    def _test_evacuate_fails_allocating_on_dest_host(self, force):
        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host

        # the ability to force evacuate a server is removed entirely in 2.68
        self.api.microversion = '2.67'

        server = self._boot_and_check_allocations(
            self.flavor, source_hostname)

        source_compute_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']

        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        rsp = fake_requests.FakeResponse(
            409,
            jsonutils.dumps(
                {'errors': [
                    {'code': 'placement.concurrent_update',
                     'detail': 'consumer generation conflict'}]}))

        with mock.patch('keystoneauth1.adapter.Adapter.put',
                        autospec=True) as mock_put:
            mock_put.return_value = rsp

            post = {
                'force': force,
            }

            if force:
                post['host'] = dest_hostname

            server = self._evacuate_server(
                server, expected_state='ERROR', extra_post_args=post,
                expected_migration_status='error')

        self.assertEqual(1, mock_put.call_count)

        # As nova failed to allocate on the dest host we only expect allocation
        # on the source
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor)

        self.assertRequestMatchesUsage({'VCPU': 0,
                                        'MEMORY_MB': 0,
                                        'DISK_GB': 0}, dest_rp_uuid)

        self.assertFlavorMatchesAllocation(self.flavor, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_force_evacuate_fails_allocating_on_dest_host(self):
        self._test_evacuate_fails_allocating_on_dest_host(force=True)

    def test_evacuate_fails_allocating_on_dest_host(self):
        self._test_evacuate_fails_allocating_on_dest_host(force=False)


class ServerMovingTestsWithNestedComputes(ServerMovingTests):
    """Runs all the server moving tests while the computes have nested trees.
    The servers still do not request resources from any child provider though.
    """
    compute_driver = 'fake.MediumFakeDriverWithNestedCustomResources'


class ServerMovingTestsWithNestedResourceRequests(
    ServerMovingTestsWithNestedComputes):
    """Runs all the server moving tests while the computes have nested trees.
    The servers also request resources from child providers.
    """

    def setUp(self):
        super(ServerMovingTestsWithNestedResourceRequests, self).setUp()
        # modify the flavors used in the ServerMoving test base class to
        # require one piece of CUSTOM_MAGIC resource as well.

        for flavor in [self.flavor1, self.flavor2, self.flavor3]:
            self.api.post_extra_spec(
                flavor['id'], {'extra_specs': {'resources:CUSTOM_MAGIC': 1}})
            # save the extra_specs in the flavor stored in the test case as
            # well
            flavor['extra_specs'] = {'resources:CUSTOM_MAGIC': 1}

    def _check_allocation_during_evacuate(
            self, flavor, server_uuid, source_root_rp_uuid, dest_root_rp_uuid):
        # NOTE(gibi): evacuate is the only case when the same consumer has
        # allocation from two different RP trees so we need a special check
        # here.
        allocations = self._get_allocations_by_server_uuid(server_uuid)
        source_rps = self._get_all_rp_uuids_in_a_tree(source_root_rp_uuid)
        dest_rps = self._get_all_rp_uuids_in_a_tree(dest_root_rp_uuid)

        self.assertEqual(set(source_rps + dest_rps), set(allocations))

        total_source_allocation = collections.defaultdict(int)
        total_dest_allocation = collections.defaultdict(int)
        for rp, alloc in allocations.items():
            for rc, value in alloc['resources'].items():
                if rp in source_rps:
                    total_source_allocation[rc] += value
                else:
                    total_dest_allocation[rc] += value

        self.assertEqual(
            self._resources_from_flavor(flavor), total_source_allocation)
        self.assertEqual(
            self._resources_from_flavor(flavor), total_dest_allocation)

    def test_live_migrate_force(self):
        # Nova intentionally does not support force live-migrating server
        # with nested allocations.

        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host
        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        # the ability to force live migrate a server is removed entirely in
        # 2.68
        self.api.microversion = '2.67'

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)
        post = {
            'os-migrateLive': {
                'host': dest_hostname,
                'block_migration': True,
                'force': True,
            }
        }

        self.api.post_server_action(server['id'], post)
        self._wait_for_migration_status(server, ['error'])
        self._wait_for_server_parameter(server,
            {'OS-EXT-SRV-ATTR:host': source_hostname,
             'status': 'ACTIVE'})
        self.assertIn('Unable to move instance %s to host host2. The instance '
                      'has complex allocations on the source host so move '
                      'cannot be forced.' %
                      server['id'],
                      self.stdlog.logger.output)

        self._run_periodics()

        # NOTE(danms): There should be no usage for the dest
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        # the server has an allocation on only the source node
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def _test_evacuate_forced_host(self, keep_hypervisor_state):
        # Nova intentionally does not support force evacuating server
        # with nested allocations.

        source_hostname = self.compute1.host
        dest_hostname = self.compute2.host

        # the ability to force evacuate a server is removed entirely in 2.68
        self.api.microversion = '2.67'

        server = self._boot_and_check_allocations(
            self.flavor1, source_hostname)

        source_compute_id = self.admin_api.get_services(
            host=source_hostname, binary='nova-compute')[0]['id']

        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        # evacuate the server and force the destination host which bypasses
        # the scheduler
        post = {
            'host': dest_hostname,
            'force': True
        }

        server = self._evacuate_server(
            server, extra_post_args=post, expected_migration_status='error',
            expected_host=source_hostname)

        self.assertIn('Unable to move instance %s to host host2. The instance '
                      'has complex allocations on the source host so move '
                      'cannot be forced.' %
                      server['id'],
                      self.stdlog.logger.output)

        # Run the periodics to show those don't modify allocations.
        self._run_periodics()

        source_rp_uuid = self._get_provider_uuid_by_host(source_hostname)
        dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname)

        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        # restart the source compute
        self.compute1 = self.restart_compute_service(
            self.compute1, keep_hypervisor_state=keep_hypervisor_state)
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'false'})

        # Run the periodics again to show they don't change anything.
        self._run_periodics()

        # When the source node starts up nothing should change as the
        # evacuation failed
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)

        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)


# NOTE(gibi): There is another case NestedToFlat but that leads to the same
# code path that NestedToNested as in both cases the instance will have
# complex allocation on the source host which is already covered in
# ServerMovingTestsWithNestedResourceRequests
class ServerMovingTestsFromFlatToNested(
        integrated_helpers.ProviderUsageBaseTestCase):
    """Tests trying to move servers from a compute with a flat RP tree to a
    compute with a nested RP tree and assert that the blind allocation copy
    fails cleanly.
    """

    REQUIRES_LOCKING = True
    compute_driver = 'fake.MediumFakeDriver'

    def setUp(self):
        super(ServerMovingTestsFromFlatToNested, self).setUp()
        flavors = self.api.get_flavors()
        self.flavor1 = flavors[0]
        self.api.post_extra_spec(
            self.flavor1['id'], {'extra_specs': {'resources:CUSTOM_MAGIC': 1}})
        self.flavor1['extra_specs'] = {'resources:CUSTOM_MAGIC': 1}

    def test_force_live_migrate_from_flat_to_nested(self):
        # first compute will start with the flat RP tree but we add
        # CUSTOM_MAGIC inventory to the root compute RP
        orig_update_provider_tree = fake.MediumFakeDriver.update_provider_tree

        # the ability to force live migrate a server is removed entirely in
        # 2.68
        self.api.microversion = '2.67'

        def stub_update_provider_tree(self, provider_tree, nodename,
                                      allocations=None):
            # do the regular inventory update
            orig_update_provider_tree(
                self, provider_tree, nodename, allocations)
            if nodename == 'host1':
                # add the extra resource
                inv = provider_tree.data(nodename).inventory
                inv['CUSTOM_MAGIC'] = {
                    'total': 10,
                    'reserved': 0,
                    'min_unit': 1,
                    'max_unit': 10,
                    'step_size': 1,
                    'allocation_ratio': 1,
                }
                provider_tree.update_inventory(nodename, inv)

        self.stub_out('nova.virt.fake.FakeDriver.update_provider_tree',
                      stub_update_provider_tree)
        self.compute1 = self._start_compute(host='host1')
        source_rp_uuid = self._get_provider_uuid_by_host('host1')

        server = self._boot_and_check_allocations(self.flavor1, 'host1')
        # start the second compute with nested RP tree
        self.flags(
            compute_driver='fake.MediumFakeDriverWithNestedCustomResources')
        self.compute2 = self._start_compute(host='host2')

        # try to force live migrate from flat to nested.
        post = {
            'os-migrateLive': {
                'host': 'host2',
                'block_migration': True,
                'force': True,
            }
        }

        self.api.post_server_action(server['id'], post)
        # We expect that the migration will fail as force migrate tries to
        # blindly copy the source allocation to the destination but on the
        # destination there is no inventory of CUSTOM_MAGIC on the compute node
        # provider as that resource is reported on a child provider.
        self._wait_for_server_parameter(server,
            {'OS-EXT-SRV-ATTR:host': 'host1',
             'status': 'ACTIVE'})

        migration = self._wait_for_migration_status(server, ['error'])
        self.assertEqual('host1', migration['source_compute'])
        self.assertEqual('host2', migration['dest_compute'])

        # Nova fails the migration because it ties to allocation CUSTOM_MAGIC
        # from the dest node root RP and placement rejects the that allocation.
        self.assertIn("Unable to allocate inventory: Inventory for "
                      "'CUSTOM_MAGIC'", self.stdlog.logger.output)
        self.assertIn('No valid host was found. Unable to move instance %s to '
                      'host host2. There is not enough capacity on the host '
                      'for the instance.' % server['id'],
                      self.stdlog.logger.output)

        dest_rp_uuid = self._get_provider_uuid_by_host('host2')

        # There should be no usage for the dest
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        # and everything stays at the source
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)

    def test_force_evacuate_from_flat_to_nested(self):
        # first compute will start with the flat RP tree but we add
        # CUSTOM_MAGIC inventory to the root compute RP
        orig_update_provider_tree = fake.MediumFakeDriver.update_provider_tree

        # the ability to force evacuate a server is removed entirely in 2.68
        self.api.microversion = '2.67'

        def stub_update_provider_tree(self, provider_tree, nodename,
                                      allocations=None):
            # do the regular inventory update
            orig_update_provider_tree(
                self, provider_tree, nodename, allocations)
            if nodename == 'host1':
                # add the extra resource
                inv = provider_tree.data(nodename).inventory
                inv['CUSTOM_MAGIC'] = {
                    'total': 10,
                    'reserved': 0,
                    'min_unit': 1,
                    'max_unit': 10,
                    'step_size': 1,
                    'allocation_ratio': 1,
                }
                provider_tree.update_inventory(nodename, inv)

        self.stub_out('nova.virt.fake.FakeDriver.update_provider_tree',
                      stub_update_provider_tree)
        self.compute1 = self._start_compute(host='host1')
        source_rp_uuid = self._get_provider_uuid_by_host('host1')

        server = self._boot_and_check_allocations(self.flavor1, 'host1')
        # start the second compute with nested RP tree
        self.flags(
            compute_driver='fake.MediumFakeDriverWithNestedCustomResources')
        self.compute2 = self._start_compute(host='host2')

        source_compute_id = self.admin_api.get_services(
            host='host1', binary='nova-compute')[0]['id']
        self.compute1.stop()
        # force it down to avoid waiting for the service group to time out
        self.admin_api.put_service(
            source_compute_id, {'forced_down': 'true'})

        # try to force evacuate from flat to nested.
        post = {
            'host': 'host2',
            'force': True,
        }

        self._evacuate_server(
            server, extra_post_args=post, expected_host='host1',
            expected_migration_status='error')

        # We expect that the evacuation will fail as force evacuate tries to
        # blindly copy the source allocation to the destination but on the
        # destination there is no inventory of CUSTOM_MAGIC on the compute node
        # provider as that resource is reported on a child provider.

        migration = self._wait_for_migration_status(server, ['error'])
        self.assertEqual('host1', migration['source_compute'])
        self.assertEqual('host2', migration['dest_compute'])

        # Nova fails the migration because it ties to allocation CUSTOM_MAGIC
        # from the dest node root RP and placement rejects the that allocation.
        self.assertIn("Unable to allocate inventory: Inventory for "
                      "'CUSTOM_MAGIC'", self.stdlog.logger.output)
        self.assertIn('No valid host was found. Unable to move instance %s to '
                      'host host2. There is not enough capacity on the host '
                      'for the instance.' % server['id'],
                      self.stdlog.logger.output)

        dest_rp_uuid = self._get_provider_uuid_by_host('host2')

        # There should be no usage for the dest
        self.assertRequestMatchesUsage(
            {'VCPU': 0,
             'MEMORY_MB': 0,
             'DISK_GB': 0}, dest_rp_uuid)

        # and everything stays at the source
        self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1)
        self.assertFlavorMatchesAllocation(self.flavor1, server['id'],
                                           source_rp_uuid)

        self._delete_and_check_allocations(server)


class AcceleratorServerBase(integrated_helpers.ProviderUsageBaseTestCase):

    compute_driver = 'fake.SmallFakeDriver'

    def setUp(self):
        super(AcceleratorServerBase, self).setUp()
        self.cyborg = self.useFixture(nova_fixtures.CyborgFixture())
        # dict of form {$compute_rp_uuid: $device_rp_uuid}
        self.device_rp_map = {}
        # self.NUM_HOSTS should be set up by derived classes
        if not hasattr(self, 'NUM_HOSTS'):
            self.NUM_HOSTS = 1
        self._setup_compute_nodes_and_device_rps()

    def _setup_compute_nodes_and_device_rps(self):
        self.compute_services = []
        # all device rp uuids
        self.device_rp_uuids = []
        # device_rp_map[host_rp_uuid]: device rp uuid belong to host
        self.device_rp_map = {}

        for i in range(self.NUM_HOSTS):
            svc = self._start_compute(host='accel_host' + str(i))
            self.compute_services.append(svc)
        # host index map to compute rp uuid
        self.compute_rp_uuids = [
           rp['uuid'] for rp in self._get_all_providers()
           if rp['uuid'] == rp['root_provider_uuid']]

        # host0 have most arqs setup, except the last one
        # host1 have the last arq of cyborg arqs list
        # only 2 host is supported now
        for host_index, host_rp_uuid in enumerate(self.compute_rp_uuids):
            if host_index == 0:
                host_dev_rps = []
                # host0 have most arqs setup, except the last one
                for i, _ in enumerate(self.cyborg.arq_list[0:-1]):
                    device_rp = self._create_device_rp(i, host_rp_uuid)
                    host_dev_rps.append(device_rp)
                self.device_rp_map[host_rp_uuid] = host_dev_rps
                self.device_rp_uuids.extend(host_dev_rps)
            else:
                # second host have only the last one arq
                host0_devs_num = len(self.cyborg.arq_list[0:-1])
                device_rp = self._create_device_rp(
                    host_index + host0_devs_num, host_rp_uuid)
                self.device_rp_uuids.append(device_rp)
                self.device_rp_map[host_rp_uuid] = [device_rp]

    def _create_device_rp(self, index, compute_rp_uuid,
                          resource='FPGA', res_amt=2):
        """Created nested RP for a device. There is one per host.

        :param index: Number of the device rp uuid for this setup
        :param compute_rp_uuid: Resource provider UUID of the host.
        :param resource: Placement resource name.
            Assumed to be a standard resource class.
        :param res_amt: Amount of the resource.
        :returns: Device RP UUID
        """
        resp = self._post_nested_resource_provider(
            'FakeDevice' + str(index), parent_rp_uuid=compute_rp_uuid)
        device_rp_uuid = resp['uuid']
        inventory = {
            'resource_provider_generation': 0,
            'inventories': {
                resource: {
                    'total': res_amt,
                    'allocation_ratio': 1.0,
                    'max_unit': res_amt,
                    'min_unit': 1,
                    'reserved': 0,
                    'step_size': 1,
                 }
             },
        }
        self._update_inventory(device_rp_uuid, inventory)
        self._create_trait(self.cyborg.trait)
        self._set_provider_traits(device_rp_uuid, [self.cyborg.trait])
        return device_rp_uuid

    def _post_nested_resource_provider(self, rp_name, parent_rp_uuid):
        body = {'name': rp_name, 'parent_provider_uuid': parent_rp_uuid}
        return self.placement.post(
            url='/resource_providers', version='1.20', body=body).body

    def _create_acc_flavor(self):
        extra_specs = {'accel:device_profile': self.cyborg.dp_name}
        flavor_id = self._create_flavor(name='acc.tiny',
                                        extra_spec=extra_specs)
        return flavor_id

    def _check_allocations_usage(
        self, server, check_other_host_alloc=True, dev_alloced=1):
        # Check allocations on host where instance is running
        # This is also works for port with accelerator device
        server_uuid = server['id']
        allocated_device_rps = []
        hostname = server['OS-EXT-SRV-ATTR:host']
        server_host_rp_uuid = self._get_provider_uuid_by_host(hostname)
        expected_host_alloc = {
            'resources': {'VCPU': 2, 'MEMORY_MB': 2048, 'DISK_GB': 20},
        }

        alloc_dev_nums = 0
        # host regular resources assert
        host_alloc = self._get_allocations_by_provider_uuid(
            server_host_rp_uuid)
        self.assertEqual(expected_host_alloc, host_alloc[server_uuid])

        for device_rp_uuid in self.device_rp_map[server_host_rp_uuid]:
            device_alloc = (
                self._get_allocations_by_provider_uuid(device_rp_uuid))
            if device_alloc:
                res = device_alloc[server_uuid]['resources']
                alloc_dev_nums += res.get('FPGA', 0)
                # placement may allocated multi devices in same
                # device_rp or use different device_rp for each
                # ports. we get resources report in either:
                # ------- {'resources': {'FPGA': 2}}
                # or:
                # ------- {'resources': {'FPGA': 1}}
                # ------- {'resources': {'FPGA': 1}}
                for i in range(res.get('FPGA', 0)):
                    allocated_device_rps.append(device_rp_uuid)

        # allocated smartnic devices asserts
        self.assertEqual(dev_alloced, alloc_dev_nums)

        # NOTE(Sundar): ARQs for an instance could come from different
        # devices in the same host, in general.
        expected_arq_bind_info = []
        for rp in allocated_device_rps:
            expected_arq_bind_info.append(('Bound', hostname,
                                       rp, server_uuid))

        arqs = nova_fixtures.CyborgFixture.fake_get_arqs_for_instance(
            server_uuid)
        # The state is hardcoded but other fields come from the test case.
        arq_bind_info = [(arq['state'], arq['hostname'],
                          arq['device_rp_uuid'], arq['instance_uuid'])
                         for arq in arqs]
        self.assertListEqual(sorted(expected_arq_bind_info),
            sorted(arq_bind_info))

        # ensure another host did not alloc anything
        if check_other_host_alloc:
            for i in range(self.NUM_HOSTS):
                compute_uuid = self.compute_rp_uuids[i]
                if compute_uuid != server_host_rp_uuid:
                    host_alloc = self._get_allocations_by_provider_uuid(
                        compute_uuid)
                    self.assertEqual({}, host_alloc)

    def _check_no_allocs_usage(self, server_uuid):
        allocs = self._get_allocations_by_server_uuid(server_uuid)
        self.assertEqual({}, allocs)

    def _check_resource_released(self, server):
        hostname = server['OS-EXT-SRV-ATTR:host']
        server_host_rp_uuid = self._get_provider_uuid_by_host(hostname)
        for i in range(self.NUM_HOSTS):
            compute_uuid = self.compute_rp_uuids[i]
            host_alloc = self._get_allocations_by_provider_uuid(compute_uuid)
            device_rp_uuids = self.device_rp_map[compute_uuid]
            if compute_uuid == server_host_rp_uuid:
                self.assertEqual({}, host_alloc)
            for dev_rp_uuid in device_rp_uuids:
                dev_alloc = self._get_allocations_by_provider_uuid(dev_rp_uuid)
                self.assertEqual({}, dev_alloc)
        # checking ARQ for server is released
        alloc_arqs = self.cyborg.fake_get_arqs_for_instance(server['id'])
        self.assertEqual([], alloc_arqs)

    def _test_evacuate(self, server, num_hosts):
        server_hostname = server['OS-EXT-SRV-ATTR:host']
        for i in range(num_hosts):
            if self.compute_services[i].host == server_hostname:
                compute_to_stop = self.compute_services[i]
            else:
                compute_to_evacuate = self.compute_services[i]
        # Stop and force down the compute service.
        compute_id = self.admin_api.get_services(
            host=server_hostname, binary='nova-compute')[0]['id']
        compute_to_stop.stop()
        self.admin_api.put_service(compute_id, {'forced_down': 'true'})
        return compute_to_stop, compute_to_evacuate


class AcceleratorServerTest(AcceleratorServerBase):
    def setUp(self):
        self.NUM_HOSTS = 1
        super(AcceleratorServerTest, self).setUp()

    def _get_server(self, expected_state='ACTIVE'):
        flavor_id = self._create_acc_flavor()
        server_name = 'accel_server1'
        server = self._create_server(
            server_name, flavor_id=flavor_id,
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks='none', expected_state=expected_state)
        return server

    def test_create_delete_server_ok(self):
        server = self._get_server()

        # Verify that the host name and the device rp UUID are set properly.
        # Other fields in the ARQ are hardcoded data from the fixture.
        arqs = self.cyborg.fake_get_arqs_for_instance(server['id'])
        for arq in arqs:
            self.assertIn(arq['device_rp_uuid'], self.device_rp_uuids)
            self.assertEqual(server['OS-EXT-SRV-ATTR:host'], arq['hostname'])

        # Check allocations and usage
        self._check_allocations_usage(server)

        # Delete server and check that ARQs got deleted
        self.api.delete_server(server['id'])
        self._wait_until_deleted(server)
        self.cyborg.mock_del_arqs.assert_called_once_with(server['id'])

        # Check that resources are freed
        self._check_no_allocs_usage(server['id'])

    def test_create_server_with_error(self):

        def throw_error(*args, **kwargs):
            raise exception.BuildAbortException(reason='',
                    instance_uuid='fake')

        self.stub_out('nova.virt.fake.FakeDriver.spawn', throw_error)

        server = self._get_server(expected_state='ERROR')
        server_uuid = server['id']
        # Check that Cyborg was called to delete ARQs
        self.cyborg.mock_del_arqs.assert_called_once_with(server_uuid)

        # BuildAbortException will not trigger a reschedule and the placement
        # cleanup is the last step in the compute manager after instance state
        # setting, fault recording and notification sending. So we have no
        # other way than simply wait to ensure the placement cleanup happens
        # before we assert it.
        def placement_cleanup():
            # An instance in error state should consume no resources
            self._check_no_allocs_usage(server_uuid)

        self._wait_for_assert(placement_cleanup)

        self.api.delete_server(server_uuid)
        self._wait_until_deleted(server)
        # Verify that there is one more call to delete ARQs
        self.cyborg.mock_del_arqs.assert_has_calls(
            [mock.call(server_uuid), mock.call(server_uuid)])

        # Verify that no allocations/usages remain after deletion
        self._check_no_allocs_usage(server_uuid)

    def test_create_server_with_local_delete(self):
        """Delete the server when compute service is down."""
        server = self._get_server()
        server_uuid = server['id']

        # Stop the server.
        self.api.post_server_action(server_uuid, {'os-stop': {}})
        self._wait_for_state_change(server, 'SHUTOFF')
        self._check_allocations_usage(server)
        # Stop and force down the compute service.
        compute_id = self.admin_api.get_services(
            host='accel_host0', binary='nova-compute')[0]['id']
        self.compute_services[0].stop()
        self.admin_api.put_service(compute_id, {'forced_down': 'true'})

        # Delete the server with compute service down.
        self.api.delete_server(server_uuid)
        self.cyborg.mock_del_arqs.assert_called_once_with(server_uuid)
        self._check_no_allocs_usage(server_uuid)

        # Restart the compute service to see if anything fails.
        self.admin_api.put_service(compute_id, {'forced_down': 'false'})
        self.compute_services[0].start()


class AcceleratorServerReschedTest(AcceleratorServerBase):

    def setUp(self):
        self.NUM_HOSTS = 2
        super(AcceleratorServerReschedTest, self).setUp()

    def test_resched(self):
        orig_spawn = fake.FakeDriver.spawn

        def fake_spawn(*args, **kwargs):
            fake_spawn.count += 1
            if fake_spawn.count == 1:
                raise exception.ComputeResourcesUnavailable(
                    reason='First host fake fail.', instance_uuid='fake')
            else:
                orig_spawn(*args, **kwargs)
        fake_spawn.count = 0

        with mock.patch('nova.virt.fake.FakeDriver.spawn', new=fake_spawn):
            flavor_id = self._create_acc_flavor()
            server_name = 'accel_server1'
            server = self._create_server(
                server_name, flavor_id=flavor_id,
                image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
                networks='none', expected_state='ACTIVE')

        self.assertEqual(2, fake_spawn.count)
        self._check_allocations_usage(server)
        self.cyborg.mock_del_arqs.assert_called_once_with(server['id'])

    def test_resched_fails(self):

        def throw_error(*args, **kwargs):
            raise exception.ComputeResourcesUnavailable(reason='',
                    instance_uuid='fake')

        self.stub_out('nova.virt.fake.FakeDriver.spawn', throw_error)

        flavor_id = self._create_acc_flavor()
        server_name = 'accel_server1'
        server = self._create_server(
            server_name, flavor_id=flavor_id,
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks='none', expected_state='ERROR')

        server_uuid = server['id']
        self._check_no_allocs_usage(server_uuid)
        self.cyborg.mock_del_arqs.assert_has_calls(
            [mock.call(server_uuid),
             mock.call(server_uuid),
             mock.call(server_uuid)])


class AcceleratorServerOpsTest(AcceleratorServerBase):

    def setUp(self):
        self.NUM_HOSTS = 2  # 2nd host needed for evacuate
        super(AcceleratorServerOpsTest, self).setUp()
        flavor_id = self._create_acc_flavor()
        server_name = 'accel_server1'
        self.server = self._create_server(
            server_name, flavor_id=flavor_id,
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks='none', expected_state='ACTIVE')

    def test_soft_reboot_ok(self):
        self._reboot_server(self.server)
        self._check_allocations_usage(self.server)

    def test_hard_reboot_ok(self):
        self._reboot_server(self.server, hard=True)
        self._check_allocations_usage(self.server)

    def test_pause_unpause_ok(self):
        # Pause and unpause should work with accelerators.
        # This is not a general test of un/pause functionality.
        self.api.post_server_action(self.server['id'], {'pause': {}})
        self._wait_for_state_change(self.server, 'PAUSED')
        self._check_allocations_usage(self.server)
        # ARQs didn't get deleted (and so didn't have to be re-created).
        self.cyborg.mock_del_arqs.assert_not_called()

        self.api.post_server_action(self.server['id'], {'unpause': {}})
        self._wait_for_state_change(self.server, 'ACTIVE')
        self._check_allocations_usage(self.server)

    def test_stop_start_ok(self):
        # Stop and start should work with accelerators.
        # This is not a general test of start/stop functionality.
        self.api.post_server_action(self.server['id'], {'os-stop': {}})
        self._wait_for_state_change(self.server, 'SHUTOFF')
        self._check_allocations_usage(self.server)
        # ARQs didn't get deleted (and so didn't have to be re-created).
        self.cyborg.mock_del_arqs.assert_not_called()

        self.api.post_server_action(self.server['id'], {'os-start': {}})
        self._wait_for_state_change(self.server, 'ACTIVE')
        self._check_allocations_usage(self.server)

    def test_lock_unlock_ok(self):
        # Lock/unlock are no-ops for accelerators.
        self.api.post_server_action(self.server['id'], {'lock': {}})
        server = self.api.get_server(self.server['id'])
        self.assertTrue(server['locked'])
        self._check_allocations_usage(self.server)

        self.api.post_server_action(self.server['id'], {'unlock': {}})
        server = self.api.get_server(self.server['id'])
        self.assertTrue(not server['locked'])
        self._check_allocations_usage(self.server)

    def test_backup_ok(self):
        self.api.post_server_action(self.server['id'],
            {'createBackup': {
                'name': 'Backup 1',
                'backup_type': 'daily',
                'rotation': 1}})
        self._check_allocations_usage(self.server)

    def test_create_image_ok(self):  # snapshot
        self.api.post_server_action(self.server['id'],
            {'createImage': {
                'name': 'foo-image',
                'metadata': {'meta_var': 'meta_val'}}})
        self._check_allocations_usage(self.server)

    def test_rescue_unrescue_ok(self):
        self.api.post_server_action(self.server['id'],
            {'rescue': {
                'adminPass': 'MySecretPass',
                'rescue_image_ref': '70a599e0-31e7-49b7-b260-868f441e862b'}})
        self._check_allocations_usage(self.server)
        # ARQs didn't get deleted (and so didn't have to be re-created).
        self.cyborg.mock_del_arqs.assert_not_called()
        self._wait_for_state_change(self.server, 'RESCUE')

        self.api.post_server_action(self.server['id'], {'unrescue': {}})
        self._check_allocations_usage(self.server)

    def test_evacuate_ok(self):
        server_hostname = self.server['OS-EXT-SRV-ATTR:host']
        arqs = self.cyborg.fake_get_arqs_for_instance(self.server['id'])
        compute_to_stop, compute_to_evacuate = self._test_evacuate(
            self.server, self.NUM_HOSTS)
        self._evacuate_server(self.server, {'host': compute_to_evacuate.host})
        compute_to_stop.start()
        self.server = self.api.get_server(self.server['id'])
        arqs_new = self.cyborg.fake_get_arqs_for_instance(self.server['id'])
        evac_hostname = self.server['OS-EXT-SRV-ATTR:host']
        self.assertNotEqual(server_hostname, evac_hostname)
        self.assertEqual(server_hostname, arqs[0]['hostname'])
        self.assertEqual(evac_hostname, arqs_new[0]['hostname'])

    def test_rebuild_ok(self):
        rebuild_image_ref = self.glance.auto_disk_config_enabled_image['id']
        self.api.post_server_action(self.server['id'],
            {'rebuild': {
                'imageRef': rebuild_image_ref,
                'OS-DCF:diskConfig': 'AUTO'}})
        self.notifier.wait_for_versioned_notifications('instance.rebuild.end')
        self._wait_for_state_change(self.server, 'ACTIVE')
        self._check_allocations_usage(self.server)

    def test_shelve_and_unshelve_ok(self):
        self.flags(shelved_offload_time=1)
        arqs = self.cyborg.fake_get_arqs_for_instance(self.server['id'])
        self.assertEqual(len(arqs), 1)
        self._shelve_server(self.server, 'SHELVED')
        arqs = self.cyborg.fake_get_arqs_for_instance(self.server['id'])
        self.assertEqual(len(arqs), 1)
        self._unshelve_server(self.server)
        arqs = self.cyborg.fake_get_arqs_for_instance(self.server['id'])
        self.assertEqual(len(arqs), 1)

    def test_shelve_offload_and_unshelve_ok(self):
        self.flags(shelved_offload_time=-1)
        arqs = self.cyborg.fake_get_arqs_for_instance(self.server['id'])
        self.assertEqual(len(arqs), 1)
        self._shelve_server(self.server, 'SHELVED')
        # arq deleted during shelve_offload_server
        self._shelve_offload_server(self.server)
        arqs = self.cyborg.fake_get_arqs_for_instance(self.server['id'])
        self.assertEqual(len(arqs), 0)
        self._unshelve_server(self.server)
        arqs = self.cyborg.fake_get_arqs_for_instance(self.server['id'])
        self.assertEqual(len(arqs), 1)

    def test_resize_fails(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'],
            {'resize': {'flavorRef': '2', 'OS-DCF:diskConfig': 'AUTO'}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def test_suspend_fails(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'], {'suspend': {}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def test_migrate_fails(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'], {'migrate': {}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def test_live_migrate_fails(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'],
            {'migrate': {'host': 'accel_host1'}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    @mock.patch.object(objects.service, 'get_minimum_version_all_cells')
    def test_evacuate_old_compute(self, old_compute_version):
        """Tests when the source compute service is too old to call
        evacuate so OpenStackApiException is raised.
        """
        old_compute_version.return_value = 52
        _, compute_to_evacuate = self._test_evacuate(
            self.server, self.NUM_HOSTS)

        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'],
            {'evacuate': {
                 'host': compute_to_evacuate.host,
                 'adminPass': 'MySecretPass'}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    @mock.patch.object(objects.service, 'get_minimum_version_all_cells')
    def test_rebuild_old_compute(self, old_compute_version):
        """Tests when the source compute service is too old to call
        rebuild so OpenStackApiException is raised.
        """
        old_compute_version.return_value = 52
        rebuild_image_ref = self.glance.auto_disk_config_enabled_image['id']

        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'],
            {'rebuild': {
                'imageRef': rebuild_image_ref,
                'OS-DCF:diskConfig': 'AUTO'}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    @mock.patch.object(objects.service, 'get_minimum_version_all_cells')
    def test_shelve_old_compute(self, old_compute_version):
        """Tests when the source compute service is too old to call
        shelve so OpenStackApiException is raised.
        """
        old_compute_version.return_value = 53
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'],
            {'shelve': {}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def _test_shelve_instance_with_compute_rpc_pin(
            self, version_cap, body=None):
        self.flags(compute=version_cap, group='upgrade_levels')

        self.flags(shelved_offload_time=-1)
        self.api.post_server_action(self.server['id'], body)
        self._wait_for_state_change(self.server, 'SHELVED')

    def test_shelve_with_compute_rpc_pin_5_0(self):
        self.flags(compute=5.0, group='upgrade_levels')
        compute_rpcapi.reset_globals()
        ex = self.assertRaises(
            client.OpenStackApiException, self.api.post_server_action,
            self.server['id'], {'shelve': {}})
        self.assertEqual(400, ex.response.status_code)

    def test_shelve_instance_5_13(self):
        body = {'shelve': {}}
        self._test_shelve_instance_with_compute_rpc_pin(
                '5.13', body=body)

    def _test_shelve_offload_instance_with_compute_rpc_pin(self, version_cap):
        self.flags(compute=version_cap, group='upgrade_levels')

        self.flags(shelved_offload_time=2)
        self.api.post_server_action(self.server['id'], {'shelve': {}})
        self._wait_for_state_change(self.server, 'SHELVED')

        self.api.post_server_action(self.server['id'], {'shelveOffload': {}})
        self._wait_for_state_change(self.server, 'SHELVED_OFFLOADED')

    def test_shelve_offload_instance_5_0(self):
        self._test_shelve_offload_instance_with_compute_rpc_pin('5.0')

    def test_shelve_offload_instance_5_13(self):
        self._test_shelve_offload_instance_with_compute_rpc_pin('5.13')

    def _test_unshelve_instance_with_compute_rpc_pin(
            self, version_cap, body=None):
        self.flags(compute=version_cap, group='upgrade_levels')

        self.api.microversion = '2.87'
        self.api.post_server_action(self.server['id'], {'shelve': {}})
        self._wait_for_state_change(self.server, 'SHELVED_OFFLOADED')

        self.api.post_server_action(self.server['id'], body)
        self._wait_for_state_change(self.server, 'ACTIVE')

    def test_unshelve_instance_5_0(self):
        body = {'unshelve': None}
        self._test_unshelve_instance_with_compute_rpc_pin(
                '5.0', body=body)

    def test_unshelve_instance_5_2(self):
        body = {'unshelve': None}
        self._test_unshelve_instance_with_compute_rpc_pin(
                '5.2', body=body)

    def test_unshelve_instance_5_13(self):
        body = {'unshelve': None}
        self._test_unshelve_instance_with_compute_rpc_pin(
                '5.13', body=body)


class TwoPortsAcceleratorServerOpsTest(AcceleratorServerBase):
    def setUp(self):
        super(TwoPortsAcceleratorServerOpsTest, self).setUp()
        self.NUM_HOSTS = 1
        self.flavor_id = self._create_flavor(name='tiny')
        self.server_name = 'two_ports_accel_server'
        self.neutron._networks[
            self.neutron.network_2['id']] = self.neutron.network_2
        self.neutron._subnets[
            self.neutron.subnet_2['id']] = self.neutron.subnet_2
        for port in self.neutron.ports_with_accelerator:
            self.neutron._ports[port['id']] = copy.deepcopy(port)
        self.ports = self.neutron.ports_with_accelerator

    def _check_neutron_binding_info_cleaned(self):
        for port in self.neutron.ports_with_accelerator:
            updated_port = self.neutron.show_port(port['id'])['port']
            binding_profile = neutronapi.get_binding_profile(updated_port)
            self.assertNotIn('arq_uuid', binding_profile)
            self.assertNotIn('pci_slot', binding_profile)

    def test_create_with_two_accels_ok(self):
        ports = self.neutron.ports_with_accelerator
        server_name = self.flavor_id
        server = self._create_server(
                  server_name, flavor_id=self.flavor_id,
                  image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
                  networks=[
                      {'port': ports[0]['id']},
                      {'port': ports[1]['id']}
                    ],
                  expected_state='ACTIVE')
        self._check_allocations_usage(server, dev_alloced=2)
        # Clean up
        self._delete_server(server)
        self._check_no_allocs_usage(server['id'])
        self._check_resource_released(server)
        # check neutron binding cleared
        self._check_neutron_binding_info_cleaned()

    def test_create_with_two_accels_all_binding_error(self):
        def throw_error(*args, **kwargs):
            raise exception.AcceleratorRequestOpFailed(reason='',
                    instance_uuid='fake')
        self.stub_out('nova.accelerator.cyborg._CyborgClient.bind_arqs',
            throw_error)
        ports = self.neutron.ports_with_accelerator
        server_name = self.flavor_id
        server = self._create_server(
                  server_name, flavor_id=self.flavor_id,
                  image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
                  networks=[
                      {'port': ports[0]['id']},
                      {'port': ports[1]['id']}
                    ],
                  expected_state='ERROR')

        # Clean up, no need to delete
        self._delete_server(server)
        self._check_no_allocs_usage(server["id"])
        self._check_neutron_binding_info_cleaned()


class PortAcceleratorServerOpsTest(AcceleratorServerBase):

    def setUp(self):
        self.NUM_HOSTS = 2  # 2nd host needed for evacuate
        super(PortAcceleratorServerOpsTest, self).setUp()
        self.flavor_id = self._create_flavor(name='tiny')
        self.server_name = 'port_accel_server'
        # add extra port for accelerator
        self.neutron._networks[
            self.neutron.network_2['id']] = self.neutron.network_2
        self.neutron._subnets[
            self.neutron.subnet_2['id']] = self.neutron.subnet_2
        self.port = self.neutron.ports_with_accelerator[0]
        self.neutron._ports[self.port['id']] = copy.deepcopy(self.port)
        self.server = self._create_server(
            self.server_name, flavor_id=self.flavor_id,
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks=[{'port': self.port['id']}], expected_state='ACTIVE')

        # check allocation and cyborg arq bind info
        self._check_allocations_usage(self.server)

        # check neutron binding info
        updated_port = self.neutron.show_port(self.port['id'])['port']
        binding_profile = neutronapi.get_binding_profile(updated_port)
        arqs = nova_fixtures.CyborgFixture.fake_get_arqs_for_instance(
            self.server['id'])
        pci = arqs[0]['attach_handle_info']
        pci_addr = "%s:%s:%s.%s" % (pci['domain'], pci['bus'],
            pci['device'], pci['function'])
        bind_info = {
              'physical_network': pci['physical_network'],
              'arq_uuid': arqs[0]['uuid'],
              'pci_slot': pci_addr}

        self.assertEqual(bind_info, binding_profile)

    def test_delete_server(self):
        self._delete_server(self.server)
        self._check_resource_released(self.server)
        self._check_no_allocs_usage(self.server['id'])
        # check neutron binding cleared
        port = self.neutron.ports_with_accelerator[0]
        updated_port = self.neutron.show_port(port['id'])['port']
        binding_profile = neutronapi.get_binding_profile(updated_port)
        self.assertNotIn('arq_uuid', binding_profile)
        self.assertNotIn('pci_slot', binding_profile)

    def test_soft_reboot_ok(self):
        self._reboot_server(self.server)
        self._check_allocations_usage(self.server)

    def test_hard_reboot_ok(self):
        self._reboot_server(self.server, hard=True)
        self._check_allocations_usage(self.server)

    def test_pause_unpause_ok(self):
        # pause and unpause should work with accelerators backed port.
        # This is not a general test of un/pause functionality.
        self.api.post_server_action(self.server['id'], {'pause': {}})
        self._wait_for_state_change(self.server, 'PAUSED')
        self._check_allocations_usage(self.server)
        # ARQs didn't get deleted (and so didn't have to be re-created).
        self.cyborg.mock_del_arqs.assert_not_called()

        self.api.post_server_action(self.server['id'], {'unpause': {}})
        self._wait_for_state_change(self.server, 'ACTIVE')
        self._check_allocations_usage(self.server)

    def test_stop_start_ok(self):
        # Stop and start should work with accelerators backed port.
        self.api.post_server_action(self.server['id'], {'os-stop': {}})
        self._wait_for_state_change(self.server, 'SHUTOFF')
        self._check_allocations_usage(self.server)
        # ARQs didn't get deleted (and so didn't have to be re-created).
        self.cyborg.mock_del_arqs.assert_not_called()
        self.api.post_server_action(self.server['id'], {'os-start': {}})
        self._wait_for_state_change(self.server, 'ACTIVE')
        self._check_allocations_usage(self.server)

    def test_lock_unlock_ok(self):
        # Lock/unlock are no-ops for accelerators.
        self.api.post_server_action(self.server['id'], {'lock': {}})
        server = self.api.get_server(self.server['id'])
        self.assertTrue(server['locked'])
        self._check_allocations_usage(self.server)

        self.api.post_server_action(self.server['id'], {'unlock': {}})
        server = self.api.get_server(self.server['id'])
        self.assertTrue(not server['locked'])
        self._check_allocations_usage(self.server)

    def test_backup_ok(self):
        self.api.post_server_action(self.server['id'],
            {'createBackup': {
                'name': 'Backup 1',
                'backup_type': 'daily',
                'rotation': 1}})
        self._check_allocations_usage(self.server)

    def test_create_image_ok(self):  # snapshot
        self.api.post_server_action(self.server['id'],
            {'createImage': {
                'name': 'foo-image',
                'metadata': {'meta_var': 'meta_val'}}})
        self._check_allocations_usage(self.server)

    def test_rescue_unrescue_ok(self):
        self.api.post_server_action(self.server['id'],
            {'rescue': {
                'adminPass': 'MySecretPass',
                'rescue_image_ref': '70a599e0-31e7-49b7-b260-868f441e862b'}})
        self._check_allocations_usage(self.server)
        # ARQs didn't get deleted (and so didn't have to be re-created).
        self.cyborg.mock_del_arqs.assert_not_called()
        self._wait_for_state_change(self.server, 'RESCUE')

        self.api.post_server_action(self.server['id'], {'unrescue': {}})
        self._check_allocations_usage(self.server)

    def test_rebuild_ok(self):
        rebuild_image_ref = self.glance.auto_disk_config_enabled_image['id']
        self.api.post_server_action(self.server['id'],
            {'rebuild': {
                'imageRef': rebuild_image_ref,
                'OS-DCF:diskConfig': 'AUTO'}})
        self.notifier.wait_for_versioned_notifications('instance.rebuild.end')
        self._wait_for_state_change(self.server, 'ACTIVE')
        self._check_allocations_usage(self.server)

    def test_resize_reject(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'],
            {'resize': {'flavorRef': '2', 'OS-DCF:diskConfig': 'AUTO'}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def test_suspend_reject(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'], {'suspend': {}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def test_migrate_reject(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'], {'migrate': {}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def test_live_migrate_reject(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'],
            {'live-migration': {'host': 'accel_host1'}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def test_shelve_reject(self):
        compute_rpcapi.reset_globals()
        ex = self.assertRaises(
            client.OpenStackApiException, self.api.post_server_action,
            self.server['id'], {'shelve': {}})
        self.assertEqual(400, ex.response.status_code)

    def test_shelve_offload_reject(self):
        compute_rpcapi.reset_globals()
        ex = self.assertRaises(
            client.OpenStackApiException, self.api.post_server_action,
            self.server['id'], {'shelveOffload': {}})
        self.assertEqual(400, ex.response.status_code)

    def test_evacuate_reject(self):
        _, compute_to_evacuate = self._test_evacuate(
            self.server, self.NUM_HOSTS)
        ex = self.assertRaises(client.OpenStackApiException,
            self.api.post_server_action, self.server['id'],
            {'evacuate': {
                 'host': compute_to_evacuate.host,
                 'adminPass': 'MySecretPass'}})
        self.assertEqual(400, ex.response.status_code)
        self._check_allocations_usage(self.server)

    def test_port_attach_interface_reject(self):
        # try to add a port with resource request
        post = {
                'interfaceAttachment': {
                    'port_id': self.port['id']
                }}
        ex = self.assertRaises(
            client.OpenStackApiException, self.api.attach_interface,
                self.server['id'], post)
        self.assertEqual(400, ex.response.status_code)

    def test_port_detach_interface_reject(self):
        # try to add a port with resource request
        ex = self.assertRaises(
            client.OpenStackApiException, self.api.detach_interface,
                self.server['id'], self.port['id'])
        self.assertEqual(400, ex.response.status_code)


class PortAcceleratorServerCreateRejectTest(AcceleratorServerBase):

    def setUp(self):
        self.NUM_HOSTS = 1
        super(PortAcceleratorServerCreateRejectTest, self).setUp()
        self.flavor_id = self._create_flavor(name='tiny')
        self.server_name = 'port_accel_server'
        # add extra port for accelerator
        self.neutron._networks[
            self.neutron.network_2['id']] = self.neutron.network_2
        self.neutron._subnets[
            self.neutron.subnet_2['id']] = self.neutron.subnet_2
        self.port = self.neutron.ports_with_multi_accelerators[0]
        self.neutron._ports[self.port['id']] = copy.deepcopy(self.port)

    def test_reject_multi_device_port(self):
        ex = self.assertRaises(client.OpenStackApiException,
            self._create_server,
            self.server_name, flavor_id=self.flavor_id,
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks=[{'port': self.port['id']}], expected_state='ACTIVE')
        self.assertEqual(400, ex.response.status_code)

    def test_reject_if_have_old_version_service(self):
        def get_min_version(*args, **kwargs):
            return 56
        self.stub_out('nova.objects.service.get_minimum_version_all_cells',
            get_min_version)
        ex = self.assertRaises(client.OpenStackApiException,
            self._create_server,
            self.server_name, flavor_id=self.flavor_id,
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks=[{'port': self.port['id']}], expected_state='ACTIVE')
        self.assertEqual(400, ex.response.status_code)


class PortAndFlavorAccelsServerCreateTest(AcceleratorServerBase):

    def setUp(self):
        self.NUM_HOSTS = 1
        super(PortAndFlavorAccelsServerCreateTest, self).setUp()

        # accelerator from flavor: device profile 'fakedev-dp'
        self.flavor_id = self._create_acc_flavor()
        self.server_name = 'port_accel_server'

        # accelerator from port: device profile 'fakedev-dp-port'
        self.neutron._networks[
            self.neutron.network_2['id']] = self.neutron.network_2
        self.neutron._subnets[
            self.neutron.subnet_2['id']] = self.neutron.subnet_2
        self.port = self.neutron.ports_with_accelerator[0]
        self.neutron._ports[self.port['id']] = copy.deepcopy(self.port)

    def test_accels_from_both_port_and_flavor(self):
        self.server = self._create_server(
            self.server_name, flavor_id=self.flavor_id,
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks=[{'port': self.port['id']}], expected_state='ACTIVE')

        # check allocation and cyborg arq bind info
        self._check_allocations_usage(self.server, dev_alloced=2)

        # check neutron binding info
        updated_port = self.neutron.show_port(self.port['id'])['port']
        binding_profile = neutronapi.get_binding_profile(updated_port)
        arqs = nova_fixtures.CyborgFixture.fake_get_arqs_for_instance(
            self.server['id'])

        for arq in arqs:
            # find which args belong to port
            if arq["device_profile_name"] == 'fakedev-dp-port':
                pci = arqs['attach_handle_info']
                pci_addr = "%s:%s:%s.%s" % (pci['domain'], pci['bus'],
                    pci['device'], pci['function'])
                bind_info = {
                    'physical_network': pci['physical_network'],
                    'arq_uuid': arqs['uuid'],
                    'pci_slot': pci_addr}
                self.assertEqual(bind_info, binding_profile)

        self._delete_server(self.server)
        self._check_resource_released(self.server)
        self._check_no_allocs_usage(self.server['id'])
        # check neutron binding cleared
        updated_port = self.neutron.show_port(self.port['id'])['port']
        binding_profile = neutronapi.get_binding_profile(updated_port)
        self.assertNotIn('arq_uuid', binding_profile)
        self.assertNotIn('pci_slot', binding_profile)


class PortBindingShelvedServerTest(integrated_helpers._IntegratedTestBase):
    """Tests for servers with ports."""

    compute_driver = 'fake.SmallFakeDriver'

    def setUp(self):
        super(PortBindingShelvedServerTest, self).setUp()
        self.flavor_id = self._create_flavor(
            disk=10, ephemeral=20, swap=5 * 1024)

    def test_shelve_offload_with_port(self):
        # Do not wait before offloading
        self.flags(shelved_offload_time=0)

        server = self._create_server(
            flavor_id=self.flavor_id,
            networks=[{'port': self.neutron.port_1['id']}])

        port = self.neutron.show_port(self.neutron.port_1['id'])['port']

        # Assert that the port is actually associated to the instance
        self.assertEqual(port['device_id'], server['id'])
        self.assertEqual(port['binding:host_id'], 'compute')
        self.assertEqual(port['binding:status'], 'ACTIVE')

        # Do shelve
        server = self._shelve_server(server, 'SHELVED_OFFLOADED')

        # Retrieve the updated port
        port = self.neutron.show_port(self.neutron.port_1['id'])['port']

        # Assert that the port is still associated to the instance
        # but the binding is not on the compute anymore
        self.assertEqual(port['device_id'], server['id'])
        self.assertIsNone(port['binding:host_id'])
        self.assertNotIn('binding:status', port)