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

"""Handles database requests from other nova services."""

import collections
import contextlib
import copy
import eventlet
import functools
import sys

from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_limit import exception as limit_exceptions
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_serialization import jsonutils
from oslo_utils import excutils
from oslo_utils import timeutils
from oslo_utils import versionutils

from nova.accelerator import cyborg
from nova import availability_zones
from nova.compute import instance_actions
from nova.compute import rpcapi as compute_rpcapi
from nova.compute import task_states
from nova.compute import utils as compute_utils
from nova.compute.utils import wrap_instance_event
from nova.compute import vm_states
from nova.conductor.tasks import cross_cell_migrate
from nova.conductor.tasks import live_migrate
from nova.conductor.tasks import migrate
from nova import context as nova_context
from nova import exception
from nova.i18n import _
from nova.image import glance
from nova.limit import placement as placement_limits
from nova import manager
from nova.network import neutron
from nova import notifications
from nova import objects
from nova.objects import base as nova_object
from nova.objects import fields
from nova import profiler
from nova import rpc
from nova.scheduler.client import query
from nova.scheduler.client import report
from nova.scheduler import utils as scheduler_utils
from nova import servicegroup
from nova import utils
from nova.volume import cinder

LOG = logging.getLogger(__name__)
CONF = cfg.CONF


def targets_cell(fn):
    """Wrap a method and automatically target the instance's cell.

    This decorates a method with signature func(self, context, instance, ...)
    and automatically targets the context with the instance's cell
    mapping. It does this by looking up the InstanceMapping.
    """
    @functools.wraps(fn)
    def wrapper(self, context, *args, **kwargs):
        instance = kwargs.get('instance') or args[0]
        try:
            im = objects.InstanceMapping.get_by_instance_uuid(
                context, instance.uuid)
        except exception.InstanceMappingNotFound:
            LOG.error('InstanceMapping not found, unable to target cell',
                      instance=instance)
        except db_exc.CantStartEngineError:
            # Check to see if we can ignore API DB connection failures
            # because we might already be in the cell conductor.
            with excutils.save_and_reraise_exception() as err_ctxt:
                if CONF.api_database.connection is None:
                    err_ctxt.reraise = False
        else:
            LOG.debug('Targeting cell %(cell)s for conductor method %(meth)s',
                      {'cell': im.cell_mapping.identity,
                       'meth': fn.__name__})
            # NOTE(danms): Target our context to the cell for the rest of
            # this request, so that none of the subsequent code needs to
            # care about it.
            nova_context.set_target_cell(context, im.cell_mapping)
        return fn(self, context, *args, **kwargs)
    return wrapper


class ConductorManager(manager.Manager):
    """Mission: Conduct things.

    The methods in the base API for nova-conductor are various proxy operations
    performed on behalf of the nova-compute service running on compute nodes.
    Compute nodes are not allowed to directly access the database, so this set
    of methods allows them to get specific work done without locally accessing
    the database.

    The nova-conductor service also exposes an API in the 'compute_task'
    namespace.  See the ComputeTaskManager class for details.
    """

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

    def __init__(self, *args, **kwargs):
        super(ConductorManager, self).__init__(service_name='conductor',
                                               *args, **kwargs)
        self.compute_task_mgr = ComputeTaskManager()
        self.additional_endpoints.append(self.compute_task_mgr)

    # NOTE(hanlind): This can be removed in version 4.0 of the RPC API
    def provider_fw_rule_get_all(self, context):
        # NOTE(hanlind): Simulate an empty db result for compat reasons.
        return []

    def _object_dispatch(self, target, method, args, kwargs):
        """Dispatch a call to an object method.

        This ensures that object methods get called and any exception
        that is raised gets wrapped in an ExpectedException for forwarding
        back to the caller (without spamming the conductor logs).
        """
        try:
            # NOTE(danms): Keep the getattr inside the try block since
            # a missing method is really a client problem
            return getattr(target, method)(*args, **kwargs)
        except Exception:
            raise messaging.ExpectedException()

    def object_class_action_versions(self, context, objname, objmethod,
                                     object_versions, args, kwargs):
        objclass = nova_object.NovaObject.obj_class_from_name(
            objname, object_versions[objname])
        args = tuple([context] + list(args))
        result = self._object_dispatch(objclass, objmethod, args, kwargs)
        # NOTE(danms): The RPC layer will convert to primitives for us,
        # but in this case, we need to honor the version the client is
        # asking for, so we do it before returning here.
        # NOTE(hanlind): Do not convert older than requested objects,
        # see bug #1596119.
        if isinstance(result, nova_object.NovaObject):
            target_version = object_versions[objname]
            requested_version = versionutils.convert_version_to_tuple(
                target_version)
            actual_version = versionutils.convert_version_to_tuple(
                result.VERSION)
            do_backport = requested_version < actual_version
            other_major_version = requested_version[0] != actual_version[0]
            if do_backport or other_major_version:
                result = result.obj_to_primitive(
                    target_version=target_version,
                    version_manifest=object_versions)
        return result

    def object_action(self, context, objinst, objmethod, args, kwargs):
        """Perform an action on an object."""
        oldobj = objinst.obj_clone()
        result = self._object_dispatch(objinst, objmethod, args, kwargs)
        updates = dict()
        # NOTE(danms): Diff the object with the one passed to us and
        # generate a list of changes to forward back
        for name, field in objinst.fields.items():
            if not objinst.obj_attr_is_set(name):
                # Avoid demand-loading anything
                continue
            if (not oldobj.obj_attr_is_set(name) or
                    getattr(oldobj, name) != getattr(objinst, name)):
                updates[name] = field.to_primitive(objinst, name,
                                                   getattr(objinst, name))
        # This is safe since a field named this would conflict with the
        # method anyway
        updates['obj_what_changed'] = objinst.obj_what_changed()
        return updates, result

    def object_backport_versions(self, context, objinst, object_versions):
        target = object_versions[objinst.obj_name()]
        LOG.debug('Backporting %(obj)s to %(ver)s with versions %(manifest)s',
                  {'obj': objinst.obj_name(),
                   'ver': target,
                   'manifest': ','.join(
                       ['%s=%s' % (name, ver)
                       for name, ver in object_versions.items()])})
        return objinst.obj_to_primitive(target_version=target,
                                        version_manifest=object_versions)

    def reset(self):
        objects.Service.clear_min_version_cache()


@contextlib.contextmanager
def try_target_cell(context, cell):
    """If cell is not None call func with context.target_cell.

    This is a method to help during the transition period. Currently
    various mappings may not exist if a deployment has not migrated to
    cellsv2. If there is no mapping call the func as normal, otherwise
    call it in a target_cell context.
    """
    if cell:
        with nova_context.target_cell(context, cell) as cell_context:
            yield cell_context
    else:
        yield context


@contextlib.contextmanager
def obj_target_cell(obj, cell):
    """Run with object's context set to a specific cell"""
    with try_target_cell(obj._context, cell) as target:
        with obj.obj_alternate_context(target):
            yield target


@profiler.trace_cls("rpc")
class ComputeTaskManager:
    """Namespace for compute methods.

    This class presents an rpc API for nova-conductor under the 'compute_task'
    namespace.  The methods here are compute operations that are invoked
    by the API service.  These methods see the operation to completion, which
    may involve coordinating activities on multiple compute nodes.
    """

    target = messaging.Target(namespace='compute_task', version='1.23')

    def __init__(self):
        self.compute_rpcapi = compute_rpcapi.ComputeAPI()
        self.volume_api = cinder.API()
        self.image_api = glance.API()
        self.network_api = neutron.API()
        self.servicegroup_api = servicegroup.API()
        self.query_client = query.SchedulerQueryClient()
        self.report_client = report.SchedulerReportClient()
        self.notifier = rpc.get_notifier('compute')
        # Help us to record host in EventReporter
        self.host = CONF.host

    def reset(self):
        LOG.info('Reloading compute RPC API')
        compute_rpcapi.LAST_VERSION = None
        self.compute_rpcapi = compute_rpcapi.ComputeAPI()

    # TODO(tdurakov): remove `live` parameter here on compute task api RPC
    # version bump to 2.x
    # TODO(danms): remove the `reservations` parameter here on compute task api
    # RPC version bump to 2.x
    @messaging.expected_exceptions(
        exception.NoValidHost,
        exception.ComputeServiceUnavailable,
        exception.ComputeHostNotFound,
        exception.InvalidHypervisorType,
        exception.InvalidCPUInfo,
        exception.UnableToMigrateToSelf,
        exception.DestinationHypervisorTooOld,
        exception.InvalidLocalStorage,
        exception.InvalidSharedStorage,
        exception.HypervisorUnavailable,
        exception.InstanceInvalidState,
        exception.MigrationPreCheckError,
        exception.UnsupportedPolicyException)
    @targets_cell
    @wrap_instance_event(prefix='conductor')
    def migrate_server(self, context, instance, scheduler_hint, live, rebuild,
            flavor, block_migration, disk_over_commit, reservations=None,
            clean_shutdown=True, request_spec=None, host_list=None):
        if instance and not isinstance(instance, nova_object.NovaObject):
            # NOTE(danms): Until v2 of the RPC API, we need to tolerate
            # old-world instance objects here
            attrs = ['metadata', 'system_metadata', 'info_cache',
                     'security_groups']
            instance = objects.Instance._from_db_object(
                context, objects.Instance(), instance,
                expected_attrs=attrs)
        # NOTE: Remove this when we drop support for v1 of the RPC API
        if flavor and not isinstance(flavor, objects.Flavor):
            # Code downstream may expect extra_specs to be populated since it
            # is receiving an object, so lookup the flavor to ensure this.
            flavor = objects.Flavor.get_by_id(context, flavor['id'])
        if live and not rebuild and not flavor:
            self._live_migrate(context, instance, scheduler_hint,
                               block_migration, disk_over_commit, request_spec)
        elif not live and not rebuild and flavor:
            instance_uuid = instance.uuid
            with compute_utils.EventReporter(context, 'cold_migrate',
                                             self.host, instance_uuid):
                self._cold_migrate(context, instance, flavor,
                                   scheduler_hint['filter_properties'],
                                   clean_shutdown, request_spec,
                                   host_list)
        else:
            raise NotImplementedError()

    @staticmethod
    def _get_request_spec_for_cold_migrate(context, instance, flavor,
                                           filter_properties, request_spec):
        # NOTE(sbauza): If a reschedule occurs when prep_resize(), then
        # it only provides filter_properties legacy dict back to the
        # conductor with no RequestSpec part of the payload for <Stein
        # computes.
        # TODO(mriedem): We can remove this compat code for no request spec
        # coming to conductor in ComputeTaskAPI RPC API version 2.0
        if not request_spec:
            image_meta = utils.get_image_from_system_metadata(
                instance.system_metadata)
            # Make sure we hydrate a new RequestSpec object with the new flavor
            # and not the nested one from the instance
            request_spec = objects.RequestSpec.from_components(
                context, instance.uuid, image_meta,
                flavor, instance.numa_topology, instance.pci_requests,
                filter_properties, None, instance.availability_zone,
                project_id=instance.project_id, user_id=instance.user_id)
        elif not isinstance(request_spec, objects.RequestSpec):
            # Prior to compute RPC API 5.1 conductor would pass a legacy dict
            # version of the request spec to compute and Stein compute
            # could be sending that back to conductor on reschedule, so if we
            # got a dict convert it to an object.
            # TODO(mriedem): We can drop this compat code when we only support
            # compute RPC API >=6.0.
            request_spec = objects.RequestSpec.from_primitives(
                context, request_spec, filter_properties)
            # We don't have to set the new flavor on the request spec because
            # if we got here it was due to a reschedule from the compute and
            # the request spec would already have the new flavor in it from the
            # else block below.
        else:
            # NOTE(sbauza): Resizes means new flavor, so we need to update the
            # original RequestSpec object for make sure the scheduler verifies
            # the right one and not the original flavor
            request_spec.flavor = flavor
        return request_spec

    def _cold_migrate(self, context, instance, flavor, filter_properties,
                      clean_shutdown, request_spec, host_list):
        request_spec = self._get_request_spec_for_cold_migrate(
            context, instance, flavor, filter_properties, request_spec)

        task = self._build_cold_migrate_task(context, instance, flavor,
                request_spec, clean_shutdown, host_list)
        try:
            task.execute()
        except exception.NoValidHost as ex:
            vm_state = instance.vm_state
            if not vm_state:
                vm_state = vm_states.ACTIVE
            updates = {'vm_state': vm_state, 'task_state': None}
            self._set_vm_state_and_notify(context, instance.uuid,
                                          'migrate_server',
                                          updates, ex, request_spec)

            # if the flavor IDs match, it's migrate; otherwise resize
            if flavor.id == instance.instance_type_id:
                msg = _("No valid host found for cold migrate")
            else:
                msg = _("No valid host found for resize")
            raise exception.NoValidHost(reason=msg)
        except exception.UnsupportedPolicyException as ex:
            with excutils.save_and_reraise_exception():
                vm_state = instance.vm_state
                if not vm_state:
                    vm_state = vm_states.ACTIVE
                updates = {'vm_state': vm_state, 'task_state': None}
                self._set_vm_state_and_notify(context, instance.uuid,
                                              'migrate_server',
                                              updates, ex, request_spec)
        except Exception as ex:
            with excutils.save_and_reraise_exception():
                # Refresh the instance so we don't overwrite vm_state changes
                # set after we executed the task.
                try:
                    instance.refresh()
                    # Passing vm_state is kind of silly but it's expected in
                    # set_vm_state_and_notify.
                    updates = {'vm_state': instance.vm_state,
                               'task_state': None}
                    self._set_vm_state_and_notify(context, instance.uuid,
                                                  'migrate_server',
                                                  updates, ex, request_spec)
                except exception.InstanceNotFound:
                    # We can't send the notification because the instance is
                    # gone so just log it.
                    LOG.info('During %s the instance was deleted.',
                             'resize' if instance.instance_type_id != flavor.id
                             else 'cold migrate', instance=instance)
        # NOTE(sbauza): Make sure we persist the new flavor in case we had
        # a successful scheduler call if and only if nothing bad happened
        if request_spec.obj_what_changed():
            request_spec.save()

    def _set_vm_state_and_notify(self, context, instance_uuid, method, updates,
                                 ex, request_spec):
        scheduler_utils.set_vm_state_and_notify(
                context, instance_uuid, 'compute_task', method, updates,
                ex, request_spec)

    def _cleanup_allocated_networks(
            self, context, instance, requested_networks):
        try:
            # If we were told not to allocate networks let's save ourselves
            # the trouble of calling the network API.
            if not (requested_networks and requested_networks.no_allocate):
                self.network_api.deallocate_for_instance(
                    context, instance, requested_networks=requested_networks)
        except Exception:
            LOG.exception('Failed to deallocate networks', instance=instance)
            return

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

    @targets_cell
    @wrap_instance_event(prefix='conductor')
    def live_migrate_instance(self, context, instance, scheduler_hint,
                              block_migration, disk_over_commit, request_spec):
        self._live_migrate(context, instance, scheduler_hint,
                           block_migration, disk_over_commit, request_spec)

    def _live_migrate(self, context, instance, scheduler_hint,
                      block_migration, disk_over_commit, request_spec):
        destination = scheduler_hint.get("host")

        def _set_vm_state(context, instance, ex, vm_state=None,
                          task_state=None):
            request_spec = {'instance_properties': {
                'uuid': instance.uuid, },
            }
            scheduler_utils.set_vm_state_and_notify(context,
                instance.uuid,
                'compute_task', 'migrate_server',
                dict(vm_state=vm_state,
                     task_state=task_state,
                     expected_task_state=task_states.MIGRATING,),
                ex, request_spec)

        migration = objects.Migration(context=context.elevated())
        migration.dest_compute = destination
        migration.status = 'accepted'
        migration.instance_uuid = instance.uuid
        migration.source_compute = instance.host
        migration.migration_type = fields.MigrationType.LIVE_MIGRATION
        if instance.obj_attr_is_set('flavor'):
            migration.old_instance_type_id = instance.flavor.id
            migration.new_instance_type_id = instance.flavor.id
        else:
            migration.old_instance_type_id = instance.instance_type_id
            migration.new_instance_type_id = instance.instance_type_id
        migration.create()

        task = self._build_live_migrate_task(context, instance, destination,
                                             block_migration, disk_over_commit,
                                             migration, request_spec)
        try:
            task.execute()
        except (exception.NoValidHost,
                exception.ComputeHostNotFound,
                exception.ComputeServiceUnavailable,
                exception.InvalidHypervisorType,
                exception.InvalidCPUInfo,
                exception.UnableToMigrateToSelf,
                exception.DestinationHypervisorTooOld,
                exception.InvalidLocalStorage,
                exception.InvalidSharedStorage,
                exception.HypervisorUnavailable,
                exception.InstanceInvalidState,
                exception.MigrationPreCheckError,
                exception.MigrationSchedulerRPCError) as ex:
            with excutils.save_and_reraise_exception():
                _set_vm_state(context, instance, ex, instance.vm_state)
                migration.status = 'error'
                migration.save()
        except Exception as ex:
            LOG.error('Migration of instance %(instance_id)s to host'
                      ' %(dest)s unexpectedly failed.',
                      {'instance_id': instance.uuid, 'dest': destination},
                      exc_info=True)
            # Reset the task state to None to indicate completion of
            # the operation as it is done in case of known exceptions.
            _set_vm_state(context, instance, ex, vm_states.ERROR,
                          task_state=None)
            migration.status = 'error'
            migration.save()
            raise exception.MigrationError(reason=str(ex))

    def _build_live_migrate_task(self, context, instance, destination,
                                 block_migration, disk_over_commit, migration,
                                 request_spec=None):
        return live_migrate.LiveMigrationTask(context, instance,
                                              destination, block_migration,
                                              disk_over_commit, migration,
                                              self.compute_rpcapi,
                                              self.servicegroup_api,
                                              self.query_client,
                                              self.report_client,
                                              request_spec)

    def _build_cold_migrate_task(self, context, instance, flavor, request_spec,
            clean_shutdown, host_list):
        return migrate.MigrationTask(context, instance, flavor,
                                     request_spec, clean_shutdown,
                                     self.compute_rpcapi,
                                     self.query_client, self.report_client,
                                     host_list, self.network_api)

    def _destroy_build_request(self, context, instance):
        # The BuildRequest needs to be stored until the instance is mapped to
        # an instance table. At that point it will never be used again and
        # should be deleted.
        build_request = objects.BuildRequest.get_by_instance_uuid(
            context, instance.uuid)
        # TODO(alaski): Sync API updates of the build_request to the
        # instance before it is destroyed. Right now only locked_by can
        # be updated before this is destroyed.
        build_request.destroy()

    def _populate_instance_mapping(self, context, instance, host):
        try:
            inst_mapping = objects.InstanceMapping.get_by_instance_uuid(
                    context, instance.uuid)
        except exception.InstanceMappingNotFound:
            # NOTE(alaski): If nova-api is up to date this exception should
            # never be hit. But during an upgrade it's possible that an old
            # nova-api didn't create an instance_mapping during this boot
            # request.
            LOG.debug('Instance was not mapped to a cell, likely due '
                      'to an older nova-api service running.',
                      instance=instance)
            return None
        else:
            try:
                host_mapping = objects.HostMapping.get_by_host(context,
                        host.service_host)
            except exception.HostMappingNotFound:
                # NOTE(alaski): For now this exception means that a
                # deployment has not migrated to cellsv2 and we should
                # remove the instance_mapping that has been created.
                # Eventually this will indicate a failure to properly map a
                # host to a cell and we may want to reschedule.
                inst_mapping.destroy()
                return None
            else:
                inst_mapping.cell_mapping = host_mapping.cell_mapping
                inst_mapping.save()
        return inst_mapping

    def _validate_existing_attachment_ids(self, context, instance, bdms):
        """Ensure any attachment ids referenced by the bdms exist.

        New attachments will only be created if the attachment ids referenced
        by the bdms no longer exist. This can happen when an instance is
        rescheduled after a failure to spawn as cleanup code on the previous
        host will delete attachments before rescheduling.
        """
        for bdm in bdms:
            if bdm.is_volume and bdm.attachment_id:
                try:
                    self.volume_api.attachment_get(context, bdm.attachment_id)
                except exception.VolumeAttachmentNotFound:
                    attachment = self.volume_api.attachment_create(
                        context, bdm.volume_id, instance.uuid)
                    bdm.attachment_id = attachment['id']
                    bdm.save()

    def _cleanup_when_reschedule_fails(
            self, context, instance, exception, legacy_request_spec,
            requested_networks):
        """Set the instance state and clean up.

        It is only used in case build_instance fails while rescheduling the
        instance
        """

        updates = {'vm_state': vm_states.ERROR,
                   'task_state': None}
        self._set_vm_state_and_notify(
            context, instance.uuid, 'build_instances', updates, exception,
            legacy_request_spec)
        self._cleanup_allocated_networks(
            context, instance, requested_networks)

        arq_uuids = None
        # arqs have not bound to port/instance yet
        if requested_networks:
            arq_uuids = [req.arq_uuid
                for req in requested_networks if req.arq_uuid]
        compute_utils.delete_arqs_if_needed(context, instance, arq_uuids)

    # NOTE(danms): This is never cell-targeted because it is only used for
    # n-cpu reschedules which go to the cell conductor and thus are always
    # cell-specific.
    def build_instances(self, context, instances, image, filter_properties,
            admin_password, injected_files, requested_networks,
            security_groups, block_device_mapping=None, legacy_bdm=True,
            request_spec=None, host_lists=None):
        # TODO(ndipanov): Remove block_device_mapping and legacy_bdm in version
        #                 2.0 of the RPC API.
        # TODO(danms): Remove this in version 2.0 of the RPC API
        if (requested_networks and
                not isinstance(requested_networks,
                               objects.NetworkRequestList)):
            requested_networks = objects.NetworkRequestList.from_tuples(
                requested_networks)
        # TODO(melwitt): Remove this in version 2.0 of the RPC API
        flavor = filter_properties.get('instance_type')
        if flavor and not isinstance(flavor, objects.Flavor):
            # Code downstream may expect extra_specs to be populated since it
            # is receiving an object, so lookup the flavor to ensure this.
            flavor = objects.Flavor.get_by_id(context, flavor['id'])
            filter_properties = dict(filter_properties, instance_type=flavor)

        # Older computes will not send a request_spec during reschedules so we
        # need to check and build our own if one is not provided.
        if request_spec is None:
            legacy_request_spec = scheduler_utils.build_request_spec(
                image, instances)
        else:
            # TODO(mriedem): This is annoying but to populate the local
            # request spec below using the filter_properties, we have to pass
            # in a primitive version of the request spec. Yes it's inefficient
            # and we can remove it once the populate_retry and
            # populate_filter_properties utility methods are converted to
            # work on a RequestSpec object rather than filter_properties.
            # NOTE(gibi): we have to keep a reference to the original
            # RequestSpec object passed to this function as we lose information
            # during the below legacy conversion
            legacy_request_spec = request_spec.to_legacy_request_spec_dict()

        # 'host_lists' will be None during a reschedule from a pre-Queens
        # compute. In all other cases, it will be a list of lists, though the
        # lists may be empty if there are no more hosts left in a rescheduling
        # situation.
        is_reschedule = host_lists is not None
        try:
            # check retry policy. Rather ugly use of instances[0]...
            # but if we've exceeded max retries... then we really only
            # have a single instance.
            # TODO(sbauza): Provide directly the RequestSpec object
            # when populate_retry() accepts it
            scheduler_utils.populate_retry(
                filter_properties, instances[0].uuid)
            instance_uuids = [instance.uuid for instance in instances]
            spec_obj = objects.RequestSpec.from_primitives(
                    context, legacy_request_spec, filter_properties)
            LOG.debug("Rescheduling: %s", is_reschedule)
            if is_reschedule:
                # Make sure that we have a host, as we may have exhausted all
                # our alternates
                if not host_lists[0]:
                    # We have an empty list of hosts, so this instance has
                    # failed to build.
                    msg = ("Exhausted all hosts available for retrying build "
                           "failures for instance %(instance_uuid)s." %
                           {"instance_uuid": instances[0].uuid})
                    raise exception.MaxRetriesExceeded(reason=msg)
            else:
                # This is not a reschedule, so we need to call the scheduler to
                # get appropriate hosts for the request.
                # NOTE(gibi): We only call the scheduler if we are rescheduling
                # from a really old compute. In that case we do not support
                # externally-defined resource requests, like port QoS. So no
                # requested_resources are set on the RequestSpec here.
                host_lists = self._schedule_instances(context, spec_obj,
                        instance_uuids, return_alternates=True)
        except Exception as exc:
            # NOTE(mriedem): If we're rescheduling from a failed build on a
            # compute, "retry" will be set and num_attempts will be >1 because
            # populate_retry above will increment it. If the server build was
            # forced onto a host/node or [scheduler]/max_attempts=1, "retry"
            # won't be in filter_properties and we won't get here because
            # nova-compute will just abort the build since reschedules are
            # disabled in those cases.
            num_attempts = filter_properties.get(
                'retry', {}).get('num_attempts', 1)
            for instance in instances:
                # If num_attempts > 1, we're in a reschedule and probably
                # either hit NoValidHost or MaxRetriesExceeded. Either way,
                # the build request should already be gone and we probably
                # can't reach the API DB from the cell conductor.
                if num_attempts <= 1:
                    try:
                        # If the BuildRequest stays around then instance
                        # show/lists will pull from it rather than the errored
                        # instance.
                        self._destroy_build_request(context, instance)
                    except exception.BuildRequestNotFound:
                        pass
                self._cleanup_when_reschedule_fails(
                    context, instance, exc, legacy_request_spec,
                    requested_networks)
            return

        elevated = context.elevated()
        for (instance, host_list) in zip(instances, host_lists):
            host = host_list.pop(0)
            if is_reschedule:
                # If this runs in the superconductor, the first instance will
                # already have its resources claimed in placement. If this is a
                # retry, though, this is running in the cell conductor, and we
                # need to claim first to ensure that the alternate host still
                # has its resources available. Note that there are schedulers
                # that don't support Placement, so must assume that the host is
                # still available.
                host_available = False
                while host and not host_available:
                    if host.allocation_request:
                        alloc_req = jsonutils.loads(host.allocation_request)
                    else:
                        alloc_req = None
                    if alloc_req:
                        try:
                            host_available = scheduler_utils.claim_resources(
                                elevated, self.report_client, spec_obj,
                                instance.uuid, alloc_req,
                                host.allocation_request_version)
                            if request_spec and host_available:
                                # NOTE(gibi): redo the request group - resource
                                # provider mapping as the above claim call
                                # moves the allocation of the instance to
                                # another host
                                scheduler_utils.fill_provider_mapping(
                                    request_spec, host)
                        except Exception as exc:
                            self._cleanup_when_reschedule_fails(
                                context, instance, exc, legacy_request_spec,
                                requested_networks)
                            return
                    else:
                        # Some deployments use different schedulers that do not
                        # use Placement, so they will not have an
                        # allocation_request to claim with. For those cases,
                        # there is no concept of claiming, so just assume that
                        # the host is valid.
                        host_available = True
                    if not host_available:
                        # Insufficient resources remain on that host, so
                        # discard it and try the next.
                        host = host_list.pop(0) if host_list else None
                if not host_available:
                    # No more available hosts for retrying the build.
                    msg = ("Exhausted all hosts available for retrying build "
                           "failures for instance %(instance_uuid)s." %
                           {"instance_uuid": instance.uuid})
                    exc = exception.MaxRetriesExceeded(reason=msg)
                    self._cleanup_when_reschedule_fails(
                        context, instance, exc, legacy_request_spec,
                        requested_networks)
                    return

            # The availability_zone field was added in v1.1 of the Selection
            # object so make sure to handle the case where it is missing.
            if 'availability_zone' in host:
                instance.availability_zone = host.availability_zone
            else:
                try:
                    instance.availability_zone = (
                        availability_zones.get_host_availability_zone(context,
                                host.service_host))
                except Exception as exc:
                    # Put the instance into ERROR state, set task_state to
                    # None, inject a fault, etc.
                    self._cleanup_when_reschedule_fails(
                        context, instance, exc, legacy_request_spec,
                        requested_networks)
                    continue

            try:
                # NOTE(danms): This saves the az change above, refreshes our
                # instance, and tells us if it has been deleted underneath us
                instance.save()
            except (exception.InstanceNotFound,
                    exception.InstanceInfoCacheNotFound):
                LOG.debug('Instance deleted during build', instance=instance)
                continue
            local_filter_props = copy.deepcopy(filter_properties)
            scheduler_utils.populate_filter_properties(local_filter_props,
                host)
            # Populate the request_spec with the local_filter_props information
            # like retries and limits. Note that at this point the request_spec
            # could have come from a compute via reschedule and it would
            # already have some things set, like scheduler_hints.
            local_reqspec = objects.RequestSpec.from_primitives(
                context, legacy_request_spec, local_filter_props)

            # NOTE(gibi): at this point the request spec already got converted
            # to a legacy dict and then back to an object so we lost the non
            # legacy part of the spec. Re-populate the requested_resources
            # field based on the original request spec object passed to this
            # function.
            if request_spec:
                local_reqspec.requested_resources = (
                    request_spec.requested_resources)

            # The block_device_mapping passed from the api doesn't contain
            # instance specific information
            bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
                    context, instance.uuid)

            # This is populated in scheduler_utils.populate_retry
            num_attempts = local_filter_props.get('retry',
                                                  {}).get('num_attempts', 1)
            if num_attempts <= 1:
                # If this is a reschedule the instance is already mapped to
                # this cell and the BuildRequest is already deleted so ignore
                # the logic below.
                inst_mapping = self._populate_instance_mapping(context,
                                                               instance,
                                                               host)
                try:
                    self._destroy_build_request(context, instance)
                except exception.BuildRequestNotFound:
                    # This indicates an instance delete has been requested in
                    # the API. Stop the build, cleanup the instance_mapping and
                    # potentially the block_device_mappings
                    # TODO(alaski): Handle block_device_mapping cleanup
                    if inst_mapping:
                        inst_mapping.destroy()
                    return
            else:
                # NOTE(lyarwood): If this is a reschedule then recreate any
                # attachments that were previously removed when cleaning up
                # after failures to spawn etc.
                self._validate_existing_attachment_ids(context, instance, bdms)

            alts = [(alt.service_host, alt.nodename) for alt in host_list]
            LOG.debug("Selected host: %s; Selected node: %s; Alternates: %s",
                    host.service_host, host.nodename, alts, instance=instance)

            try:
                accel_uuids = self._create_and_bind_arq_for_instance(
                    context, instance, host.nodename, local_reqspec,
                    requested_networks)
            except Exception as exc:
                LOG.exception('Failed to reschedule. Reason: %s', exc)
                self._cleanup_when_reschedule_fails(
                        context, instance, exc, legacy_request_spec,
                        requested_networks)
                continue

            self.compute_rpcapi.build_and_run_instance(context,
                    instance=instance, host=host.service_host, image=image,
                    request_spec=local_reqspec,
                    filter_properties=local_filter_props,
                    admin_password=admin_password,
                    injected_files=injected_files,
                    requested_networks=requested_networks,
                    security_groups=security_groups,
                    block_device_mapping=bdms, node=host.nodename,
                    limits=host.limits, host_list=host_list,
                    accel_uuids=accel_uuids)

    def _create_and_bind_arq_for_instance(
            self, context, instance, hostname,
            request_spec, requested_networks=None):
        try:
            resource_provider_mapping = (
                request_spec.get_request_group_mapping())
            # Using nodename instead of hostname. See:
            # http://lists.openstack.org/pipermail/openstack-discuss/2019-November/011044.html  # noqa
            cyclient = cyborg.get_client(context)
            bindings = {}
            port_bindings = {}

            # Create ARQs comes from extra specs.
            bindings = self._create_and_bind_arqs(
                cyclient, instance.uuid, instance.flavor.extra_specs,
                hostname, resource_provider_mapping)

            if requested_networks:
                # Create ARQs comes from port device profile
                port_bindings = self._create_arqs_for_ports(
                    cyclient, instance.uuid, requested_networks,
                    hostname, resource_provider_mapping)

            # Initiate Cyborg binding asynchronously
            bindings.update(port_bindings)
            if bindings:
                cyclient.bind_arqs(bindings)

            return list(bindings.keys())

        except exception.AcceleratorRequestBindingFailed as exc:
            # If anything failed here we need to cleanup and bail out.
            cyclient = cyborg.get_client(context)
            cyclient.delete_arqs_by_uuid(exc.arqs)
            raise

    def _schedule_instances(self, context, request_spec,
                            instance_uuids=None, return_alternates=False):
        scheduler_utils.setup_instance_group(context, request_spec)
        with timeutils.StopWatch() as timer:
            host_lists = self.query_client.select_destinations(
                context, request_spec, instance_uuids, return_objects=True,
                return_alternates=return_alternates)
        LOG.debug('Took %0.2f seconds to select destinations for %s '
                  'instance(s).', timer.elapsed(), len(instance_uuids))
        return host_lists

    @staticmethod
    def _restrict_request_spec_to_cell(context, instance, request_spec):
        """Sets RequestSpec.requested_destination.cell for the move operation

        Move operations, e.g. evacuate and unshelve, must be restricted to the
        cell in which the instance already exists, so this method is used to
        target the RequestSpec, which is sent to the scheduler via the
        _schedule_instances method, to the instance's current cell.

        :param context: nova auth RequestContext
        """
        instance_mapping = \
            objects.InstanceMapping.get_by_instance_uuid(
                context, instance.uuid)
        LOG.debug('Requesting cell %(cell)s during scheduling',
                  {'cell': instance_mapping.cell_mapping.identity},
                  instance=instance)
        if ('requested_destination' in request_spec and
                request_spec.requested_destination):
            request_spec.requested_destination.cell = (
                instance_mapping.cell_mapping)
        else:
            request_spec.requested_destination = (
                objects.Destination(
                    cell=instance_mapping.cell_mapping))

    # TODO(mriedem): Make request_spec required in ComputeTaskAPI RPC v2.0.
    @targets_cell
    def unshelve_instance(self, context, instance, request_spec=None):
        sys_meta = instance.system_metadata

        def safe_image_show(ctx, image_id):
            if image_id:
                return self.image_api.get(ctx, image_id, show_deleted=False)
            else:
                raise exception.ImageNotFound(image_id='')

        if instance.vm_state == vm_states.SHELVED:
            instance.task_state = task_states.POWERING_ON
            instance.save(expected_task_state=task_states.UNSHELVING)
            self.compute_rpcapi.start_instance(context, instance)
        elif instance.vm_state == vm_states.SHELVED_OFFLOADED:
            image = None
            image_id = sys_meta.get('shelved_image_id')
            # No need to check for image if image_id is None as
            # "shelved_image_id" key is not set for volume backed
            # instance during the shelve process
            if image_id:
                with compute_utils.EventReporter(
                        context, 'get_image_info', self.host, instance.uuid):
                    try:
                        image = safe_image_show(context, image_id)
                    except exception.ImageNotFound as error:
                        instance.vm_state = vm_states.ERROR
                        instance.save()

                        reason = _('Unshelve attempted but the image %s '
                                   'cannot be found.') % image_id

                        LOG.error(reason, instance=instance)
                        compute_utils.add_instance_fault_from_exc(
                            context, instance, error, sys.exc_info(),
                            fault_message=reason)
                        raise exception.UnshelveException(
                            instance_id=instance.uuid, reason=reason)

            try:
                with compute_utils.EventReporter(context, 'schedule_instances',
                                                 self.host, instance.uuid):
                    # NOTE(sbauza): Force_hosts/nodes needs to be reset
                    # if we want to make sure that the next destination
                    # is not forced to be the original host
                    request_spec.reset_forced_destinations()
                    # TODO(sbauza): Provide directly the RequestSpec object
                    # when populate_filter_properties accepts it
                    filter_properties = request_spec.\
                        to_legacy_filter_properties_dict()
                    res_req, req_lvl_params = (
                        self.network_api.get_requested_resource_for_instance(
                            context, instance.uuid)
                    )
                    extra_specs = request_spec.flavor.extra_specs
                    device_profile = extra_specs.get('accel:device_profile')
                    res_req.extend(
                        cyborg.get_device_profile_request_groups(
                            context, device_profile) if device_profile else [])
                    # NOTE(gibi): When other modules want to handle similar
                    # non-nova resources then here we have to collect all
                    # the external resource requests in a single list and
                    # add them to the RequestSpec.
                    request_spec.requested_resources = res_req
                    request_spec.request_level_params = req_lvl_params

                    # NOTE(cfriesen): Ensure that we restrict the scheduler to
                    # the cell specified by the instance mapping.
                    self._restrict_request_spec_to_cell(
                        context, instance, request_spec)

                    request_spec.ensure_project_and_user_id(instance)
                    request_spec.ensure_network_information(instance)
                    compute_utils.heal_reqspec_is_bfv(
                        context, request_spec, instance)
                    host_lists = self._schedule_instances(context,
                            request_spec, [instance.uuid],
                            return_alternates=False)
                    host_list = host_lists[0]
                    selection = host_list[0]
                    scheduler_utils.populate_filter_properties(
                            filter_properties, selection)
                    (host, node) = (selection.service_host, selection.nodename)
                    LOG.debug(
                        "Scheduler selected host: %s, node:%s",
                        host,
                        node,
                        instance=instance
                    )
                    instance.availability_zone = (
                        availability_zones.get_host_availability_zone(
                            context, host))

                    scheduler_utils.fill_provider_mapping(
                        request_spec, selection)

                    # NOTE(brinzhang): For unshelve operation we should
                    # re-create-and-bound the arqs for the instance.
                    accel_uuids = self._create_and_bind_arq_for_instance(
                        context, instance, node, request_spec)
                    self.compute_rpcapi.unshelve_instance(
                        context, instance, host, request_spec, image=image,
                        filter_properties=filter_properties, node=node,
                        accel_uuids=accel_uuids)
            except (exception.NoValidHost,
                    exception.UnsupportedPolicyException):
                instance.task_state = None
                instance.save()
                LOG.warning("No valid host found for unshelve instance",
                            instance=instance)
                return
            except Exception as exc:
                if isinstance(exc, exception.AcceleratorRequestBindingFailed):
                    cyclient = cyborg.get_client(context)
                    cyclient.delete_arqs_by_uuid(exc.arqs)
                LOG.exception('Failed to unshelve. Reason: %s', exc)
                with excutils.save_and_reraise_exception():
                    instance.task_state = None
                    instance.save()
                    LOG.error("Unshelve attempted but an error "
                              "has occurred", instance=instance)
        else:
            LOG.error('Unshelve attempted but vm_state not SHELVED or '
                      'SHELVED_OFFLOADED', instance=instance)
            instance.vm_state = vm_states.ERROR
            instance.save()
            return

    def _allocate_for_evacuate_dest_host(self, context, instance, host,
                                         request_spec=None):
        # The user is forcing the destination host and bypassing the
        # scheduler. We need to copy the source compute node
        # allocations in Placement to the destination compute node.
        # Normally select_destinations() in the scheduler would do this
        # for us, but when forcing the target host we don't call the
        # scheduler.
        source_node = None  # This is used for error handling below.
        try:
            source_node = objects.ComputeNode.get_by_host_and_nodename(
                context, instance.host, instance.node)
            dest_node = (
                objects.ComputeNode.get_first_node_by_host_for_old_compat(
                    context, host, use_slave=True))
        except exception.ComputeHostNotFound as ex:
            with excutils.save_and_reraise_exception():
                self._set_vm_state_and_notify(
                    context, instance.uuid, 'rebuild_server',
                    {'vm_state': instance.vm_state,
                     'task_state': None}, ex, request_spec)
                if source_node:
                    LOG.warning('Specified host %s for evacuate was not '
                                'found.', host, instance=instance)
                else:
                    LOG.warning('Source host %s and node %s for evacuate was '
                                'not found.', instance.host, instance.node,
                                instance=instance)

        try:
            scheduler_utils.claim_resources_on_destination(
                context, self.report_client, instance, source_node, dest_node)
        except exception.NoValidHost as ex:
            with excutils.save_and_reraise_exception():
                self._set_vm_state_and_notify(
                    context, instance.uuid, 'rebuild_server',
                    {'vm_state': instance.vm_state,
                     'task_state': None}, ex, request_spec)
                LOG.warning('Specified host %s for evacuate is '
                            'invalid.', host, instance=instance)

    # TODO(mriedem): Make request_spec required in ComputeTaskAPI RPC v2.0.
    @targets_cell
    def rebuild_instance(self, context, instance, orig_image_ref, image_ref,
                         injected_files, new_pass, orig_sys_metadata,
                         bdms, recreate, on_shared_storage,
                         preserve_ephemeral=False, host=None,
                         request_spec=None):
        # recreate=True means the instance is being evacuated from a failed
        # host to a new destination host. The 'recreate' variable name is
        # confusing, so rename it to evacuate here at the top, which is simpler
        # than renaming a parameter in an RPC versioned method.
        evacuate = recreate

        # NOTE(efried): It would be nice if this were two separate events, one
        # for 'rebuild' and one for 'evacuate', but this is part of the API
        # now, so it would be nontrivial to change.
        with compute_utils.EventReporter(context, 'rebuild_server',
                                         self.host, instance.uuid):
            node = limits = None

            try:
                migration = objects.Migration.get_by_instance_and_status(
                    context, instance.uuid, 'accepted')
            except exception.MigrationNotFoundByStatus:
                LOG.debug("No migration record for the rebuild/evacuate "
                          "request.", instance=instance)
                migration = None

            # The host variable is passed in two cases:
            # 1. rebuild - the instance.host is passed to rebuild on the
            #       same host and bypass the scheduler *unless* a new image
            #       was specified
            # 2. evacuate with specified host and force=True - the specified
            #       host is passed and is meant to bypass the scheduler.
            # NOTE(mriedem): This could be a lot more straight-forward if we
            # had separate methods for rebuild and evacuate...
            if host:
                # We only create a new allocation on the specified host if
                # we're doing an evacuate since that is a move operation.
                if host != instance.host:
                    # If a destination host is forced for evacuate, create
                    # allocations against it in Placement.
                    try:
                        self._allocate_for_evacuate_dest_host(
                            context, instance, host, request_spec)
                    except exception.AllocationUpdateFailed as ex:
                        with excutils.save_and_reraise_exception():
                            if migration:
                                migration.status = 'error'
                                migration.save()
                            # NOTE(efried): It would be nice if this were two
                            # separate events, one for 'rebuild' and one for
                            # 'evacuate', but this is part of the API now, so
                            # it would be nontrivial to change.
                            self._set_vm_state_and_notify(
                                context,
                                instance.uuid,
                                'rebuild_server',
                                {'vm_state': vm_states.ERROR,
                                 'task_state': None}, ex, request_spec)
                            LOG.warning('Rebuild failed: %s',
                                        str(ex), instance=instance)
                    except exception.NoValidHost:
                        with excutils.save_and_reraise_exception():
                            if migration:
                                migration.status = 'error'
                                migration.save()
            else:
                # At this point, the user is either:
                #
                # 1. Doing a rebuild on the same host (not evacuate) and
                #    specified a new image.
                # 2. Evacuating and specified a host but are not forcing it.
                #
                # In either case, the API passes host=None but sets up the
                # RequestSpec.requested_destination field for the specified
                # host.
                if evacuate:
                    # NOTE(sbauza): Augment the RequestSpec object by excluding
                    # the source host for avoiding the scheduler to pick it
                    request_spec.ignore_hosts = [instance.host]
                    # NOTE(sbauza): Force_hosts/nodes needs to be reset
                    # if we want to make sure that the next destination
                    # is not forced to be the original host
                    request_spec.reset_forced_destinations()
                    res_req, req_lvl_params = (
                        self.network_api.get_requested_resource_for_instance(
                            context, instance.uuid)
                    )
                    extra_specs = request_spec.flavor.extra_specs
                    device_profile = extra_specs.get('accel:device_profile')
                    res_req.extend(
                        cyborg.get_device_profile_request_groups(
                            context, device_profile)
                        if device_profile else [])
                    # NOTE(gibi): When other modules want to handle similar
                    # non-nova resources then here we have to collect all
                    # the external resource requests in a single list and
                    # add them to the RequestSpec.
                    request_spec.requested_resources = res_req
                    request_spec.request_level_params = req_lvl_params

                try:
                    # if this is a rebuild of instance on the same host with
                    # new image.
                    if not evacuate and orig_image_ref != image_ref:
                        self._validate_image_traits_for_rebuild(context,
                                                                instance,
                                                                image_ref)
                    self._restrict_request_spec_to_cell(
                        context, instance, request_spec)
                    request_spec.ensure_project_and_user_id(instance)
                    request_spec.ensure_network_information(instance)
                    compute_utils.heal_reqspec_is_bfv(
                        context, request_spec, instance)

                    host_lists = self._schedule_instances(context,
                            request_spec, [instance.uuid],
                            return_alternates=False)
                    host_list = host_lists[0]
                    selection = host_list[0]
                    host, node, limits = (selection.service_host,
                            selection.nodename, selection.limits)

                    if recreate:
                        scheduler_utils.fill_provider_mapping(
                            request_spec, selection)

                except (exception.NoValidHost,
                        exception.UnsupportedPolicyException,
                        exception.AllocationUpdateFailed,
                        # the next two can come from fill_provider_mapping and
                        # signals a software error.
                        NotImplementedError,
                        ValueError) as ex:
                    if migration:
                        migration.status = 'error'
                        migration.save()
                    # Rollback the image_ref if a new one was provided (this
                    # only happens in the rebuild case, not evacuate).
                    if orig_image_ref and orig_image_ref != image_ref:
                        instance.image_ref = orig_image_ref
                        instance.save()
                    with excutils.save_and_reraise_exception():
                        # NOTE(efried): It would be nice if this were two
                        # separate events, one for 'rebuild' and one for
                        # 'evacuate', but this is part of the API now, so it
                        # would be nontrivial to change.
                        self._set_vm_state_and_notify(context, instance.uuid,
                                'rebuild_server',
                                {'vm_state': vm_states.ERROR,
                                 'task_state': None}, ex, request_spec)
                        LOG.warning('Rebuild failed: %s',
                                    str(ex), instance=instance)

            compute_utils.notify_about_instance_usage(
                self.notifier, context, instance, "rebuild.scheduled")
            compute_utils.notify_about_instance_rebuild(
                context, instance, host,
                action=fields.NotificationAction.REBUILD_SCHEDULED,
                source=fields.NotificationSource.CONDUCTOR)

            instance.availability_zone = (
                availability_zones.get_host_availability_zone(
                    context, host))
            accel_uuids = []
            try:
                if instance.flavor.extra_specs.get('accel:device_profile'):
                    cyclient = cyborg.get_client(context)
                    if evacuate:
                        # NOTE(brinzhang): For evacuate operation we should
                        # delete the bound arqs, then re-create-and-bound the
                        # arqs for the instance.
                        cyclient.delete_arqs_for_instance(instance.uuid)
                        accel_uuids = self._create_and_bind_arq_for_instance(
                            context, instance, node, request_spec)
                    else:
                        accel_uuids = cyclient.get_arq_uuids_for_instance(
                            instance)
            except Exception as exc:
                if isinstance(exc, exception.AcceleratorRequestBindingFailed):
                    cyclient = cyborg.get_client(context)
                    cyclient.delete_arqs_by_uuid(exc.arqs)
                LOG.exception('Failed to rebuild. Reason: %s', exc)
                raise exc

            self.compute_rpcapi.rebuild_instance(
                context,
                instance=instance,
                new_pass=new_pass,
                injected_files=injected_files,
                image_ref=image_ref,
                orig_image_ref=orig_image_ref,
                orig_sys_metadata=orig_sys_metadata,
                bdms=bdms,
                recreate=evacuate,
                on_shared_storage=on_shared_storage,
                preserve_ephemeral=preserve_ephemeral,
                migration=migration,
                host=host,
                node=node,
                limits=limits,
                request_spec=request_spec,
                accel_uuids=accel_uuids)

    def _validate_image_traits_for_rebuild(self, context, instance, image_ref):
        """Validates that the traits specified in the image can be satisfied
        by the providers of the current allocations for the instance during
        rebuild of the instance. If the traits cannot be
        satisfied, fails the action by raising a NoValidHost exception.

        :raises: NoValidHost exception in case the traits on the providers
                 of the allocated resources for the instance do not match
                 the required traits on the image.
        """
        image_meta = objects.ImageMeta.from_image_ref(
            context, self.image_api, image_ref)
        if ('properties' not in image_meta or
                'traits_required' not in image_meta.properties or not
                image_meta.properties.traits_required):
            return

        image_traits = set(image_meta.properties.traits_required)

        # check any of the image traits are forbidden in flavor traits.
        # if so raise an exception
        extra_specs = instance.flavor.extra_specs
        forbidden_flavor_traits = set()
        for key, val in extra_specs.items():
            if key.startswith('trait'):
                # get the actual key.
                prefix, parsed_key = key.split(':', 1)
                if val == 'forbidden':
                    forbidden_flavor_traits.add(parsed_key)

        forbidden_traits = image_traits & forbidden_flavor_traits

        if forbidden_traits:
            raise exception.NoValidHost(
                reason=_("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."))

        # If image traits are present, then validate against allocations.
        allocations = self.report_client.get_allocations_for_consumer(
            context, instance.uuid)
        instance_rp_uuids = list(allocations)

        # Get provider tree for the instance. We use the uuid of the host
        # on which the instance is rebuilding to get the provider tree.
        compute_node = objects.ComputeNode.get_by_host_and_nodename(
            context, instance.host, instance.node)

        # TODO(karimull): Call with a read-only version, when available.
        instance_rp_tree = (
            self.report_client.get_provider_tree_and_ensure_root(
                context, compute_node.uuid))

        traits_in_instance_rps = set()

        for rp_uuid in instance_rp_uuids:
            traits_in_instance_rps.update(
                instance_rp_tree.data(rp_uuid).traits)

        missing_traits = image_traits - traits_in_instance_rps

        if missing_traits:
            raise exception.NoValidHost(
                reason=_("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."))

    # TODO(avolkov): move method to bdm
    @staticmethod
    def _volume_size(flavor, bdm):
        size = bdm.get('volume_size')
        # NOTE (ndipanov): inherit flavor size only for swap and ephemeral
        if (size is None and bdm.get('source_type') == 'blank' and
                bdm.get('destination_type') == 'local'):
            if bdm.get('guest_format') == 'swap':
                size = flavor.get('swap', 0)
            else:
                size = flavor.get('ephemeral_gb', 0)
        return size

    def _create_block_device_mapping(self, cell, flavor, instance_uuid,
                                     block_device_mapping):
        """Create the BlockDeviceMapping objects in the db.

        This method makes a copy of the list in order to avoid using the same
        id field in case this is called for multiple instances.
        """
        LOG.debug("block_device_mapping %s", list(block_device_mapping),
                  instance_uuid=instance_uuid)
        instance_block_device_mapping = copy.deepcopy(block_device_mapping)
        for bdm in instance_block_device_mapping:
            bdm.volume_size = self._volume_size(flavor, bdm)
            bdm.instance_uuid = instance_uuid
            with obj_target_cell(bdm, cell):
                bdm.update_or_create()
        return instance_block_device_mapping

    def _create_tags(self, context, instance_uuid, tags):
        """Create the Tags objects in the db."""
        if tags:
            tag_list = [tag.tag for tag in tags]
            instance_tags = objects.TagList.create(
                context, instance_uuid, tag_list)
            return instance_tags
        else:
            return tags

    def _create_instance_action_for_cell0(self, context, instance, exc):
        """Create a failed "create" instance action for the instance in cell0.

        :param context: nova auth RequestContext targeted at cell0
        :param instance: Instance object being buried in cell0
        :param exc: Exception that occurred which resulted in burial
        """
        # First create the action record.
        objects.InstanceAction.action_start(
            context, instance.uuid, instance_actions.CREATE, want_result=False)
        # Now create an event for that action record.
        event_name = 'conductor_schedule_and_build_instances'
        objects.InstanceActionEvent.event_start(
            context, instance.uuid, event_name, want_result=False,
            host=self.host)
        # And finish the event with the exception. Note that we expect this
        # method to be called from _bury_in_cell0 which is called from within
        # an exception handler so sys.exc_info should return values but if not
        # it's not the end of the world - this is best effort.
        objects.InstanceActionEvent.event_finish_with_failure(
            context, instance.uuid, event_name, exc_val=exc,
            exc_tb=sys.exc_info()[2], want_result=False)

    def _bury_in_cell0(self, context, request_spec, exc,
                       build_requests=None, instances=None,
                       block_device_mapping=None,
                       tags=None):
        """Ensure all provided build_requests and instances end up in cell0.

        Cell0 is the fake cell we schedule dead instances to when we can't
        schedule them somewhere real. Requests that don't yet have instances
        will get a new instance, created in cell0. Instances that have not yet
        been created will be created in cell0. All build requests are destroyed
        after we're done. Failure to delete a build request will trigger the
        instance deletion, just like the happy path in
        schedule_and_build_instances() below.
        """
        try:
            cell0 = objects.CellMapping.get_by_uuid(
                context, objects.CellMapping.CELL0_UUID)
        except exception.CellMappingNotFound:
            # Not yet setup for cellsv2. Instances will need to be written
            # to the configured database. This will become a deployment
            # error in Ocata.
            LOG.error('No cell mapping found for cell0 while '
                      'trying to record scheduling failure. '
                      'Setup is incomplete.')
            return

        build_requests = build_requests or []
        instances = instances or []
        instances_by_uuid = {inst.uuid: inst for inst in instances}
        for build_request in build_requests:
            if build_request.instance_uuid not in instances_by_uuid:
                # This is an instance object with no matching db entry.
                instance = build_request.get_new_instance(context)
                instances_by_uuid[instance.uuid] = instance

        updates = {'vm_state': vm_states.ERROR, 'task_state': None}
        for instance in instances_by_uuid.values():

            inst_mapping = None
            try:
                # We don't need the cell0-targeted context here because the
                # instance mapping is in the API DB.
                inst_mapping = \
                    objects.InstanceMapping.get_by_instance_uuid(
                        context, instance.uuid)
            except exception.InstanceMappingNotFound:
                # The API created the instance mapping record so it should
                # definitely be here. Log an error but continue to create the
                # instance in the cell0 database.
                LOG.error('While burying instance in cell0, no instance '
                          'mapping was found.', instance=instance)

            # Perform a final sanity check that the instance is not mapped
            # to some other cell already because of maybe some crazy
            # clustered message queue weirdness.
            if inst_mapping and inst_mapping.cell_mapping is not None:
                LOG.error('When attempting to bury instance in cell0, the '
                          'instance is already mapped to cell %s. Ignoring '
                          'bury in cell0 attempt.',
                          inst_mapping.cell_mapping.identity,
                          instance=instance)
                continue

            with obj_target_cell(instance, cell0) as cctxt:
                instance.create()
                if inst_mapping:
                    inst_mapping.cell_mapping = cell0
                    inst_mapping.save()

                # Record an instance action with a failed event.
                self._create_instance_action_for_cell0(
                    cctxt, instance, exc)

                # NOTE(mnaser): In order to properly clean-up volumes after
                #               being buried in cell0, we need to store BDMs.
                if block_device_mapping:
                    self._create_block_device_mapping(
                       cell0, instance.flavor, instance.uuid,
                       block_device_mapping)

                self._create_tags(cctxt, instance.uuid, tags)

                # Use the context targeted to cell0 here since the instance is
                # now in cell0.
                self._set_vm_state_and_notify(
                    cctxt, instance.uuid, 'build_instances', updates,
                    exc, request_spec)

        for build_request in build_requests:
            try:
                build_request.destroy()
            except exception.BuildRequestNotFound:
                # Instance was deleted before we finished scheduling
                inst = instances_by_uuid[build_request.instance_uuid]
                with obj_target_cell(inst, cell0):
                    inst.destroy()

    def schedule_and_build_instances(self, context, build_requests,
                                     request_specs, image,
                                     admin_password, injected_files,
                                     requested_networks, block_device_mapping,
                                     tags=None):
        # Add all the UUIDs for the instances
        instance_uuids = [spec.instance_uuid for spec in request_specs]
        try:
            host_lists = self._schedule_instances(context, request_specs[0],
                    instance_uuids, return_alternates=True)
        except Exception as exc:
            LOG.exception('Failed to schedule instances')
            self._bury_in_cell0(context, request_specs[0], exc,
                                build_requests=build_requests,
                                block_device_mapping=block_device_mapping,
                                tags=tags)
            return

        host_mapping_cache = {}
        cell_mapping_cache = {}
        instances = []
        host_az = {}  # host=az cache to optimize multi-create

        for (build_request, request_spec, host_list) in zip(
                build_requests, request_specs, host_lists):
            instance = build_request.get_new_instance(context)
            # host_list is a list of one or more Selection objects, the first
            # of which has been selected and its resources claimed.
            host = host_list[0]
            # Convert host from the scheduler into a cell record
            if host.service_host not in host_mapping_cache:
                try:
                    host_mapping = objects.HostMapping.get_by_host(
                        context, host.service_host)
                    host_mapping_cache[host.service_host] = host_mapping
                except exception.HostMappingNotFound as exc:
                    LOG.error('No host-to-cell mapping found for selected '
                              'host %(host)s. Setup is incomplete.',
                              {'host': host.service_host})
                    self._bury_in_cell0(
                        context, request_spec, exc,
                        build_requests=[build_request], instances=[instance],
                        block_device_mapping=block_device_mapping,
                        tags=tags)
                    # This is a placeholder in case the quota recheck fails.
                    instances.append(None)
                    continue
            else:
                host_mapping = host_mapping_cache[host.service_host]

            cell = host_mapping.cell_mapping

            # Before we create the instance, let's make one final check that
            # the build request is still around and wasn't deleted by the user
            # already.
            try:
                objects.BuildRequest.get_by_instance_uuid(
                    context, instance.uuid)
            except exception.BuildRequestNotFound:
                # the build request is gone so we're done for this instance
                LOG.debug('While scheduling instance, the build request '
                          'was already deleted.', instance=instance)
                # This is a placeholder in case the quota recheck fails.
                instances.append(None)
                # If the build request was deleted and the instance is not
                # going to be created, there is on point in leaving an orphan
                # instance mapping so delete it.
                try:
                    im = objects.InstanceMapping.get_by_instance_uuid(
                        context, instance.uuid)
                    im.destroy()
                except exception.InstanceMappingNotFound:
                    pass
                self.report_client.delete_allocation_for_instance(
                    context, instance.uuid, force=True)
                continue
            else:
                if host.service_host not in host_az:
                    host_az[host.service_host] = (
                        availability_zones.get_host_availability_zone(
                            context, host.service_host))
                instance.availability_zone = host_az[host.service_host]
                with obj_target_cell(instance, cell):
                    instance.create()
                    instances.append(instance)
                    cell_mapping_cache[instance.uuid] = cell

        # NOTE(melwitt): We recheck the quota after creating the
        # objects to prevent users from allocating more resources
        # than their allowed quota in the event of a race. This is
        # configurable because it can be expensive if strict quota
        # limits are not required in a deployment.
        if CONF.quota.recheck_quota:
            try:
                compute_utils.check_num_instances_quota(
                    context, instance.flavor, 0, 0,
                    orig_num_req=len(build_requests))
                placement_limits.enforce_num_instances_and_flavor(
                    context, context.project_id, instance.flavor,
                    request_specs[0].is_bfv, 0, 0)
            except (exception.TooManyInstances,
                    limit_exceptions.ProjectOverLimit) as exc:
                with excutils.save_and_reraise_exception():
                    self._cleanup_build_artifacts(context, exc, instances,
                                                  build_requests,
                                                  request_specs,
                                                  block_device_mapping, tags,
                                                  cell_mapping_cache)

        zipped = zip(build_requests, request_specs, host_lists, instances)
        for (build_request, request_spec, host_list, instance) in zipped:
            if instance is None:
                # Skip placeholders that were buried in cell0 or had their
                # build requests deleted by the user before instance create.
                continue
            cell = cell_mapping_cache[instance.uuid]
            # host_list is a list of one or more Selection objects, the first
            # of which has been selected and its resources claimed.
            host = host_list.pop(0)
            alts = [(alt.service_host, alt.nodename) for alt in host_list]
            LOG.debug("Selected host: %s; Selected node: %s; Alternates: %s",
                    host.service_host, host.nodename, alts, instance=instance)
            filter_props = request_spec.to_legacy_filter_properties_dict()
            scheduler_utils.populate_retry(filter_props, instance.uuid)
            scheduler_utils.populate_filter_properties(filter_props,
                                                       host)

            # Now that we have a selected host (which has claimed resource
            # allocations in the scheduler) for this instance, we may need to
            # map allocations to resource providers in the request spec.
            try:
                scheduler_utils.fill_provider_mapping(request_spec, host)
            except Exception as exc:
                # If anything failed here we need to cleanup and bail out.
                with excutils.save_and_reraise_exception():
                    self._cleanup_build_artifacts(
                        context, exc, instances, build_requests, request_specs,
                        block_device_mapping, tags, cell_mapping_cache)

            # TODO(melwitt): Maybe we should set_target_cell on the contexts
            # once we map to a cell, and remove these separate with statements.
            with obj_target_cell(instance, cell) as cctxt:
                # send a state update notification for the initial create to
                # show it going from non-existent to BUILDING
                # This can lazy-load attributes on instance.
                notifications.send_update_with_states(cctxt, instance, None,
                        vm_states.BUILDING, None, None, service="conductor")
                objects.InstanceAction.action_start(
                    cctxt, instance.uuid, instance_actions.CREATE,
                    want_result=False)
                instance_bdms = self._create_block_device_mapping(
                    cell, instance.flavor, instance.uuid, block_device_mapping)
                instance_tags = self._create_tags(cctxt, instance.uuid, tags)

            # TODO(Kevin Zheng): clean this up once instance.create() handles
            # tags; we do this so the instance.create notification in
            # build_and_run_instance in nova-compute doesn't lazy-load tags
            instance.tags = instance_tags if instance_tags \
                else objects.TagList()

            # Update mapping for instance.
            self._map_instance_to_cell(context, instance, cell)

            if not self._delete_build_request(
                    context, build_request, instance, cell, instance_bdms,
                    instance_tags):
                # The build request was deleted before/during scheduling so
                # the instance is gone and we don't have anything to build for
                # this one.
                continue

            try:
                accel_uuids = self._create_and_bind_arq_for_instance(
                        context, instance, host.nodename, request_spec,
                        requested_networks)
            except Exception as exc:
                with excutils.save_and_reraise_exception():
                    self._cleanup_build_artifacts(
                        context, exc, instances, build_requests, request_specs,
                        block_device_mapping, tags, cell_mapping_cache)

            # NOTE(danms): Compute RPC expects security group names or ids
            # not objects, so convert this to a list of names until we can
            # pass the objects.
            legacy_secgroups = [s.identifier
                                for s in request_spec.security_groups]
            with obj_target_cell(instance, cell) as cctxt:
                self.compute_rpcapi.build_and_run_instance(
                    cctxt, instance=instance, image=image,
                    request_spec=request_spec,
                    filter_properties=filter_props,
                    admin_password=admin_password,
                    injected_files=injected_files,
                    requested_networks=requested_networks,
                    security_groups=legacy_secgroups,
                    block_device_mapping=instance_bdms,
                    host=host.service_host, node=host.nodename,
                    limits=host.limits, host_list=host_list,
                    accel_uuids=accel_uuids)

    def _create_and_bind_arqs(
            self, cyclient, instance_uuid, extra_specs,
            hostname, resource_provider_mapping):
        """Create ARQs comes from extra specs, determine their RPs.

           The binding is asynchronous; Cyborg will notify on completion.
           The notification will be handled in the compute manager.
        """
        arqs = []
        bindings = {}
        dp_name = extra_specs.get('accel:device_profile')

        # profiles from request spec: Create ARQ and binding
        if not dp_name:
            # empty arq list and binding info
            return bindings

        LOG.debug('Calling Cyborg to get ARQs. dp_name=%s instance=%s',
                dp_name, instance_uuid)
        arqs = cyclient.create_arqs_and_match_resource_providers(
            dp_name, resource_provider_mapping)
        LOG.debug('Got ARQs with resource provider mapping %s', arqs)
        bindings = {
            arq['uuid']:
                {"hostname": hostname,
                "device_rp_uuid": arq['device_rp_uuid'],
                "instance_uuid": instance_uuid
                }
            for arq in arqs}

        return bindings

    def _create_arqs_for_ports(self, cyclient, instance_uuid,
                               requested_networks,
                               hostname, resource_provider_mapping):
        """Create ARQs for port with backend device profile.

           The binding is asynchronous; Cyborg will notify on completion.
           The notification will be handled in the compute manager.
        """
        bindings = {}

        for request_net in requested_networks:
            if request_net.port_id and request_net.device_profile:
                device_profile = request_net.device_profile
                # the port doesn't support multiple devices
                arqs = cyclient.create_arqs(device_profile)
                if len(arqs) > 1:
                    raise exception.AcceleratorRequestOpFailed(
                        op=_('create'),
                        msg='the port does not support multiple devices.')
                arq = arqs[0]

                LOG.debug("Create ARQ %s for port %s of instance %s",
                    arq["uuid"], request_net.port_id, instance_uuid)
                request_net.arq_uuid = arq["uuid"]

                rp_uuid = cyclient.get_arq_device_rp_uuid(
                    arq,
                    resource_provider_mapping,
                    request_net.port_id)

                arq_binding = {request_net.arq_uuid:
                    {"hostname": hostname,
                    "device_rp_uuid": rp_uuid,
                    "instance_uuid": instance_uuid}
                }
                LOG.debug("ARQ %s binding: %s", request_net.arq_uuid,
                    arq_binding)
                bindings.update(arq_binding)

        return bindings

    @staticmethod
    def _map_instance_to_cell(context, instance, cell):
        """Update the instance mapping to point at the given cell.

        During initial scheduling once a host and cell is selected in which
        to build the instance this method is used to update the instance
        mapping to point at that cell.

        :param context: nova auth RequestContext
        :param instance: Instance object being built
        :param cell: CellMapping representing the cell in which the instance
            was created and is being built.
        :returns: InstanceMapping object that was updated.
        """
        inst_mapping = objects.InstanceMapping.get_by_instance_uuid(
            context, instance.uuid)
        # Perform a final sanity check that the instance is not mapped
        # to some other cell already because of maybe some crazy
        # clustered message queue weirdness.
        if inst_mapping.cell_mapping is not None:
            LOG.error('During scheduling instance is already mapped to '
                      'another cell: %s. This should not happen and is an '
                      'indication of bigger problems. If you see this you '
                      'should report it to the nova team. Overwriting '
                      'the mapping to point at cell %s.',
                      inst_mapping.cell_mapping.identity, cell.identity,
                      instance=instance)
        inst_mapping.cell_mapping = cell
        inst_mapping.save()
        return inst_mapping

    def _cleanup_build_artifacts(self, context, exc, instances, build_requests,
                                 request_specs, block_device_mappings, tags,
                                 cell_mapping_cache):
        for (instance, build_request, request_spec) in zip(
                instances, build_requests, request_specs):
            # Skip placeholders that were buried in cell0 or had their
            # build requests deleted by the user before instance create.
            if instance is None:
                continue
            updates = {'vm_state': vm_states.ERROR, 'task_state': None}
            cell = cell_mapping_cache[instance.uuid]
            with try_target_cell(context, cell) as cctxt:
                self._set_vm_state_and_notify(cctxt, instance.uuid,
                                              'build_instances', updates, exc,
                                              request_spec)

            # In order to properly clean-up volumes when deleting a server in
            # ERROR status with no host, we need to store BDMs in the same
            # cell.
            if block_device_mappings:
                self._create_block_device_mapping(
                    cell, instance.flavor, instance.uuid,
                    block_device_mappings)

            # Like BDMs, the server tags provided by the user when creating the
            # server should be persisted in the same cell so they can be shown
            # from the API.
            if tags:
                with nova_context.target_cell(context, cell) as cctxt:
                    self._create_tags(cctxt, instance.uuid, tags)

            # NOTE(mdbooth): To avoid an incomplete instance record being
            #                returned by the API, the instance mapping must be
            #                created after the instance record is complete in
            #                the cell, and before the build request is
            #                destroyed.
            # TODO(mnaser): The cell mapping should already be populated by
            #               this point to avoid setting it below here.
            inst_mapping = objects.InstanceMapping.get_by_instance_uuid(
                context, instance.uuid)
            inst_mapping.cell_mapping = cell
            inst_mapping.save()

            # Be paranoid about artifacts being deleted underneath us.
            try:
                build_request.destroy()
            except exception.BuildRequestNotFound:
                pass
            try:
                request_spec.destroy()
            except exception.RequestSpecNotFound:
                pass

    def _delete_build_request(self, context, build_request, instance, cell,
                              instance_bdms, instance_tags):
        """Delete a build request after creating the instance in the cell.

        This method handles cleaning up the instance in case the build request
        is already deleted by the time we try to delete it.

        :param context: the context of the request being handled
        :type context: nova.context.RequestContext
        :param build_request: the build request to delete
        :type build_request: nova.objects.BuildRequest
        :param instance: the instance created from the build_request
        :type instance: nova.objects.Instance
        :param cell: the cell in which the instance was created
        :type cell: nova.objects.CellMapping
        :param instance_bdms: list of block device mappings for the instance
        :type instance_bdms: nova.objects.BlockDeviceMappingList
        :param instance_tags: list of tags for the instance
        :type instance_tags: nova.objects.TagList
        :returns: True if the build request was successfully deleted, False if
            the build request was already deleted and the instance is now gone.
        """
        try:
            build_request.destroy()
        except exception.BuildRequestNotFound:
            # This indicates an instance deletion request has been
            # processed, and the build should halt here. Clean up the
            # bdm, tags and instance record.
            with obj_target_cell(instance, cell) as cctxt:
                with compute_utils.notify_about_instance_delete(
                        self.notifier, cctxt, instance,
                        source=fields.NotificationSource.CONDUCTOR):
                    try:
                        instance.destroy()
                    except exception.InstanceNotFound:
                        pass
                    except exception.ObjectActionError:
                        # NOTE(melwitt): Instance became scheduled during
                        # the destroy, "host changed". Refresh and re-destroy.
                        try:
                            instance.refresh()
                            instance.destroy()
                        except exception.InstanceNotFound:
                            pass
            for bdm in instance_bdms:
                with obj_target_cell(bdm, cell):
                    try:
                        bdm.destroy()
                    except exception.ObjectActionError:
                        pass
            if instance_tags:
                with try_target_cell(context, cell) as target_ctxt:
                    try:
                        objects.TagList.destroy(target_ctxt, instance.uuid)
                    except exception.InstanceNotFound:
                        pass
            return False
        return True

    def cache_images(self, context, aggregate, image_ids):
        """Cache a set of images on the set of hosts in an aggregate.

        :param context: The RequestContext
        :param aggregate: The Aggregate object from the request to constrain
                          the host list
        :param image_id: The IDs of the image to cache
        """

        # TODO(mriedem): Consider including the list of images in the
        # notification payload.
        compute_utils.notify_about_aggregate_action(
            context, aggregate,
            fields.NotificationAction.IMAGE_CACHE,
            fields.NotificationPhase.START)

        clock = timeutils.StopWatch()
        threads = CONF.image_cache.precache_concurrency
        fetch_pool = eventlet.GreenPool(size=threads)

        hosts_by_cell = {}
        cells_by_uuid = {}
        # TODO(danms): Make this a much more efficient bulk query
        for hostname in aggregate.hosts:
            hmap = objects.HostMapping.get_by_host(context, hostname)
            cells_by_uuid.setdefault(hmap.cell_mapping.uuid, hmap.cell_mapping)
            hosts_by_cell.setdefault(hmap.cell_mapping.uuid, [])
            hosts_by_cell[hmap.cell_mapping.uuid].append(hostname)

        LOG.info('Preparing to request pre-caching of image(s) %(image_ids)s '
                 'on %(hosts)i hosts across %(cells)i cells.',
                 {'image_ids': ','.join(image_ids),
                  'hosts': len(aggregate.hosts),
                  'cells': len(hosts_by_cell)})
        clock.start()

        stats = collections.defaultdict(lambda: (0, 0, 0, 0))
        failed_images = collections.defaultdict(int)
        down_hosts = set()
        host_stats = {
            'completed': 0,
            'total': len(aggregate.hosts),
        }

        def host_completed(context, host, result):
            for image_id, status in result.items():
                cached, existing, error, unsupported = stats[image_id]
                if status == 'error':
                    failed_images[image_id] += 1
                    error += 1
                elif status == 'cached':
                    cached += 1
                elif status == 'existing':
                    existing += 1
                elif status == 'unsupported':
                    unsupported += 1
                stats[image_id] = (cached, existing, error, unsupported)

            host_stats['completed'] += 1
            compute_utils.notify_about_aggregate_cache(context, aggregate,
                                                       host, result,
                                                       host_stats['completed'],
                                                       host_stats['total'])

        def wrap_cache_images(ctxt, host, image_ids):
            result = self.compute_rpcapi.cache_images(
                ctxt,
                host=host,
                image_ids=image_ids)
            host_completed(context, host, result)

        def skipped_host(context, host, image_ids):
            result = {image: 'skipped' for image in image_ids}
            host_completed(context, host, result)

        for cell_uuid, hosts in hosts_by_cell.items():
            cell = cells_by_uuid[cell_uuid]
            with nova_context.target_cell(context, cell) as target_ctxt:
                for host in hosts:
                    service = objects.Service.get_by_compute_host(target_ctxt,
                                                                  host)
                    if not self.servicegroup_api.service_is_up(service):
                        down_hosts.add(host)
                        LOG.info(
                            'Skipping image pre-cache request to compute '
                            '%(host)r because it is not up',
                            {'host': host})
                        skipped_host(target_ctxt, host, image_ids)
                        continue

                    fetch_pool.spawn_n(wrap_cache_images, target_ctxt, host,
                                       image_ids)

        # Wait until all those things finish
        fetch_pool.waitall()

        overall_stats = {'cached': 0, 'existing': 0, 'error': 0,
                         'unsupported': 0}
        for cached, existing, error, unsupported in stats.values():
            overall_stats['cached'] += cached
            overall_stats['existing'] += existing
            overall_stats['error'] += error
            overall_stats['unsupported'] += unsupported

        clock.stop()
        LOG.info('Image pre-cache operation for image(s) %(image_ids)s '
                 'completed in %(time).2f seconds; '
                 '%(cached)i cached, %(existing)i existing, %(error)i errors, '
                 '%(unsupported)i unsupported, %(skipped)i skipped (down) '
                 'hosts',
                 {'image_ids': ','.join(image_ids),
                  'time': clock.elapsed(),
                  'cached': overall_stats['cached'],
                  'existing': overall_stats['existing'],
                  'error': overall_stats['error'],
                  'unsupported': overall_stats['unsupported'],
                  'skipped': len(down_hosts),
                 })
        # Log error'd images specifically at warning level
        for image_id, fails in failed_images.items():
            LOG.warning('Image pre-cache operation for image %(image)s '
                        'failed %(fails)i times',
                        {'image': image_id,
                         'fails': fails})

        compute_utils.notify_about_aggregate_action(
            context, aggregate,
            fields.NotificationAction.IMAGE_CACHE,
            fields.NotificationPhase.END)

    @targets_cell
    @wrap_instance_event(prefix='conductor')
    def confirm_snapshot_based_resize(self, context, instance, migration):
        """Executes the ConfirmResizeTask

        :param context: nova auth request context targeted at the target cell
        :param instance: Instance object in "resized" status from the target
            cell
        :param migration: Migration object from the target cell for the resize
            operation expected to have status "confirming"
        """
        task = cross_cell_migrate.ConfirmResizeTask(
            context, instance, migration, self.notifier, self.compute_rpcapi)
        task.execute()

    @targets_cell
    # NOTE(mriedem): Upon successful completion of RevertResizeTask the
    # instance is hard-deleted, along with its instance action record(s), from
    # the target cell database so EventReporter hits InstanceActionNotFound on
    # __exit__. Pass graceful_exit=True to avoid an ugly traceback.
    @wrap_instance_event(prefix='conductor', graceful_exit=True)
    def revert_snapshot_based_resize(self, context, instance, migration):
        """Executes the RevertResizeTask

        :param context: nova auth request context targeted at the target cell
        :param instance: Instance object in "resized" status from the target
            cell
        :param migration: Migration object from the target cell for the resize
            operation expected to have status "reverting"
        """
        task = cross_cell_migrate.RevertResizeTask(
            context, instance, migration, self.notifier, self.compute_rpcapi)
        task.execute()