summaryrefslogtreecommitdiff
path: root/glance/db/sqlalchemy/api.py
blob: b8794fb2dfaae4bc7c4640c39381a6215d7f0710 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2012 Justin Santa Barbara
# Copyright 2013 IBM Corp.
# Copyright 2015 Mirantis, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.


"""Defines interface for DB access."""

import datetime
import itertools
import threading

from oslo_config import cfg
from oslo_db import exception as db_exception
from oslo_db.sqlalchemy import session
from oslo_log import log as logging
from oslo_utils import excutils
import osprofiler.sqlalchemy
from retrying import retry
import six
# NOTE(jokke): simplified transition to py3, behaves like py2 xrange
from six.moves import range
import sqlalchemy
from sqlalchemy.ext.compiler import compiles
from sqlalchemy import MetaData, Table
import sqlalchemy.orm as sa_orm
from sqlalchemy import sql
import sqlalchemy.sql as sa_sql

from glance.common import exception
from glance.common import timeutils
from glance.common import utils
from glance.db.sqlalchemy.metadef_api import (resource_type
                                              as metadef_resource_type_api)
from glance.db.sqlalchemy.metadef_api import (resource_type_association
                                              as metadef_association_api)
from glance.db.sqlalchemy.metadef_api import namespace as metadef_namespace_api
from glance.db.sqlalchemy.metadef_api import object as metadef_object_api
from glance.db.sqlalchemy.metadef_api import property as metadef_property_api
from glance.db.sqlalchemy.metadef_api import tag as metadef_tag_api
from glance.db.sqlalchemy import models
from glance.db import utils as db_utils
from glance.i18n import _, _LW, _LI, _LE

sa_logger = None
LOG = logging.getLogger(__name__)


STATUSES = ['active', 'saving', 'queued', 'killed', 'pending_delete',
            'deleted', 'deactivated', 'importing', 'uploading']

CONF = cfg.CONF
CONF.import_group("profiler", "glance.common.wsgi")

_FACADE = None
_LOCK = threading.Lock()


def _retry_on_deadlock(exc):
    """Decorator to retry a DB API call if Deadlock was received."""

    if isinstance(exc, db_exception.DBDeadlock):
        LOG.warn(_LW("Deadlock detected. Retrying..."))
        return True
    return False


def _create_facade_lazily():
    global _LOCK, _FACADE
    if _FACADE is None:
        with _LOCK:
            if _FACADE is None:
                _FACADE = session.EngineFacade.from_config(CONF)

                if CONF.profiler.enabled and CONF.profiler.trace_sqlalchemy:
                    osprofiler.sqlalchemy.add_tracing(sqlalchemy,
                                                      _FACADE.get_engine(),
                                                      "db")
    return _FACADE


def get_engine():
    facade = _create_facade_lazily()
    return facade.get_engine()


def get_session(autocommit=True, expire_on_commit=False):
    facade = _create_facade_lazily()
    return facade.get_session(autocommit=autocommit,
                              expire_on_commit=expire_on_commit)


def _validate_db_int(**kwargs):
    """Make sure that all arguments are less than or equal to 2 ** 31 - 1.

    This limitation is introduced because databases stores INT in 4 bytes.
    If the validation fails for some argument, exception.Invalid is raised with
    appropriate information.
    """
    max_int = (2 ** 31) - 1

    for param_key, param_value in kwargs.items():
        if param_value and param_value > max_int:
            msg = _("'%(param)s' value out of range, "
                    "must not exceed %(max)d.") % {"param": param_key,
                                                   "max": max_int}
            raise exception.Invalid(msg)


def clear_db_env():
    """
    Unset global configuration variables for database.
    """
    global _FACADE
    _FACADE = None


def _check_mutate_authorization(context, image_ref):
    if not is_image_mutable(context, image_ref):
        LOG.warn(_LW("Attempted to modify image user did not own."))
        msg = _("You do not own this image")
        if image_ref.visibility in ['private', 'shared']:
            exc_class = exception.Forbidden
        else:
            # 'public', or 'community'
            exc_class = exception.ForbiddenPublicImage

        raise exc_class(msg)


def image_create(context, values, v1_mode=False):
    """Create an image from the values dictionary."""
    image = _image_update(context, values, None, purge_props=False)
    if v1_mode:
        image = db_utils.mutate_image_dict_to_v1(image)
    return image


def image_update(context, image_id, values, purge_props=False,
                 from_state=None, v1_mode=False, atomic_props=None):
    """
    Set the given properties on an image and update it.

    :raises: ImageNotFound if image does not exist.
    """
    image = _image_update(context, values, image_id, purge_props,
                          from_state=from_state, atomic_props=atomic_props)
    if v1_mode:
        image = db_utils.mutate_image_dict_to_v1(image)
    return image


def image_restore(context, image_id):
    """Restore the pending-delete image to active."""
    session = get_session()
    with session.begin():
        image_ref = _image_get(context, image_id, session=session)
        if image_ref.status != 'pending_delete':
            msg = (_('cannot restore the image from %s to active (wanted '
                     'from_state=pending_delete)') % image_ref.status)
            raise exception.Conflict(msg)

        query = session.query(models.Image).filter_by(id=image_id)
        values = {'status': 'active', 'deleted': 0}
        query.update(values, synchronize_session='fetch')


@retry(retry_on_exception=_retry_on_deadlock, wait_fixed=500,
       stop_max_attempt_number=50)
def image_destroy(context, image_id):
    """Destroy the image or raise if it does not exist."""
    session = get_session()
    with session.begin():
        image_ref = _image_get(context, image_id, session=session)

        # Perform authorization check
        _check_mutate_authorization(context, image_ref)

        image_ref.delete(session=session)
        delete_time = image_ref.deleted_at

        _image_locations_delete_all(context, image_id, delete_time, session)

        _image_property_delete_all(context, image_id, delete_time, session)

        _image_member_delete_all(context, image_id, delete_time, session)

        _image_tag_delete_all(context, image_id, delete_time, session)

    return _normalize_locations(context, image_ref)


def _normalize_locations(context, image, force_show_deleted=False):
    """
    Generate suitable dictionary list for locations field of image.

    We don't need to set other data fields of location record which return
    from image query.
    """

    if image['status'] == 'deactivated' and not context.is_admin:
        # Locations are not returned for a deactivated image for non-admin user
        image['locations'] = []
        return image

    if force_show_deleted:
        locations = image['locations']
    else:
        locations = [x for x in image['locations'] if not x.deleted]
    image['locations'] = [{'id': loc['id'],
                           'url': loc['value'],
                           'metadata': loc['meta_data'],
                           'status': loc['status']}
                          for loc in locations]
    return image


def _normalize_tags(image):
    undeleted_tags = [x for x in image['tags'] if not x.deleted]
    image['tags'] = [tag['value'] for tag in undeleted_tags]
    return image


def image_get(context, image_id, session=None, force_show_deleted=False,
              v1_mode=False):
    image = _image_get(context, image_id, session=session,
                       force_show_deleted=force_show_deleted)
    image = _normalize_locations(context, image.to_dict(),
                                 force_show_deleted=force_show_deleted)
    if v1_mode:
        image = db_utils.mutate_image_dict_to_v1(image)
    return image


def _check_image_id(image_id):
    """
    check if the given image id is valid before executing operations. For
    now, we only check its length. The original purpose of this method is
    wrapping the different behaviors between MySql and DB2 when the image id
    length is longer than the defined length in database model.
    :param image_id: The id of the image we want to check
    :returns: Raise NoFound exception if given image id is invalid
    """
    if (image_id and
       len(image_id) > models.Image.id.property.columns[0].type.length):
        raise exception.ImageNotFound()


def _image_get(context, image_id, session=None, force_show_deleted=False):
    """Get an image or raise if it does not exist."""
    _check_image_id(image_id)
    session = session or get_session()

    try:
        query = session.query(models.Image).options(
            sa_orm.joinedload(models.Image.properties)).options(
                sa_orm.joinedload(
                    models.Image.locations)).filter_by(id=image_id)

        # filter out deleted images if context disallows it
        if not force_show_deleted and not context.can_see_deleted:
            query = query.filter_by(deleted=False)

        image = query.one()

    except sa_orm.exc.NoResultFound:
        msg = "No image found with ID %s" % image_id
        LOG.debug(msg)
        raise exception.ImageNotFound(msg)

    # Make sure they can look at it
    if not is_image_visible(context, image):
        msg = "Forbidding request, image %s not visible" % image_id
        LOG.debug(msg)
        raise exception.Forbidden(msg)

    return image


def is_image_mutable(context, image):
    """Return True if the image is mutable in this context."""
    # Is admin == image mutable
    if context.is_admin:
        return True

    # No owner == image not mutable
    if image['owner'] is None or context.owner is None:
        return False

    # Image only mutable by its owner
    return image['owner'] == context.owner


def is_image_visible(context, image, status=None):
    """Return True if the image is visible in this context."""
    return db_utils.is_image_visible(context, image, image_member_find, status)


def _get_default_column_value(column_type):
    """Return the default value of the columns from DB table

    In postgreDB case, if no right default values are being set, an
    psycopg2.DataError will be thrown.
    """
    type_schema = {
        'datetime': None,
        'big_integer': 0,
        'integer': 0,
        'string': ''
    }

    if isinstance(column_type, sa_sql.type_api.Variant):
        return _get_default_column_value(column_type.impl)

    return type_schema[column_type.__visit_name__]


def _paginate_query(query, model, limit, sort_keys, marker=None,
                    sort_dir=None, sort_dirs=None):
    """Returns a query with sorting / pagination criteria added.

    Pagination works by requiring a unique sort_key, specified by sort_keys.
    (If sort_keys is not unique, then we risk looping through values.)
    We use the last row in the previous page as the 'marker' for pagination.
    So we must return values that follow the passed marker in the order.
    With a single-valued sort_key, this would be easy: sort_key > X.
    With a compound-values sort_key, (k1, k2, k3) we must do this to repeat
    the lexicographical ordering:
    (k1 > X1) or (k1 == X1 && k2 > X2) or (k1 == X1 && k2 == X2 && k3 > X3)

    We also have to cope with different sort_directions.

    Typically, the id of the last row is used as the client-facing pagination
    marker, then the actual marker object must be fetched from the db and
    passed in to us as marker.

    :param query: the query object to which we should add paging/sorting
    :param model: the ORM model class
    :param limit: maximum number of items to return
    :param sort_keys: array of attributes by which results should be sorted
    :param marker: the last item of the previous page; we returns the next
                    results after this value.
    :param sort_dir: direction in which results should be sorted (asc, desc)
    :param sort_dirs: per-column array of sort_dirs, corresponding to sort_keys

    :rtype: sqlalchemy.orm.query.Query
    :returns: The query with sorting/pagination added.
    """

    if 'id' not in sort_keys:
        # TODO(justinsb): If this ever gives a false-positive, check
        # the actual primary key, rather than assuming its id
        LOG.warn(_LW('Id not in sort_keys; is sort_keys unique?'))

    assert(not (sort_dir and sort_dirs))  # nosec
    # nosec: This function runs safely if the assertion fails.

    # Default the sort direction to ascending
    if sort_dir is None:
        sort_dir = 'asc'

    # Ensure a per-column sort direction
    if sort_dirs is None:
        sort_dirs = [sort_dir] * len(sort_keys)

    assert(len(sort_dirs) == len(sort_keys))  # nosec
    # nosec: This function runs safely if the assertion fails.
    if len(sort_dirs) < len(sort_keys):
        sort_dirs += [sort_dir] * (len(sort_keys) - len(sort_dirs))

    # Add sorting
    for current_sort_key, current_sort_dir in zip(sort_keys, sort_dirs):
        sort_dir_func = {
            'asc': sqlalchemy.asc,
            'desc': sqlalchemy.desc,
        }[current_sort_dir]

        try:
            sort_key_attr = getattr(model, current_sort_key)
        except AttributeError:
            raise exception.InvalidSortKey()
        query = query.order_by(sort_dir_func(sort_key_attr))

    default = ''  # Default to an empty string if NULL

    # Add pagination
    if marker is not None:
        marker_values = []
        for sort_key in sort_keys:
            v = getattr(marker, sort_key)
            if v is None:
                v = default
            marker_values.append(v)

        # Build up an array of sort criteria as in the docstring
        criteria_list = []
        for i in range(len(sort_keys)):
            crit_attrs = []
            for j in range(i):
                model_attr = getattr(model, sort_keys[j])
                default = _get_default_column_value(
                    model_attr.property.columns[0].type)
                attr = sa_sql.expression.case([(model_attr != None,
                                              model_attr), ],
                                              else_=default)
                crit_attrs.append((attr == marker_values[j]))

            model_attr = getattr(model, sort_keys[i])
            default = _get_default_column_value(
                model_attr.property.columns[0].type)
            attr = sa_sql.expression.case([(model_attr != None,
                                          model_attr), ],
                                          else_=default)
            if sort_dirs[i] == 'desc':
                crit_attrs.append((attr < marker_values[i]))
            elif sort_dirs[i] == 'asc':
                crit_attrs.append((attr > marker_values[i]))
            else:
                raise ValueError(_("Unknown sort direction, "
                                   "must be 'desc' or 'asc'"))

            criteria = sa_sql.and_(*crit_attrs)
            criteria_list.append(criteria)

        f = sa_sql.or_(*criteria_list)
        query = query.filter(f)

    if limit is not None:
        query = query.limit(limit)

    return query


def _make_conditions_from_filters(filters, is_public=None):
    # NOTE(venkatesh) make copy of the filters are to be altered in this
    # method.
    filters = filters.copy()

    image_conditions = []
    prop_conditions = []
    tag_conditions = []

    if is_public is not None:
        if is_public:
            image_conditions.append(models.Image.visibility == 'public')
        else:
            image_conditions.append(models.Image.visibility != 'public')

    if 'os_hidden' in filters:
        os_hidden = filters.pop('os_hidden')
        image_conditions.append(models.Image.os_hidden == os_hidden)

    if 'checksum' in filters:
        checksum = filters.pop('checksum')
        image_conditions.append(models.Image.checksum == checksum)

    if 'os_hash_value' in filters:
        os_hash_value = filters.pop('os_hash_value')
        image_conditions.append(models.Image.os_hash_value == os_hash_value)

    for (k, v) in filters.pop('properties', {}).items():
        prop_filters = _make_image_property_condition(key=k, value=v)
        prop_conditions.append(prop_filters)

    if 'changes-since' in filters:
        # normalize timestamp to UTC, as sqlalchemy doesn't appear to
        # respect timezone offsets
        changes_since = timeutils.normalize_time(filters.pop('changes-since'))
        image_conditions.append(models.Image.updated_at > changes_since)

    if 'deleted' in filters:
        deleted_filter = filters.pop('deleted')
        image_conditions.append(models.Image.deleted == deleted_filter)
        # TODO(bcwaldon): handle this logic in registry server
        if not deleted_filter:
            image_statuses = [s for s in STATUSES if s != 'killed']
            image_conditions.append(models.Image.status.in_(image_statuses))

    if 'tags' in filters:
        tags = filters.pop('tags')
        for tag in tags:
            tag_filters = [models.ImageTag.deleted == False]
            tag_filters.extend([models.ImageTag.value == tag])
            tag_conditions.append(tag_filters)

    filters = {k: v for k, v in filters.items() if v is not None}

    # need to copy items because filters is modified in the loop body
    # (filters.pop(k))
    keys = list(filters.keys())
    for k in keys:
        key = k
        if k.endswith('_min') or k.endswith('_max'):
            key = key[0:-4]
            try:
                v = int(filters.pop(k))
            except ValueError:
                msg = _("Unable to filter on a range "
                        "with a non-numeric value.")
                raise exception.InvalidFilterRangeValue(msg)

            if k.endswith('_min'):
                image_conditions.append(getattr(models.Image, key) >= v)
            if k.endswith('_max'):
                image_conditions.append(getattr(models.Image, key) <= v)
        elif k in ['created_at', 'updated_at']:
            attr_value = getattr(models.Image, key)
            operator, isotime = utils.split_filter_op(filters.pop(k))
            try:
                parsed_time = timeutils.parse_isotime(isotime)
                threshold = timeutils.normalize_time(parsed_time)
            except ValueError:
                msg = (_("Bad \"%s\" query filter format. "
                         "Use ISO 8601 DateTime notation.") % k)
                raise exception.InvalidParameterValue(msg)

            comparison = utils.evaluate_filter_op(attr_value, operator,
                                                  threshold)
            image_conditions.append(comparison)

        elif k in ['name', 'id', 'status', 'container_format', 'disk_format']:
            attr_value = getattr(models.Image, key)
            operator, list_value = utils.split_filter_op(filters.pop(k))
            if operator == 'in':
                threshold = utils.split_filter_value_for_quotes(list_value)
                comparison = attr_value.in_(threshold)
                image_conditions.append(comparison)
            elif operator == 'eq':
                image_conditions.append(attr_value == list_value)
            else:
                msg = (_("Unable to filter by unknown operator '%s'.")
                       % operator)
                raise exception.InvalidFilterOperatorValue(msg)

    for (k, value) in filters.items():
        if hasattr(models.Image, k):
            image_conditions.append(getattr(models.Image, k) == value)
        else:
            prop_filters = _make_image_property_condition(key=k, value=value)
            prop_conditions.append(prop_filters)

    return image_conditions, prop_conditions, tag_conditions


def _make_image_property_condition(key, value):
    prop_filters = [models.ImageProperty.deleted == False]
    prop_filters.extend([models.ImageProperty.name == key])
    prop_filters.extend([models.ImageProperty.value == value])
    return prop_filters


def _select_images_query(context, image_conditions, admin_as_user,
                         member_status, visibility):
    session = get_session()

    img_conditional_clause = sa_sql.and_(*image_conditions)

    regular_user = (not context.is_admin) or admin_as_user

    query_member = session.query(models.Image).join(
        models.Image.members).filter(img_conditional_clause)
    if regular_user:
        member_filters = [models.ImageMember.deleted == False]
        member_filters.extend([models.Image.visibility == 'shared'])
        if context.owner is not None:
            member_filters.extend([models.ImageMember.member == context.owner])
            if member_status != 'all':
                member_filters.extend([
                    models.ImageMember.status == member_status])
        query_member = query_member.filter(sa_sql.and_(*member_filters))

    query_image = session.query(models.Image).filter(img_conditional_clause)
    if regular_user:
        visibility_filters = [
            models.Image.visibility == 'public',
            models.Image.visibility == 'community',
        ]
        query_image = query_image .filter(sa_sql.or_(*visibility_filters))
        query_image_owner = None
        if context.owner is not None:
            query_image_owner = session.query(models.Image).filter(
                models.Image.owner == context.owner).filter(
                    img_conditional_clause)
        if query_image_owner is not None:
            query = query_image.union(query_image_owner, query_member)
        else:
            query = query_image.union(query_member)
        return query
    else:
        # Admin user
        return query_image


def image_get_all(context, filters=None, marker=None, limit=None,
                  sort_key=None, sort_dir=None,
                  member_status='accepted', is_public=None,
                  admin_as_user=False, return_tag=False, v1_mode=False):
    """
    Get all images that match zero or more filters.

    :param filters: dict of filter keys and values. If a 'properties'
                    key is present, it is treated as a dict of key/value
                    filters on the image properties attribute
    :param marker: image id after which to start page
    :param limit: maximum number of images to return
    :param sort_key: list of image attributes by which results should be sorted
    :param sort_dir: directions in which results should be sorted (asc, desc)
    :param member_status: only return shared images that have this membership
                          status
    :param is_public: If true, return only public images. If false, return
                      only private and shared images.
    :param admin_as_user: For backwards compatibility. If true, then return to
                      an admin the equivalent set of images which it would see
                      if it was a regular user
    :param return_tag: To indicates whether image entry in result includes it
                       relevant tag entries. This could improve upper-layer
                       query performance, to prevent using separated calls
    :param v1_mode: If true, mutates the 'visibility' value of each image
                    into the v1-compatible field 'is_public'
    """
    sort_key = ['created_at'] if not sort_key else sort_key

    default_sort_dir = 'desc'

    if not sort_dir:
        sort_dir = [default_sort_dir] * len(sort_key)
    elif len(sort_dir) == 1:
        default_sort_dir = sort_dir[0]
        sort_dir *= len(sort_key)

    filters = filters or {}

    visibility = filters.pop('visibility', None)
    showing_deleted = 'changes-since' in filters or filters.get('deleted',
                                                                False)

    img_cond, prop_cond, tag_cond = _make_conditions_from_filters(
        filters, is_public)

    query = _select_images_query(context,
                                 img_cond,
                                 admin_as_user,
                                 member_status,
                                 visibility)
    if visibility is not None:
        # with a visibility, we always and only include images with that
        # visibility except when using the 'all' visibility
        if visibility != 'all':
            query = query.filter(models.Image.visibility == visibility)
    elif context.owner is None:
        # without either a visibility or an owner, we never include
        # 'community' images
        query = query.filter(models.Image.visibility != 'community')
    else:
        # without a visibility and with an owner, we only want to include
        # 'community' images if and only if they are owned by this owner
        community_filters = [
            models.Image.owner == context.owner,
            models.Image.visibility != 'community',
        ]
        query = query.filter(sa_sql.or_(*community_filters))

    if prop_cond:
        for prop_condition in prop_cond:
            query = query.join(models.ImageProperty, aliased=True).filter(
                sa_sql.and_(*prop_condition))

    if tag_cond:
        for tag_condition in tag_cond:
            query = query.join(models.ImageTag, aliased=True).filter(
                sa_sql.and_(*tag_condition))

    marker_image = None
    if marker is not None:
        marker_image = _image_get(context,
                                  marker,
                                  force_show_deleted=showing_deleted)

    for key in ['created_at', 'id']:
        if key not in sort_key:
            sort_key.append(key)
            sort_dir.append(default_sort_dir)

    query = _paginate_query(query, models.Image, limit,
                            sort_key,
                            marker=marker_image,
                            sort_dir=None,
                            sort_dirs=sort_dir)

    query = query.options(sa_orm.joinedload(
        models.Image.properties)).options(
            sa_orm.joinedload(models.Image.locations))
    if return_tag:
        query = query.options(sa_orm.joinedload(models.Image.tags))

    images = []
    for image in query.all():
        image_dict = image.to_dict()
        image_dict = _normalize_locations(context, image_dict,
                                          force_show_deleted=showing_deleted)
        if return_tag:
            image_dict = _normalize_tags(image_dict)
        if v1_mode:
            image_dict = db_utils.mutate_image_dict_to_v1(image_dict)
        images.append(image_dict)
    return images


def _drop_protected_attrs(model_class, values):
    """
    Removed protected attributes from values dictionary using the models
    __protected_attributes__ field.
    """
    for attr in model_class.__protected_attributes__:
        if attr in values:
            del values[attr]


def _image_get_disk_usage_by_owner(owner, session, image_id=None):
    query = session.query(models.Image)
    query = query.filter(models.Image.owner == owner)
    if image_id is not None:
        query = query.filter(models.Image.id != image_id)
    query = query.filter(models.Image.size > 0)
    query = query.filter(~models.Image.status.in_(['killed', 'deleted']))
    images = query.all()

    total = 0
    for i in images:
        locations = [l for l in i.locations if l['status'] != 'deleted']
        total += (i.size * len(locations))
    return total


def _image_get_staging_usage_by_owner(owner, session):
    # NOTE(danms): We could do this in a single query, but I think it is
    # easier to understand as two that we concatenate while generating
    # results.

    # Images in uploading or importing state are consuming staging
    # space.
    query = session.query(models.Image)
    query = query.filter(models.Image.owner == owner)
    query = query.filter(models.Image.size > 0)
    query = query.filter(models.Image.status.in_(('uploading',
                                                  'importing')))
    importing_images = query.all()

    # Images with non-empty os_glance_importing_to_stores properties
    # may also be consuming staging space. Filter our deleted images
    # or importing ones included in the above query.
    props = session.query(models.ImageProperty).filter(
        models.ImageProperty.name == 'os_glance_importing_to_stores',
        models.ImageProperty.value != '').subquery()
    query = session.query(models.Image)
    query = query.join(props, props.c.image_id == models.Image.id)
    query = query.filter(models.Image.owner == owner)
    query = query.filter(models.Image.size > 0)
    query = query.filter(~models.Image.status.in_(('uploading',
                                                   'importing',
                                                   'killed',
                                                   'deleted')))
    copying_images = query.all()

    return sum(i.size for i in itertools.chain(importing_images,
                                               copying_images))


def _image_get_count_by_owner(owner, session):
    query = session.query(models.Image)
    query = query.filter(models.Image.owner == owner)
    query = query.filter(~models.Image.status.in_(['killed', 'deleted']))
    return query.count()


def _image_get_uploading_count_by_owner(owner, session):
    """Return a count of the images uploading or importing."""

    importing_statuses = ('saving', 'uploading', 'importing')

    # Images in any state indicating uploading, including through image_upload
    # or importing count for this.
    query = session.query(models.Image)
    query = query.filter(models.Image.owner == owner)
    query = query.filter(models.Image.status.in_(importing_statuses))
    uploading = query.count()

    # Images that are not in the above list, but are not deleted and
    # in the process of doing a copy count for this.
    props = session.query(models.ImageProperty).filter(
        models.ImageProperty.name == 'os_glance_importing_to_stores',
        models.ImageProperty.value != '').subquery()
    query = session.query(models.Image)
    query = query.join(props, props.c.image_id == models.Image.id)
    query = query.filter(models.Image.owner == owner)
    query = query.filter(~models.Image.status.in_(importing_statuses +
                                                  ('killed', 'deleted')))
    copying = query.count()

    return uploading + copying


def _validate_image(values, mandatory_status=True):
    """
    Validates the incoming data and raises a Invalid exception
    if anything is out of order.

    :param values: Mapping of image metadata to check
    :param mandatory_status: Whether to validate status from values
    """

    if mandatory_status:
        status = values.get('status')
        if not status:
            msg = "Image status is required."
            raise exception.Invalid(msg)

        if status not in STATUSES:
            msg = "Invalid image status '%s' for image." % status
            raise exception.Invalid(msg)

    # validate integer values to eliminate DBError on save
    _validate_db_int(min_disk=values.get('min_disk'),
                     min_ram=values.get('min_ram'))

    return values


def _update_values(image_ref, values):
    for k in values:
        if getattr(image_ref, k) != values[k]:
            setattr(image_ref, k, values[k])


def image_set_property_atomic(image_id, name, value):
    """
    Atomically set an image property to a value.

    This will only succeed if the property does not currently exist
    and it was created successfully. This can be used by multiple
    competing threads to ensure that only one of those threads
    succeeded in creating the property.

    Note that ImageProperty objects are marked as deleted=$id and so we must
    first try to atomically update-and-undelete such a property, if it
    exists. If that does not work, we should try to create the property. The
    latter should fail with DBDuplicateEntry because of the UniqueConstraint
    across ImageProperty(image_id, name).

    :param image_id: The ID of the image on which to create the property
    :param name: The property name
    :param value: The value to set for the property
    :raises Duplicate: If the property already exists
    """
    session = get_session()
    with session.begin():
        connection = session.connection()
        table = models.ImageProperty.__table__

        # This should be:
        #   UPDATE image_properties SET value=$value, deleted=False
        #     WHERE name=$name AND deleted!=False
        result = connection.execute(table.update().where(
            sa_sql.and_(table.c.name == name,
                        table.c.image_id == image_id,
                        table.c.deleted != False)).values(
                            value=value, deleted=False))
        if result.rowcount == 1:
            # Found and updated a deleted property, so we win
            return

        # There might have been no deleted property, or the property
        # exists and is undeleted, so try to create it and use that
        # to determine if we've lost the race or not.

        try:
            connection.execute(table.insert(),
                               dict(deleted=False,
                                    created_at=timeutils.utcnow(),
                                    image_id=image_id,
                                    name=name,
                                    value=value))
        except db_exception.DBDuplicateEntry:
            # Lost the race to create the new property
            raise exception.Duplicate()

        # If we got here, we created a new row, UniqueConstraint would have
        # caused us to fail if we lost the race


def image_delete_property_atomic(image_id, name, value):
    """
    Atomically delete an image property.

    This will only succeed if the referenced image has a property set
    to exactly the value provided.

    :param image_id: The ID of the image on which to delete the property
    :param name: The property name
    :param value: The value the property is expected to be set to
    :raises NotFound: If the property does not exist
    """
    session = get_session()
    with session.begin():
        connection = session.connection()
        table = models.ImageProperty.__table__

        result = connection.execute(table.delete().where(
            sa_sql.and_(table.c.name == name,
                        table.c.value == value,
                        table.c.image_id == image_id,
                        table.c.deleted == False)))
        if result.rowcount == 1:
            return

        raise exception.NotFound()


@retry(retry_on_exception=_retry_on_deadlock, wait_fixed=500,
       stop_max_attempt_number=50)
@utils.no_4byte_params
def _image_update(context, values, image_id, purge_props=False,
                  from_state=None, atomic_props=None):
    """
    Used internally by image_create and image_update

    :param context: Request context
    :param values: A dict of attributes to set
    :param image_id: If None, create the image, otherwise, find and update it
    :param from_state: If not None, reequire the image be in this state to do
                       the update
    :param purge_props: If True, delete properties found in the database but
                        not present in values
    :param atomic_props: If non-None, refuse to create or update properties
                         in this list
    """

    # NOTE(jbresnah) values is altered in this so a copy is needed
    values = values.copy()

    session = get_session()
    with session.begin():

        # Remove the properties passed in the values mapping. We
        # handle properties separately from base image attributes,
        # and leaving properties in the values mapping will cause
        # a SQLAlchemy model error because SQLAlchemy expects the
        # properties attribute of an Image model to be a list and
        # not a dict.
        properties = values.pop('properties', {})

        location_data = values.pop('locations', None)

        new_status = values.get('status')
        if image_id:
            image_ref = _image_get(context, image_id, session=session)
            current = image_ref.status
            # Perform authorization check
            _check_mutate_authorization(context, image_ref)
        else:
            if values.get('size') is not None:
                values['size'] = int(values['size'])

            if 'min_ram' in values:
                values['min_ram'] = int(values['min_ram'] or 0)

            if 'min_disk' in values:
                values['min_disk'] = int(values['min_disk'] or 0)

            values['protected'] = bool(values.get('protected', False))
            image_ref = models.Image()

        values = db_utils.ensure_image_dict_v2_compliant(values)

        # Need to canonicalize ownership
        if 'owner' in values and not values['owner']:
            values['owner'] = None

        if image_id:
            # Don't drop created_at if we're passing it in...
            _drop_protected_attrs(models.Image, values)
            # NOTE(iccha-sethi): updated_at must be explicitly set in case
            #                   only ImageProperty table was modifited
            values['updated_at'] = timeutils.utcnow()

        if image_id:
            query = session.query(models.Image).filter_by(id=image_id)
            if from_state:
                query = query.filter_by(status=from_state)

            mandatory_status = True if new_status else False
            _validate_image(values, mandatory_status=mandatory_status)

            # Validate fields for Images table. This is similar to what is done
            # for the query result update except that we need to do it prior
            # in this case.
            values = {key: values[key] for key in values
                      if key in image_ref.to_dict()}
            updated = query.update(values, synchronize_session='fetch')

            if not updated:
                msg = (_('cannot transition from %(current)s to '
                         '%(next)s in update (wanted '
                         'from_state=%(from)s)') %
                       {'current': current, 'next': new_status,
                        'from': from_state})
                raise exception.Conflict(msg)

            image_ref = _image_get(context, image_id, session=session)
        else:
            image_ref.update(values)
            # Validate the attributes before we go any further. From my
            # investigation, the @validates decorator does not validate
            # on new records, only on existing records, which is, well,
            # idiotic.
            values = _validate_image(image_ref.to_dict())
            _update_values(image_ref, values)

            try:
                image_ref.save(session=session)
            except db_exception.DBDuplicateEntry:
                raise exception.Duplicate("Image ID %s already exists!"
                                          % values['id'])

        _set_properties_for_image(context, image_ref, properties, purge_props,
                                  atomic_props, session)

        if location_data:
            _image_locations_set(context, image_ref.id, location_data,
                                 session=session)

    return image_get(context, image_ref.id)


@utils.no_4byte_params
def image_location_add(context, image_id, location, session=None):
    deleted = location['status'] in ('deleted', 'pending_delete')
    delete_time = timeutils.utcnow() if deleted else None
    location_ref = models.ImageLocation(image_id=image_id,
                                        value=location['url'],
                                        meta_data=location['metadata'],
                                        status=location['status'],
                                        deleted=deleted,
                                        deleted_at=delete_time)
    session = session or get_session()
    location_ref.save(session=session)


@utils.no_4byte_params
def image_location_update(context, image_id, location, session=None):
    loc_id = location.get('id')
    if loc_id is None:
        msg = _("The location data has an invalid ID: %d") % loc_id
        raise exception.Invalid(msg)

    try:
        session = session or get_session()
        location_ref = session.query(models.ImageLocation).filter_by(
            id=loc_id).filter_by(image_id=image_id).one()

        deleted = location['status'] in ('deleted', 'pending_delete')
        updated_time = timeutils.utcnow()
        delete_time = updated_time if deleted else None

        location_ref.update({"value": location['url'],
                             "meta_data": location['metadata'],
                             "status": location['status'],
                             "deleted": deleted,
                             "updated_at": updated_time,
                             "deleted_at": delete_time})
        location_ref.save(session=session)
    except sa_orm.exc.NoResultFound:
        msg = (_("No location found with ID %(loc)s from image %(img)s") %
               dict(loc=loc_id, img=image_id))
        LOG.warn(msg)
        raise exception.NotFound(msg)


def image_location_delete(context, image_id, location_id, status,
                          delete_time=None, session=None):
    if status not in ('deleted', 'pending_delete'):
        msg = _("The status of deleted image location can only be set to "
                "'pending_delete' or 'deleted'")
        raise exception.Invalid(msg)

    try:
        session = session or get_session()
        location_ref = session.query(models.ImageLocation).filter_by(
            id=location_id).filter_by(image_id=image_id).one()

        delete_time = delete_time or timeutils.utcnow()

        location_ref.update({"deleted": True,
                             "status": status,
                             "updated_at": delete_time,
                             "deleted_at": delete_time})
        location_ref.save(session=session)
    except sa_orm.exc.NoResultFound:
        msg = (_("No location found with ID %(loc)s from image %(img)s") %
               dict(loc=location_id, img=image_id))
        LOG.warn(msg)
        raise exception.NotFound(msg)


def _image_locations_set(context, image_id, locations, session=None):
    # NOTE(zhiyan): 1. Remove records from DB for deleted locations
    session = session or get_session()
    query = session.query(models.ImageLocation).filter_by(
        image_id=image_id).filter_by(deleted=False)

    loc_ids = [loc['id'] for loc in locations if loc.get('id')]
    if loc_ids:
        query = query.filter(~models.ImageLocation.id.in_(loc_ids))

    for loc_id in [loc_ref.id for loc_ref in query.all()]:
        image_location_delete(context, image_id, loc_id, 'deleted',
                              session=session)

    # NOTE(zhiyan): 2. Adding or update locations
    for loc in locations:
        if loc.get('id') is None:
            image_location_add(context, image_id, loc, session=session)
        else:
            image_location_update(context, image_id, loc, session=session)


def _image_locations_delete_all(context, image_id,
                                delete_time=None, session=None):
    """Delete all image locations for given image"""
    session = session or get_session()
    location_refs = session.query(models.ImageLocation).filter_by(
        image_id=image_id).filter_by(deleted=False).all()

    for loc_id in [loc_ref.id for loc_ref in location_refs]:
        image_location_delete(context, image_id, loc_id, 'deleted',
                              delete_time=delete_time, session=session)


@utils.no_4byte_params
def _set_properties_for_image(context, image_ref, properties,
                              purge_props=False, atomic_props=None,
                              session=None):
    """
    Create or update a set of image_properties for a given image

    :param context: Request context
    :param image_ref: An Image object
    :param properties: A dict of properties to set
    :param purge_props: If True, delete properties in the database
                        that are not in properties
    :param atomic_props: If non-None, skip update/create/delete of properties
                         named in this list
    :param session: A SQLAlchemy session to use (if present)
    """

    if atomic_props is None:
        atomic_props = []

    orig_properties = {}
    for prop_ref in image_ref.properties:
        orig_properties[prop_ref.name] = prop_ref

    for name, value in six.iteritems(properties):
        prop_values = {'image_id': image_ref.id,
                       'name': name,
                       'value': value}
        if name in atomic_props:
            # NOTE(danms): Never update or create properties in the list
            # of atomics
            continue
        elif name in orig_properties:
            prop_ref = orig_properties[name]
            _image_property_update(context, prop_ref, prop_values,
                                   session=session)
        else:
            image_property_create(context, prop_values, session=session)

    if purge_props:
        for key in orig_properties.keys():
            if key in atomic_props:
                continue
            elif key not in properties:
                prop_ref = orig_properties[key]
                image_property_delete(context, prop_ref.name,
                                      image_ref.id, session=session)


def _image_child_entry_delete_all(child_model_cls, image_id, delete_time=None,
                                  session=None):
    """Deletes all the child entries for the given image id.

    Deletes all the child entries of the given child entry ORM model class
    using the parent image's id.

    The child entry ORM model class can be one of the following:
    model.ImageLocation, model.ImageProperty, model.ImageMember and
    model.ImageTag.

    :param child_model_cls: the ORM model class.
    :param image_id: id of the image whose child entries are to be deleted.
    :param delete_time: datetime of deletion to be set.
                        If None, uses current datetime.
    :param session: A SQLAlchemy session to use (if present)

    :rtype: int
    :returns: The number of child entries got soft-deleted.
    """
    session = session or get_session()

    query = session.query(child_model_cls).filter_by(
        image_id=image_id).filter_by(deleted=False)

    delete_time = delete_time or timeutils.utcnow()

    count = query.update({"deleted": True, "deleted_at": delete_time})
    return count


def image_property_create(context, values, session=None):
    """Create an ImageProperty object."""
    prop_ref = models.ImageProperty()
    prop = _image_property_update(context, prop_ref, values, session=session)
    return prop.to_dict()


def _image_property_update(context, prop_ref, values, session=None):
    """
    Used internally by image_property_create and image_property_update.
    """
    _drop_protected_attrs(models.ImageProperty, values)
    values["deleted"] = False
    prop_ref.update(values)
    prop_ref.save(session=session)
    return prop_ref


def image_property_delete(context, prop_ref, image_ref, session=None):
    """
    Used internally by _set_properties_for_image().
    """
    session = session or get_session()
    prop = session.query(models.ImageProperty).filter_by(image_id=image_ref,
                                                         name=prop_ref).one()
    try:
        prop.delete(session=session)
    except sa_orm.exc.StaleDataError as e:
        LOG.debug(('StaleDataError while deleting property %(prop)r '
                   'from image %(image)r likely means we raced during delete: '
                   '%(err)s'),
                  {'prop': prop_ref, 'image': image_ref,
                   'err': str(e)})
        return
    return prop


def _image_property_delete_all(context, image_id, delete_time=None,
                               session=None):
    """Delete all image properties for given image"""
    props_updated_count = _image_child_entry_delete_all(models.ImageProperty,
                                                        image_id,
                                                        delete_time,
                                                        session)
    return props_updated_count


@utils.no_4byte_params
def image_member_create(context, values, session=None):
    """Create an ImageMember object."""
    memb_ref = models.ImageMember()
    _image_member_update(context, memb_ref, values, session=session)
    return _image_member_format(memb_ref)


def _image_member_format(member_ref):
    """Format a member ref for consumption outside of this module."""
    return {
        'id': member_ref['id'],
        'image_id': member_ref['image_id'],
        'member': member_ref['member'],
        'can_share': member_ref['can_share'],
        'status': member_ref['status'],
        'created_at': member_ref['created_at'],
        'updated_at': member_ref['updated_at'],
        'deleted': member_ref['deleted']
    }


def image_member_update(context, memb_id, values):
    """Update an ImageMember object."""
    session = get_session()
    memb_ref = _image_member_get(context, memb_id, session)
    _image_member_update(context, memb_ref, values, session)
    return _image_member_format(memb_ref)


def _image_member_update(context, memb_ref, values, session=None):
    """Apply supplied dictionary of values to a Member object."""
    _drop_protected_attrs(models.ImageMember, values)
    values["deleted"] = False
    values.setdefault('can_share', False)
    memb_ref.update(values)
    memb_ref.save(session=session)
    return memb_ref


def image_member_delete(context, memb_id, session=None):
    """Delete an ImageMember object."""
    session = session or get_session()
    member_ref = _image_member_get(context, memb_id, session)
    _image_member_delete(context, member_ref, session)


def _image_member_delete(context, memb_ref, session):
    memb_ref.delete(session=session)


def _image_member_delete_all(context, image_id, delete_time=None,
                             session=None):
    """Delete all image members for given image"""
    members_updated_count = _image_child_entry_delete_all(models.ImageMember,
                                                          image_id,
                                                          delete_time,
                                                          session)
    return members_updated_count


def _image_member_get(context, memb_id, session):
    """Fetch an ImageMember entity by id."""
    query = session.query(models.ImageMember)
    query = query.filter_by(id=memb_id)
    return query.one()


def image_member_find(context, image_id=None, member=None,
                      status=None, include_deleted=False):
    """Find all members that meet the given criteria.

    Note, currently include_deleted should be true only when create a new
    image membership, as there may be a deleted image membership between
    the same image and tenant, the membership will be reused in this case.
    It should be false in other cases.

    :param image_id: identifier of image entity
    :param member: tenant to which membership has been granted
    :include_deleted: A boolean indicating whether the result should include
                      the deleted record of image member
    """
    session = get_session()
    members = _image_member_find(context, session, image_id,
                                 member, status, include_deleted)
    return [_image_member_format(m) for m in members]


def _image_member_find(context, session, image_id=None,
                       member=None, status=None, include_deleted=False):
    query = session.query(models.ImageMember)
    if not include_deleted:
        query = query.filter_by(deleted=False)

    if not context.is_admin:
        query = query.join(models.Image)
        filters = [
            models.Image.owner == context.owner,
            models.ImageMember.member == context.owner,
        ]
        query = query.filter(sa_sql.or_(*filters))

    if image_id is not None:
        query = query.filter(models.ImageMember.image_id == image_id)
    if member is not None:
        query = query.filter(models.ImageMember.member == member)
    if status is not None:
        query = query.filter(models.ImageMember.status == status)

    return query.all()


def image_member_count(context, image_id):
    """Return the number of image members for this image

    :param image_id: identifier of image entity
    """
    session = get_session()

    if not image_id:
        msg = _("Image id is required.")
        raise exception.Invalid(msg)

    query = session.query(models.ImageMember)
    query = query.filter_by(deleted=False)
    query = query.filter(models.ImageMember.image_id == str(image_id))

    return query.count()


def image_tag_set_all(context, image_id, tags):
    # NOTE(kragniz): tag ordering should match exactly what was provided, so a
    # subsequent call to image_tag_get_all returns them in the correct order

    session = get_session()
    existing_tags = image_tag_get_all(context, image_id, session)

    tags_created = []
    for tag in tags:
        if tag not in tags_created and tag not in existing_tags:
            tags_created.append(tag)
            image_tag_create(context, image_id, tag, session)

    for tag in existing_tags:
        if tag not in tags:
            image_tag_delete(context, image_id, tag, session)


@utils.no_4byte_params
def image_tag_create(context, image_id, value, session=None):
    """Create an image tag."""
    session = session or get_session()
    tag_ref = models.ImageTag(image_id=image_id, value=value)
    tag_ref.save(session=session)
    return tag_ref['value']


def image_tag_delete(context, image_id, value, session=None):
    """Delete an image tag."""
    _check_image_id(image_id)
    session = session or get_session()
    query = session.query(models.ImageTag).filter_by(
        image_id=image_id).filter_by(
            value=value).filter_by(deleted=False)
    try:
        tag_ref = query.one()
    except sa_orm.exc.NoResultFound:
        raise exception.NotFound()

    tag_ref.delete(session=session)


def _image_tag_delete_all(context, image_id, delete_time=None, session=None):
    """Delete all image tags for given image"""
    tags_updated_count = _image_child_entry_delete_all(models.ImageTag,
                                                       image_id,
                                                       delete_time,
                                                       session)
    return tags_updated_count


def image_tag_get_all(context, image_id, session=None):
    """Get a list of tags for a specific image."""
    _check_image_id(image_id)
    session = session or get_session()
    tags = session.query(models.ImageTag.value).filter_by(
        image_id=image_id).filter_by(deleted=False).all()
    return [tag[0] for tag in tags]


class DeleteFromSelect(sa_sql.expression.UpdateBase):
    def __init__(self, table, select, column):
        self.table = table
        self.select = select
        self.column = column


# NOTE(abhishekk): MySQL doesn't yet support subquery with
# 'LIMIT & IN/ALL/ANY/SOME' We need work around this with nesting select.
@compiles(DeleteFromSelect)
def visit_delete_from_select(element, compiler, **kw):
    return "DELETE FROM %s WHERE %s in (SELECT T1.%s FROM (%s) as T1)" % (
        compiler.process(element.table, asfrom=True),
        compiler.process(element.column),
        element.column.name,
        compiler.process(element.select))


def purge_deleted_rows(context, age_in_days, max_rows, session=None):
    """Purges soft deleted rows

    Deletes rows of table images, table tasks and all dependent tables
    according to given age for relevant models.
    """
    # check max_rows for its maximum limit
    _validate_db_int(max_rows=max_rows)

    session = session or get_session()
    metadata = MetaData(get_engine())
    deleted_age = timeutils.utcnow() - datetime.timedelta(days=age_in_days)

    tables = []
    for model_class in models.__dict__.values():
        if not hasattr(model_class, '__tablename__'):
            continue
        if hasattr(model_class, 'deleted'):
            tables.append(model_class.__tablename__)

    # First force purging of records that are not soft deleted but
    # are referencing soft deleted tasks/images records (e.g. task_info
    # records). Then purge all soft deleted records in glance tables in the
    # right order to avoid FK constraint violation.
    t = Table("tasks", metadata, autoload=True)
    ti = Table("task_info", metadata, autoload=True)
    joined_rec = ti.join(t, t.c.id == ti.c.task_id)
    deleted_task_info = sql.select([ti.c.task_id],
                                   t.c.deleted_at < deleted_age).\
        select_from(joined_rec).order_by(t.c.deleted_at).limit(max_rows)
    delete_statement = DeleteFromSelect(ti, deleted_task_info,
                                        ti.c.task_id)
    LOG.info(_LI('Purging deleted rows older than %(age_in_days)d day(s) '
                 'from table %(tbl)s'),
             {'age_in_days': age_in_days, 'tbl': ti})
    try:
        with session.begin():
            result = session.execute(delete_statement)
    except (db_exception.DBError, db_exception.DBReferenceError) as ex:
        LOG.exception(_LE('DBError detected when force purging '
                          'table=%(table)s: %(error)s'),
                      {'table': ti, 'error': six.text_type(ex)})
        raise

    rows = result.rowcount
    LOG.info(_LI('Deleted %(rows)d row(s) from table %(tbl)s'),
             {'rows': rows, 'tbl': ti})

    # get rid of FK constraints
    for tbl in ('images', 'tasks'):
        try:
            tables.remove(tbl)
        except ValueError:
            LOG.warning(_LW('Expected table %(tbl)s was not found in DB.'),
                        {'tbl': tbl})
        else:
            # NOTE(abhishekk): To mitigate OSSN-0075 images records should be
            # purged with new ``purge-images-table`` command.
            if tbl == 'images':
                continue

            tables.append(tbl)

    for tbl in tables:
        tab = Table(tbl, metadata, autoload=True)
        LOG.info(
            _LI('Purging deleted rows older than %(age_in_days)d day(s) '
                'from table %(tbl)s'),
            {'age_in_days': age_in_days, 'tbl': tbl})

        column = tab.c.id
        deleted_at_column = tab.c.deleted_at

        query_delete = sql.select(
            [column], deleted_at_column < deleted_age).order_by(
            deleted_at_column).limit(max_rows)

        delete_statement = DeleteFromSelect(tab, query_delete, column)

        try:
            with session.begin():
                result = session.execute(delete_statement)
        except db_exception.DBReferenceError as ex:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE('DBError detected when purging from '
                          "%(tablename)s: %(error)s"),
                          {'tablename': tbl, 'error': six.text_type(ex)})

        rows = result.rowcount
        LOG.info(_LI('Deleted %(rows)d row(s) from table %(tbl)s'),
                 {'rows': rows, 'tbl': tbl})


def purge_deleted_rows_from_images(context, age_in_days, max_rows,
                                   session=None):
    """Purges soft deleted rows

    Deletes rows of table images table according to given age for
    relevant models.
    """
    # check max_rows for its maximum limit
    _validate_db_int(max_rows=max_rows)

    session = session or get_session()
    metadata = MetaData(get_engine())
    deleted_age = timeutils.utcnow() - datetime.timedelta(days=age_in_days)

    tbl = 'images'
    tab = Table(tbl, metadata, autoload=True)
    LOG.info(
        _LI('Purging deleted rows older than %(age_in_days)d day(s) '
            'from table %(tbl)s'),
        {'age_in_days': age_in_days, 'tbl': tbl})

    column = tab.c.id
    deleted_at_column = tab.c.deleted_at

    query_delete = sql.select(
        [column], deleted_at_column < deleted_age).order_by(
        deleted_at_column).limit(max_rows)

    delete_statement = DeleteFromSelect(tab, query_delete, column)

    try:
        with session.begin():
            result = session.execute(delete_statement)
    except db_exception.DBReferenceError as ex:
        with excutils.save_and_reraise_exception():
            LOG.error(_LE('DBError detected when purging from '
                      "%(tablename)s: %(error)s"),
                      {'tablename': tbl, 'error': six.text_type(ex)})

    rows = result.rowcount
    LOG.info(_LI('Deleted %(rows)d row(s) from table %(tbl)s'),
             {'rows': rows, 'tbl': tbl})


def user_get_storage_usage(context, owner_id, image_id=None, session=None):
    _check_image_id(image_id)
    session = session or get_session()
    total_size = _image_get_disk_usage_by_owner(
        owner_id, session, image_id=image_id)
    return total_size


def user_get_staging_usage(context, owner_id, session=None):
    session = session or get_session()
    return _image_get_staging_usage_by_owner(owner_id, session)


def user_get_image_count(context, owner_id, session=None):
    session = session or get_session()
    return _image_get_count_by_owner(owner_id, session)


def user_get_uploading_count(context, owner_id, session=None):
    session = session or get_session()
    return _image_get_uploading_count_by_owner(owner_id, session)


def _task_info_format(task_info_ref):
    """Format a task info ref for consumption outside of this module"""
    if task_info_ref is None:
        return {}
    return {
        'task_id': task_info_ref['task_id'],
        'input': task_info_ref['input'],
        'result': task_info_ref['result'],
        'message': task_info_ref['message'],
    }


def _task_info_create(context, task_id, values, session=None):
    """Create an TaskInfo object"""
    session = session or get_session()
    task_info_ref = models.TaskInfo()
    task_info_ref.task_id = task_id
    task_info_ref.update(values)
    task_info_ref.save(session=session)
    return _task_info_format(task_info_ref)


def _task_info_update(context, task_id, values, session=None):
    """Update an TaskInfo object"""
    session = session or get_session()
    task_info_ref = _task_info_get(context, task_id, session=session)
    if task_info_ref:
        task_info_ref.update(values)
        task_info_ref.save(session=session)
    return _task_info_format(task_info_ref)


def _task_info_get(context, task_id, session=None):
    """Fetch an TaskInfo entity by task_id"""
    session = session or get_session()
    query = session.query(models.TaskInfo)
    query = query.filter_by(task_id=task_id)
    try:
        task_info_ref = query.one()
    except sa_orm.exc.NoResultFound:
        LOG.debug("TaskInfo was not found for task with id %(task_id)s",
                  {'task_id': task_id})
        task_info_ref = None

    return task_info_ref


def task_create(context, values, session=None):
    """Create a task object"""

    values = values.copy()
    session = session or get_session()
    with session.begin():
        task_info_values = _pop_task_info_values(values)

        task_ref = models.Task()
        _task_update(context, task_ref, values, session=session)

        _task_info_create(context,
                          task_ref.id,
                          task_info_values,
                          session=session)

    return task_get(context, task_ref.id, session)


def _pop_task_info_values(values):
    task_info_values = {}
    for k, v in list(values.items()):
        if k in ['input', 'result', 'message']:
            values.pop(k)
            task_info_values[k] = v

    return task_info_values


def task_update(context, task_id, values, session=None):
    """Update a task object"""

    session = session or get_session()

    with session.begin():
        task_info_values = _pop_task_info_values(values)

        task_ref = _task_get(context, task_id, session)
        _drop_protected_attrs(models.Task, values)

        values['updated_at'] = timeutils.utcnow()

        _task_update(context, task_ref, values, session)

        if task_info_values:
            _task_info_update(context,
                              task_id,
                              task_info_values,
                              session)

    return task_get(context, task_id, session)


def task_get(context, task_id, session=None, force_show_deleted=False):
    """Fetch a task entity by id"""
    task_ref = _task_get(context, task_id, session=session,
                         force_show_deleted=force_show_deleted)
    return _task_format(task_ref, task_ref.info)


def tasks_get_by_image(context, image_id, session=None):
    """Fetch all tasks associated with image_id"""
    tasks = []
    session = session or get_session()
    _task_soft_delete(context, session=session)

    query = session.query(models.Task).options(
        sa_orm.joinedload(models.Task.info)
    ).filter_by(image_id=image_id)

    expires_at = models.Task.expires_at
    query = query.filter(sa_sql.or_(expires_at == None,
                                    expires_at >= timeutils.utcnow()))
    updated_at = models.Task.updated_at
    query.filter(
        updated_at <= (timeutils.utcnow() +
                       datetime.timedelta(hours=CONF.task.task_time_to_live)))

    if not context.can_see_deleted:
        query = query.filter_by(deleted=False)

    try:
        task_refs = query.all()
    except sa_orm.exc.NoResultFound:
        LOG.debug("No task found for image with ID %s", image_id)
        return tasks

    for task_ref in task_refs:
        # Make sure the task is visible
        if not _is_task_visible(context, task_ref):
            msg = "Task %s is not visible, excluding" % task_ref.id
            LOG.debug(msg)
            continue
        tasks.append(_task_format(task_ref, task_ref.info))

    return tasks


def task_delete(context, task_id, session=None):
    """Delete a task"""
    session = session or get_session()
    task_ref = _task_get(context, task_id, session=session)
    task_ref.delete(session=session)
    return _task_format(task_ref, task_ref.info)


def _task_soft_delete(context, session=None):
    """Scrub task entities which are expired """
    expires_at = models.Task.expires_at
    session = session or get_session()
    query = session.query(models.Task)

    query = (query.filter(models.Task.owner == context.owner)
                  .filter_by(deleted=False)
                  .filter(expires_at <= timeutils.utcnow()))
    values = {'deleted': True, 'deleted_at': timeutils.utcnow()}

    with session.begin():
        query.update(values)


def task_get_all(context, filters=None, marker=None, limit=None,
                 sort_key='created_at', sort_dir='desc', admin_as_user=False):
    """
    Get all tasks that match zero or more filters.

    :param filters: dict of filter keys and values.
    :param marker: task id after which to start page
    :param limit: maximum number of tasks to return
    :param sort_key: task attribute by which results should be sorted
    :param sort_dir: direction in which results should be sorted (asc, desc)
    :param admin_as_user: For backwards compatibility. If true, then return to
                      an admin the equivalent set of tasks which it would see
                      if it were a regular user
    :returns: tasks set
    """
    filters = filters or {}

    session = get_session()
    query = session.query(models.Task)

    if not (context.is_admin or admin_as_user) and context.owner is not None:
        query = query.filter(models.Task.owner == context.owner)

    _task_soft_delete(context, session=session)

    showing_deleted = False

    if 'deleted' in filters:
        deleted_filter = filters.pop('deleted')
        query = query.filter_by(deleted=deleted_filter)
        showing_deleted = deleted_filter

    for (k, v) in filters.items():
        if v is not None:
            key = k
            if hasattr(models.Task, key):
                query = query.filter(getattr(models.Task, key) == v)

    marker_task = None
    if marker is not None:
        marker_task = _task_get(context, marker,
                                force_show_deleted=showing_deleted)

    sort_keys = ['created_at', 'id']
    if sort_key not in sort_keys:
        sort_keys.insert(0, sort_key)

    query = _paginate_query(query, models.Task, limit,
                            sort_keys,
                            marker=marker_task,
                            sort_dir=sort_dir)

    task_refs = query.all()

    tasks = []
    for task_ref in task_refs:
        tasks.append(_task_format(task_ref, task_info_ref=None))

    return tasks


def _is_task_visible(context, task):
    """Return True if the task is visible in this context."""
    # Is admin == task visible
    if context.is_admin:
        return True

    # No owner == task visible
    if task['owner'] is None:
        return True

    # Perform tests based on whether we have an owner
    if context.owner is not None:
        if context.owner == task['owner']:
            return True

    return False


def _task_get(context, task_id, session=None, force_show_deleted=False):
    """Fetch a task entity by id"""
    session = session or get_session()
    query = session.query(models.Task).options(
        sa_orm.joinedload(models.Task.info)
    ).filter_by(id=task_id)

    if not force_show_deleted and not context.can_see_deleted:
        query = query.filter_by(deleted=False)
    try:
        task_ref = query.one()
    except sa_orm.exc.NoResultFound:
        LOG.debug("No task found with ID %s", task_id)
        raise exception.TaskNotFound(task_id=task_id)

    # Make sure the task is visible
    if not _is_task_visible(context, task_ref):
        msg = "Forbidding request, task %s is not visible" % task_id
        LOG.debug(msg)
        raise exception.Forbidden(msg)

    return task_ref


def _task_update(context, task_ref, values, session=None):
    """Apply supplied dictionary of values to a task object."""
    if 'deleted' not in values:
        values["deleted"] = False
    task_ref.update(values)
    task_ref.save(session=session)
    return task_ref


def _task_format(task_ref, task_info_ref=None):
    """Format a task ref for consumption outside of this module"""
    task_dict = {
        'id': task_ref['id'],
        'type': task_ref['type'],
        'status': task_ref['status'],
        'owner': task_ref['owner'],
        'expires_at': task_ref['expires_at'],
        'created_at': task_ref['created_at'],
        'updated_at': task_ref['updated_at'],
        'deleted_at': task_ref['deleted_at'],
        'deleted': task_ref['deleted'],
        'image_id': task_ref['image_id'],
        'request_id': task_ref['request_id'],
        'user_id': task_ref['user_id'],
    }

    if task_info_ref:
        task_info_dict = {
            'input': task_info_ref['input'],
            'result': task_info_ref['result'],
            'message': task_info_ref['message'],
        }
        task_dict.update(task_info_dict)

    return task_dict


def metadef_namespace_get_all(context, marker=None, limit=None, sort_key=None,
                              sort_dir=None, filters=None, session=None):
    """List all available namespaces."""
    session = session or get_session()
    namespaces = metadef_namespace_api.get_all(
        context, session, marker, limit, sort_key, sort_dir, filters)
    return namespaces


def metadef_namespace_get(context, namespace_name, session=None):
    """Get a namespace or raise if it does not exist or is not visible."""
    session = session or get_session()
    return metadef_namespace_api.get(
        context, namespace_name, session)


@utils.no_4byte_params
def metadef_namespace_create(context, values, session=None):
    """Create a namespace or raise if it already exists."""
    session = session or get_session()
    return metadef_namespace_api.create(context, values, session)


@utils.no_4byte_params
def metadef_namespace_update(context, namespace_id, namespace_dict,
                             session=None):
    """Update a namespace or raise if it does not exist or not visible"""
    session = session or get_session()
    return metadef_namespace_api.update(
        context, namespace_id, namespace_dict, session)


def metadef_namespace_delete(context, namespace_name, session=None):
    """Delete the namespace and all foreign references"""
    session = session or get_session()
    return metadef_namespace_api.delete_cascade(
        context, namespace_name, session)


def metadef_object_get_all(context, namespace_name, session=None):
    """Get a metadata-schema object or raise if it does not exist."""
    session = session or get_session()
    return metadef_object_api.get_all(
        context, namespace_name, session)


def metadef_object_get(context, namespace_name, object_name, session=None):
    """Get a metadata-schema object or raise if it does not exist."""
    session = session or get_session()
    return metadef_object_api.get(
        context, namespace_name, object_name, session)


@utils.no_4byte_params
def metadef_object_create(context, namespace_name, object_dict,
                          session=None):
    """Create a metadata-schema object or raise if it already exists."""
    session = session or get_session()
    return metadef_object_api.create(
        context, namespace_name, object_dict, session)


@utils.no_4byte_params
def metadef_object_update(context, namespace_name, object_id, object_dict,
                          session=None):
    """Update an object or raise if it does not exist or not visible."""
    session = session or get_session()
    return metadef_object_api.update(
        context, namespace_name, object_id, object_dict, session)


def metadef_object_delete(context, namespace_name, object_name,
                          session=None):
    """Delete an object or raise if namespace or object doesn't exist."""
    session = session or get_session()
    return metadef_object_api.delete(
        context, namespace_name, object_name, session)


def metadef_object_delete_namespace_content(
        context, namespace_name, session=None):
    """Delete an object or raise if namespace or object doesn't exist."""
    session = session or get_session()
    return metadef_object_api.delete_by_namespace_name(
        context, namespace_name, session)


def metadef_object_count(context, namespace_name, session=None):
    """Get count of properties for a namespace, raise if ns doesn't exist."""
    session = session or get_session()
    return metadef_object_api.count(context, namespace_name, session)


def metadef_property_get_all(context, namespace_name, session=None):
    """Get a metadef property or raise if it does not exist."""
    session = session or get_session()
    return metadef_property_api.get_all(context, namespace_name, session)


def metadef_property_get(context, namespace_name,
                         property_name, session=None):
    """Get a metadef property or raise if it does not exist."""
    session = session or get_session()
    return metadef_property_api.get(
        context, namespace_name, property_name, session)


@utils.no_4byte_params
def metadef_property_create(context, namespace_name, property_dict,
                            session=None):
    """Create a metadef property or raise if it already exists."""
    session = session or get_session()
    return metadef_property_api.create(
        context, namespace_name, property_dict, session)


@utils.no_4byte_params
def metadef_property_update(context, namespace_name, property_id,
                            property_dict, session=None):
    """Update an object or raise if it does not exist or not visible."""
    session = session or get_session()
    return metadef_property_api.update(
        context, namespace_name, property_id, property_dict, session)


def metadef_property_delete(context, namespace_name, property_name,
                            session=None):
    """Delete a property or raise if it or namespace doesn't exist."""
    session = session or get_session()
    return metadef_property_api.delete(
        context, namespace_name, property_name, session)


def metadef_property_delete_namespace_content(
        context, namespace_name, session=None):
    """Delete a property or raise if it or namespace doesn't exist."""
    session = session or get_session()
    return metadef_property_api.delete_by_namespace_name(
        context, namespace_name, session)


def metadef_property_count(context, namespace_name, session=None):
    """Get count of properties for a namespace, raise if ns doesn't exist."""
    session = session or get_session()
    return metadef_property_api.count(context, namespace_name, session)


def metadef_resource_type_create(context, values, session=None):
    """Create a resource_type"""
    session = session or get_session()
    return metadef_resource_type_api.create(
        context, values, session)


def metadef_resource_type_get(context, resource_type_name, session=None):
    """Get a resource_type"""
    session = session or get_session()
    return metadef_resource_type_api.get(
        context, resource_type_name, session)


def metadef_resource_type_get_all(context, session=None):
    """list all resource_types"""
    session = session or get_session()
    return metadef_resource_type_api.get_all(context, session)


def metadef_resource_type_delete(context, resource_type_name, session=None):
    """Get a resource_type"""
    session = session or get_session()
    return metadef_resource_type_api.delete(
        context, resource_type_name, session)


def metadef_resource_type_association_get(
        context, namespace_name, resource_type_name, session=None):
    session = session or get_session()
    return metadef_association_api.get(
        context, namespace_name, resource_type_name, session)


def metadef_resource_type_association_create(
        context, namespace_name, values, session=None):
    session = session or get_session()
    return metadef_association_api.create(
        context, namespace_name, values, session)


def metadef_resource_type_association_delete(
        context, namespace_name, resource_type_name, session=None):
    session = session or get_session()
    return metadef_association_api.delete(
        context, namespace_name, resource_type_name, session)


def metadef_resource_type_association_get_all_by_namespace(
        context, namespace_name, session=None):
    session = session or get_session()
    return metadef_association_api.get_all_by_namespace(
        context, namespace_name, session)


def metadef_tag_get_all(
        context, namespace_name, filters=None, marker=None, limit=None,
        sort_key=None, sort_dir=None, session=None):
    """Get metadata-schema tags or raise if none exist."""
    session = session or get_session()
    return metadef_tag_api.get_all(
        context, namespace_name, session,
        filters, marker, limit, sort_key, sort_dir)


def metadef_tag_get(context, namespace_name, name, session=None):
    """Get a metadata-schema tag or raise if it does not exist."""
    session = session or get_session()
    return metadef_tag_api.get(
        context, namespace_name, name, session)


@utils.no_4byte_params
def metadef_tag_create(context, namespace_name, tag_dict,
                       session=None):
    """Create a metadata-schema tag or raise if it already exists."""
    session = session or get_session()
    return metadef_tag_api.create(
        context, namespace_name, tag_dict, session)


def metadef_tag_create_tags(context, namespace_name, tag_list,
                            session=None):
    """Create a metadata-schema tag or raise if it already exists."""
    session = get_session()
    return metadef_tag_api.create_tags(
        context, namespace_name, tag_list, session)


@utils.no_4byte_params
def metadef_tag_update(context, namespace_name, id, tag_dict,
                       session=None):
    """Update an tag or raise if it does not exist or not visible."""
    session = session or get_session()
    return metadef_tag_api.update(
        context, namespace_name, id, tag_dict, session)


def metadef_tag_delete(context, namespace_name, name,
                       session=None):
    """Delete an tag or raise if namespace or tag doesn't exist."""
    session = session or get_session()
    return metadef_tag_api.delete(
        context, namespace_name, name, session)


def metadef_tag_delete_namespace_content(
        context, namespace_name, session=None):
    """Delete an tag or raise if namespace or tag doesn't exist."""
    session = session or get_session()
    return metadef_tag_api.delete_by_namespace_name(
        context, namespace_name, session)


def metadef_tag_count(context, namespace_name, session=None):
    """Get count of tags for a namespace, raise if ns doesn't exist."""
    session = session or get_session()
    return metadef_tag_api.count(context, namespace_name, session)